]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
update
[l4.git] / l4 / pkg / sqlite / lib / contrib / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.15.  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"
677 #define SQLITE_VERSION_NUMBER 3007015
678 #define SQLITE_SOURCE_ID      "2012-12-12 13:36:53 cd0b37c52658bfdf992b1e3dc467bae1835a94ae"
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 global.c ******************************************/
12414 /*
12415 ** 2008 June 13
12416 **
12417 ** The author disclaims copyright to this source code.  In place of
12418 ** a legal notice, here is a blessing:
12419 **
12420 **    May you do good and not evil.
12421 **    May you find forgiveness for yourself and forgive others.
12422 **    May you share freely, never taking more than you give.
12423 **
12424 *************************************************************************
12425 **
12426 ** This file contains definitions of global variables and contants.
12427 */
12428
12429 /* An array to map all upper-case characters into their corresponding
12430 ** lower-case character. 
12431 **
12432 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12433 ** handle case conversions for the UTF character set since the tables
12434 ** involved are nearly as big or bigger than SQLite itself.
12435 */
12436 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12437 #ifdef SQLITE_ASCII
12438       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12439      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12440      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12441      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12442     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12443     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12444     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12445     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12446     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12447     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12448     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12449     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12450     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12451     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12452     252,253,254,255
12453 #endif
12454 #ifdef SQLITE_EBCDIC
12455       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12456      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12457      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12458      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12459      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12460      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12461      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12462     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12463     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12464     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12465     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12466     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12467     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12468     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12469     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12470     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12471 #endif
12472 };
12473
12474 /*
12475 ** The following 256 byte lookup table is used to support SQLites built-in
12476 ** equivalents to the following standard library functions:
12477 **
12478 **   isspace()                        0x01
12479 **   isalpha()                        0x02
12480 **   isdigit()                        0x04
12481 **   isalnum()                        0x06
12482 **   isxdigit()                       0x08
12483 **   toupper()                        0x20
12484 **   SQLite identifier character      0x40
12485 **
12486 ** Bit 0x20 is set if the mapped character requires translation to upper
12487 ** case. i.e. if the character is a lower-case ASCII character.
12488 ** If x is a lower-case ASCII character, then its upper-case equivalent
12489 ** is (x - 0x20). Therefore toupper() can be implemented as:
12490 **
12491 **   (x & ~(map[x]&0x20))
12492 **
12493 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12494 ** array. tolower() is used more often than toupper() by SQLite.
12495 **
12496 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12497 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12498 ** non-ASCII UTF character. Hence the test for whether or not a character is
12499 ** part of an identifier is 0x46.
12500 **
12501 ** SQLite's versions are identical to the standard versions assuming a
12502 ** locale of "C". They are implemented as macros in sqliteInt.h.
12503 */
12504 #ifdef SQLITE_ASCII
12505 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12506   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12507   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12508   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12509   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12510   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12511   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12512   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12513   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12514
12515   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12516   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12517   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12518   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12519   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12520   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12521   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12522   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12523
12524   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12525   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12526   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12527   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12528   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12529   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12530   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12531   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12532
12533   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12534   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12535   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12536   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12537   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12538   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12539   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12540   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12541 };
12542 #endif
12543
12544 #ifndef SQLITE_USE_URI
12545 # define  SQLITE_USE_URI 0
12546 #endif
12547
12548 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12549 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12550 #endif
12551
12552 /*
12553 ** The following singleton contains the global configuration for
12554 ** the SQLite library.
12555 */
12556 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12557    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12558    1,                         /* bCoreMutex */
12559    SQLITE_THREADSAFE==1,      /* bFullMutex */
12560    SQLITE_USE_URI,            /* bOpenUri */
12561    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12562    0x7ffffffe,                /* mxStrlen */
12563    128,                       /* szLookaside */
12564    500,                       /* nLookaside */
12565    {0,0,0,0,0,0,0,0},         /* m */
12566    {0,0,0,0,0,0,0,0,0},       /* mutex */
12567    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12568    (void*)0,                  /* pHeap */
12569    0,                         /* nHeap */
12570    0, 0,                      /* mnHeap, mxHeap */
12571    (void*)0,                  /* pScratch */
12572    0,                         /* szScratch */
12573    0,                         /* nScratch */
12574    (void*)0,                  /* pPage */
12575    0,                         /* szPage */
12576    0,                         /* nPage */
12577    0,                         /* mxParserStack */
12578    0,                         /* sharedCacheEnabled */
12579    /* All the rest should always be initialized to zero */
12580    0,                         /* isInit */
12581    0,                         /* inProgress */
12582    0,                         /* isMutexInit */
12583    0,                         /* isMallocInit */
12584    0,                         /* isPCacheInit */
12585    0,                         /* pInitMutex */
12586    0,                         /* nRefInitMutex */
12587    0,                         /* xLog */
12588    0,                         /* pLogArg */
12589    0,                         /* bLocaltimeFault */
12590 #ifdef SQLITE_ENABLE_SQLLOG
12591    0,                         /* xSqllog */
12592    0                          /* pSqllogArg */
12593 #endif
12594 };
12595
12596
12597 /*
12598 ** Hash table for global functions - functions common to all
12599 ** database connections.  After initialization, this table is
12600 ** read-only.
12601 */
12602 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12603
12604 /*
12605 ** Constant tokens for values 0 and 1.
12606 */
12607 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12608    { "0", 1 },
12609    { "1", 1 }
12610 };
12611
12612
12613 /*
12614 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12615 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12616 ** the database page that contains the pending byte.  It never attempts
12617 ** to read or write that page.  The pending byte page is set assign
12618 ** for use by the VFS layers as space for managing file locks.
12619 **
12620 ** During testing, it is often desirable to move the pending byte to
12621 ** a different position in the file.  This allows code that has to
12622 ** deal with the pending byte to run on files that are much smaller
12623 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12624 ** move the pending byte.
12625 **
12626 ** IMPORTANT:  Changing the pending byte to any value other than
12627 ** 0x40000000 results in an incompatible database file format!
12628 ** Changing the pending byte during operating results in undefined
12629 ** and dileterious behavior.
12630 */
12631 #ifndef SQLITE_OMIT_WSD
12632 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12633 #endif
12634
12635 /*
12636 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12637 ** created by mkopcodeh.awk during compilation.  Data is obtained
12638 ** from the comments following the "case OP_xxxx:" statements in
12639 ** the vdbe.c file.  
12640 */
12641 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12642
12643 /************** End of global.c **********************************************/
12644 /************** Begin file ctime.c *******************************************/
12645 /*
12646 ** 2010 February 23
12647 **
12648 ** The author disclaims copyright to this source code.  In place of
12649 ** a legal notice, here is a blessing:
12650 **
12651 **    May you do good and not evil.
12652 **    May you find forgiveness for yourself and forgive others.
12653 **    May you share freely, never taking more than you give.
12654 **
12655 *************************************************************************
12656 **
12657 ** This file implements routines used to report what compile-time options
12658 ** SQLite was built with.
12659 */
12660
12661 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12662
12663
12664 /*
12665 ** An array of names of all compile-time options.  This array should 
12666 ** be sorted A-Z.
12667 **
12668 ** This array looks large, but in a typical installation actually uses
12669 ** only a handful of compile-time options, so most times this array is usually
12670 ** rather short and uses little memory space.
12671 */
12672 static const char * const azCompileOpt[] = {
12673
12674 /* These macros are provided to "stringify" the value of the define
12675 ** for those options in which the value is meaningful. */
12676 #define CTIMEOPT_VAL_(opt) #opt
12677 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12678
12679 #ifdef SQLITE_32BIT_ROWID
12680   "32BIT_ROWID",
12681 #endif
12682 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12683   "4_BYTE_ALIGNED_MALLOC",
12684 #endif
12685 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12686   "CASE_SENSITIVE_LIKE",
12687 #endif
12688 #ifdef SQLITE_CHECK_PAGES
12689   "CHECK_PAGES",
12690 #endif
12691 #ifdef SQLITE_COVERAGE_TEST
12692   "COVERAGE_TEST",
12693 #endif
12694 #ifdef SQLITE_CURDIR
12695   "CURDIR",
12696 #endif
12697 #ifdef SQLITE_DEBUG
12698   "DEBUG",
12699 #endif
12700 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12701   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12702 #endif
12703 #ifdef SQLITE_DISABLE_DIRSYNC
12704   "DISABLE_DIRSYNC",
12705 #endif
12706 #ifdef SQLITE_DISABLE_LFS
12707   "DISABLE_LFS",
12708 #endif
12709 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12710   "ENABLE_ATOMIC_WRITE",
12711 #endif
12712 #ifdef SQLITE_ENABLE_CEROD
12713   "ENABLE_CEROD",
12714 #endif
12715 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12716   "ENABLE_COLUMN_METADATA",
12717 #endif
12718 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12719   "ENABLE_EXPENSIVE_ASSERT",
12720 #endif
12721 #ifdef SQLITE_ENABLE_FTS1
12722   "ENABLE_FTS1",
12723 #endif
12724 #ifdef SQLITE_ENABLE_FTS2
12725   "ENABLE_FTS2",
12726 #endif
12727 #ifdef SQLITE_ENABLE_FTS3
12728   "ENABLE_FTS3",
12729 #endif
12730 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12731   "ENABLE_FTS3_PARENTHESIS",
12732 #endif
12733 #ifdef SQLITE_ENABLE_FTS4
12734   "ENABLE_FTS4",
12735 #endif
12736 #ifdef SQLITE_ENABLE_ICU
12737   "ENABLE_ICU",
12738 #endif
12739 #ifdef SQLITE_ENABLE_IOTRACE
12740   "ENABLE_IOTRACE",
12741 #endif
12742 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12743   "ENABLE_LOAD_EXTENSION",
12744 #endif
12745 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12746   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12747 #endif
12748 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12749   "ENABLE_MEMORY_MANAGEMENT",
12750 #endif
12751 #ifdef SQLITE_ENABLE_MEMSYS3
12752   "ENABLE_MEMSYS3",
12753 #endif
12754 #ifdef SQLITE_ENABLE_MEMSYS5
12755   "ENABLE_MEMSYS5",
12756 #endif
12757 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12758   "ENABLE_OVERSIZE_CELL_CHECK",
12759 #endif
12760 #ifdef SQLITE_ENABLE_RTREE
12761   "ENABLE_RTREE",
12762 #endif
12763 #ifdef SQLITE_ENABLE_STAT3
12764   "ENABLE_STAT3",
12765 #endif
12766 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12767   "ENABLE_UNLOCK_NOTIFY",
12768 #endif
12769 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12770   "ENABLE_UPDATE_DELETE_LIMIT",
12771 #endif
12772 #ifdef SQLITE_HAS_CODEC
12773   "HAS_CODEC",
12774 #endif
12775 #ifdef SQLITE_HAVE_ISNAN
12776   "HAVE_ISNAN",
12777 #endif
12778 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12779   "HOMEGROWN_RECURSIVE_MUTEX",
12780 #endif
12781 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12782   "IGNORE_AFP_LOCK_ERRORS",
12783 #endif
12784 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12785   "IGNORE_FLOCK_LOCK_ERRORS",
12786 #endif
12787 #ifdef SQLITE_INT64_TYPE
12788   "INT64_TYPE",
12789 #endif
12790 #ifdef SQLITE_LOCK_TRACE
12791   "LOCK_TRACE",
12792 #endif
12793 #ifdef SQLITE_MAX_SCHEMA_RETRY
12794   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12795 #endif
12796 #ifdef SQLITE_MEMDEBUG
12797   "MEMDEBUG",
12798 #endif
12799 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12800   "MIXED_ENDIAN_64BIT_FLOAT",
12801 #endif
12802 #ifdef SQLITE_NO_SYNC
12803   "NO_SYNC",
12804 #endif
12805 #ifdef SQLITE_OMIT_ALTERTABLE
12806   "OMIT_ALTERTABLE",
12807 #endif
12808 #ifdef SQLITE_OMIT_ANALYZE
12809   "OMIT_ANALYZE",
12810 #endif
12811 #ifdef SQLITE_OMIT_ATTACH
12812   "OMIT_ATTACH",
12813 #endif
12814 #ifdef SQLITE_OMIT_AUTHORIZATION
12815   "OMIT_AUTHORIZATION",
12816 #endif
12817 #ifdef SQLITE_OMIT_AUTOINCREMENT
12818   "OMIT_AUTOINCREMENT",
12819 #endif
12820 #ifdef SQLITE_OMIT_AUTOINIT
12821   "OMIT_AUTOINIT",
12822 #endif
12823 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12824   "OMIT_AUTOMATIC_INDEX",
12825 #endif
12826 #ifdef SQLITE_OMIT_AUTORESET
12827   "OMIT_AUTORESET",
12828 #endif
12829 #ifdef SQLITE_OMIT_AUTOVACUUM
12830   "OMIT_AUTOVACUUM",
12831 #endif
12832 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12833   "OMIT_BETWEEN_OPTIMIZATION",
12834 #endif
12835 #ifdef SQLITE_OMIT_BLOB_LITERAL
12836   "OMIT_BLOB_LITERAL",
12837 #endif
12838 #ifdef SQLITE_OMIT_BTREECOUNT
12839   "OMIT_BTREECOUNT",
12840 #endif
12841 #ifdef SQLITE_OMIT_BUILTIN_TEST
12842   "OMIT_BUILTIN_TEST",
12843 #endif
12844 #ifdef SQLITE_OMIT_CAST
12845   "OMIT_CAST",
12846 #endif
12847 #ifdef SQLITE_OMIT_CHECK
12848   "OMIT_CHECK",
12849 #endif
12850 /* // redundant
12851 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12852 **   "OMIT_COMPILEOPTION_DIAGS",
12853 ** #endif
12854 */
12855 #ifdef SQLITE_OMIT_COMPLETE
12856   "OMIT_COMPLETE",
12857 #endif
12858 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12859   "OMIT_COMPOUND_SELECT",
12860 #endif
12861 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12862   "OMIT_DATETIME_FUNCS",
12863 #endif
12864 #ifdef SQLITE_OMIT_DECLTYPE
12865   "OMIT_DECLTYPE",
12866 #endif
12867 #ifdef SQLITE_OMIT_DEPRECATED
12868   "OMIT_DEPRECATED",
12869 #endif
12870 #ifdef SQLITE_OMIT_DISKIO
12871   "OMIT_DISKIO",
12872 #endif
12873 #ifdef SQLITE_OMIT_EXPLAIN
12874   "OMIT_EXPLAIN",
12875 #endif
12876 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12877   "OMIT_FLAG_PRAGMAS",
12878 #endif
12879 #ifdef SQLITE_OMIT_FLOATING_POINT
12880   "OMIT_FLOATING_POINT",
12881 #endif
12882 #ifdef SQLITE_OMIT_FOREIGN_KEY
12883   "OMIT_FOREIGN_KEY",
12884 #endif
12885 #ifdef SQLITE_OMIT_GET_TABLE
12886   "OMIT_GET_TABLE",
12887 #endif
12888 #ifdef SQLITE_OMIT_INCRBLOB
12889   "OMIT_INCRBLOB",
12890 #endif
12891 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12892   "OMIT_INTEGRITY_CHECK",
12893 #endif
12894 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12895   "OMIT_LIKE_OPTIMIZATION",
12896 #endif
12897 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12898   "OMIT_LOAD_EXTENSION",
12899 #endif
12900 #ifdef SQLITE_OMIT_LOCALTIME
12901   "OMIT_LOCALTIME",
12902 #endif
12903 #ifdef SQLITE_OMIT_LOOKASIDE
12904   "OMIT_LOOKASIDE",
12905 #endif
12906 #ifdef SQLITE_OMIT_MEMORYDB
12907   "OMIT_MEMORYDB",
12908 #endif
12909 #ifdef SQLITE_OMIT_MERGE_SORT
12910   "OMIT_MERGE_SORT",
12911 #endif
12912 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12913   "OMIT_OR_OPTIMIZATION",
12914 #endif
12915 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12916   "OMIT_PAGER_PRAGMAS",
12917 #endif
12918 #ifdef SQLITE_OMIT_PRAGMA
12919   "OMIT_PRAGMA",
12920 #endif
12921 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12922   "OMIT_PROGRESS_CALLBACK",
12923 #endif
12924 #ifdef SQLITE_OMIT_QUICKBALANCE
12925   "OMIT_QUICKBALANCE",
12926 #endif
12927 #ifdef SQLITE_OMIT_REINDEX
12928   "OMIT_REINDEX",
12929 #endif
12930 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12931   "OMIT_SCHEMA_PRAGMAS",
12932 #endif
12933 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12934   "OMIT_SCHEMA_VERSION_PRAGMAS",
12935 #endif
12936 #ifdef SQLITE_OMIT_SHARED_CACHE
12937   "OMIT_SHARED_CACHE",
12938 #endif
12939 #ifdef SQLITE_OMIT_SUBQUERY
12940   "OMIT_SUBQUERY",
12941 #endif
12942 #ifdef SQLITE_OMIT_TCL_VARIABLE
12943   "OMIT_TCL_VARIABLE",
12944 #endif
12945 #ifdef SQLITE_OMIT_TEMPDB
12946   "OMIT_TEMPDB",
12947 #endif
12948 #ifdef SQLITE_OMIT_TRACE
12949   "OMIT_TRACE",
12950 #endif
12951 #ifdef SQLITE_OMIT_TRIGGER
12952   "OMIT_TRIGGER",
12953 #endif
12954 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12955   "OMIT_TRUNCATE_OPTIMIZATION",
12956 #endif
12957 #ifdef SQLITE_OMIT_UTF16
12958   "OMIT_UTF16",
12959 #endif
12960 #ifdef SQLITE_OMIT_VACUUM
12961   "OMIT_VACUUM",
12962 #endif
12963 #ifdef SQLITE_OMIT_VIEW
12964   "OMIT_VIEW",
12965 #endif
12966 #ifdef SQLITE_OMIT_VIRTUALTABLE
12967   "OMIT_VIRTUALTABLE",
12968 #endif
12969 #ifdef SQLITE_OMIT_WAL
12970   "OMIT_WAL",
12971 #endif
12972 #ifdef SQLITE_OMIT_WSD
12973   "OMIT_WSD",
12974 #endif
12975 #ifdef SQLITE_OMIT_XFER_OPT
12976   "OMIT_XFER_OPT",
12977 #endif
12978 #ifdef SQLITE_PERFORMANCE_TRACE
12979   "PERFORMANCE_TRACE",
12980 #endif
12981 #ifdef SQLITE_PROXY_DEBUG
12982   "PROXY_DEBUG",
12983 #endif
12984 #ifdef SQLITE_RTREE_INT_ONLY
12985   "RTREE_INT_ONLY",
12986 #endif
12987 #ifdef SQLITE_SECURE_DELETE
12988   "SECURE_DELETE",
12989 #endif
12990 #ifdef SQLITE_SMALL_STACK
12991   "SMALL_STACK",
12992 #endif
12993 #ifdef SQLITE_SOUNDEX
12994   "SOUNDEX",
12995 #endif
12996 #ifdef SQLITE_TCL
12997   "TCL",
12998 #endif
12999 #ifdef SQLITE_TEMP_STORE
13000   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13001 #endif
13002 #ifdef SQLITE_TEST
13003   "TEST",
13004 #endif
13005 #ifdef SQLITE_THREADSAFE
13006   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13007 #endif
13008 #ifdef SQLITE_USE_ALLOCA
13009   "USE_ALLOCA",
13010 #endif
13011 #ifdef SQLITE_ZERO_MALLOC
13012   "ZERO_MALLOC"
13013 #endif
13014 };
13015
13016 /*
13017 ** Given the name of a compile-time option, return true if that option
13018 ** was used and false if not.
13019 **
13020 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13021 ** is not required for a match.
13022 */
13023 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13024   int i, n;
13025   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13026   n = sqlite3Strlen30(zOptName);
13027
13028   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13029   ** linear search is adequate.  No need for a binary search. */
13030   for(i=0; i<ArraySize(azCompileOpt); i++){
13031     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
13032        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
13033   }
13034   return 0;
13035 }
13036
13037 /*
13038 ** Return the N-th compile-time option string.  If N is out of range,
13039 ** return a NULL pointer.
13040 */
13041 SQLITE_API const char *sqlite3_compileoption_get(int N){
13042   if( N>=0 && N<ArraySize(azCompileOpt) ){
13043     return azCompileOpt[N];
13044   }
13045   return 0;
13046 }
13047
13048 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13049
13050 /************** End of ctime.c ***********************************************/
13051 /************** Begin file status.c ******************************************/
13052 /*
13053 ** 2008 June 18
13054 **
13055 ** The author disclaims copyright to this source code.  In place of
13056 ** a legal notice, here is a blessing:
13057 **
13058 **    May you do good and not evil.
13059 **    May you find forgiveness for yourself and forgive others.
13060 **    May you share freely, never taking more than you give.
13061 **
13062 *************************************************************************
13063 **
13064 ** This module implements the sqlite3_status() interface and related
13065 ** functionality.
13066 */
13067 /************** Include vdbeInt.h in the middle of status.c ******************/
13068 /************** Begin file vdbeInt.h *****************************************/
13069 /*
13070 ** 2003 September 6
13071 **
13072 ** The author disclaims copyright to this source code.  In place of
13073 ** a legal notice, here is a blessing:
13074 **
13075 **    May you do good and not evil.
13076 **    May you find forgiveness for yourself and forgive others.
13077 **    May you share freely, never taking more than you give.
13078 **
13079 *************************************************************************
13080 ** This is the header file for information that is private to the
13081 ** VDBE.  This information used to all be at the top of the single
13082 ** source code file "vdbe.c".  When that file became too big (over
13083 ** 6000 lines long) it was split up into several smaller files and
13084 ** this header information was factored out.
13085 */
13086 #ifndef _VDBEINT_H_
13087 #define _VDBEINT_H_
13088
13089 /*
13090 ** SQL is translated into a sequence of instructions to be
13091 ** executed by a virtual machine.  Each instruction is an instance
13092 ** of the following structure.
13093 */
13094 typedef struct VdbeOp Op;
13095
13096 /*
13097 ** Boolean values
13098 */
13099 typedef unsigned char Bool;
13100
13101 /* Opaque type used by code in vdbesort.c */
13102 typedef struct VdbeSorter VdbeSorter;
13103
13104 /* Opaque type used by the explainer */
13105 typedef struct Explain Explain;
13106
13107 /*
13108 ** A cursor is a pointer into a single BTree within a database file.
13109 ** The cursor can seek to a BTree entry with a particular key, or
13110 ** loop over all entries of the Btree.  You can also insert new BTree
13111 ** entries or retrieve the key or data from the entry that the cursor
13112 ** is currently pointing to.
13113 ** 
13114 ** Every cursor that the virtual machine has open is represented by an
13115 ** instance of the following structure.
13116 */
13117 struct VdbeCursor {
13118   BtCursor *pCursor;    /* The cursor structure of the backend */
13119   Btree *pBt;           /* Separate file holding temporary table */
13120   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13121   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13122   int pseudoTableReg;   /* Register holding pseudotable content. */
13123   int nField;           /* Number of fields in the header */
13124   Bool zeroed;          /* True if zeroed out and ready for reuse */
13125   Bool rowidIsValid;    /* True if lastRowid is valid */
13126   Bool atFirst;         /* True if pointing to first entry */
13127   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13128   Bool nullRow;         /* True if pointing to a row with no data */
13129   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13130   Bool isTable;         /* True if a table requiring integer keys */
13131   Bool isIndex;         /* True if an index containing keys only - no data */
13132   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13133   Bool isSorter;        /* True if a new-style sorter */
13134   Bool multiPseudo;     /* Multi-register pseudo-cursor */
13135   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13136   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13137   i64 seqCount;         /* Sequence counter */
13138   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13139   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13140   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13141
13142   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
13143   ** OP_IsUnique opcode on this cursor. */
13144   int seekResult;
13145
13146   /* Cached information about the header for the data record that the
13147   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13148   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13149   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13150   ** the cache is out of date.
13151   **
13152   ** aRow might point to (ephemeral) data for the current row, or it might
13153   ** be NULL.
13154   */
13155   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13156   int payloadSize;      /* Total number of bytes in the record */
13157   u32 *aType;           /* Type values for all entries in the record */
13158   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13159   u8 *aRow;             /* Data for the current row, if all on one page */
13160 };
13161 typedef struct VdbeCursor VdbeCursor;
13162
13163 /*
13164 ** When a sub-program is executed (OP_Program), a structure of this type
13165 ** is allocated to store the current value of the program counter, as
13166 ** well as the current memory cell array and various other frame specific
13167 ** values stored in the Vdbe struct. When the sub-program is finished, 
13168 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13169 ** restoring the state of the VM to as it was before the sub-program
13170 ** began executing.
13171 **
13172 ** The memory for a VdbeFrame object is allocated and managed by a memory
13173 ** cell in the parent (calling) frame. When the memory cell is deleted or
13174 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13175 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13176 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13177 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13178 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13179 ** child frame are released.
13180 **
13181 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13182 ** set to NULL if the currently executing frame is the main program.
13183 */
13184 typedef struct VdbeFrame VdbeFrame;
13185 struct VdbeFrame {
13186   Vdbe *v;                /* VM this frame belongs to */
13187   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13188   Op *aOp;                /* Program instructions for parent frame */
13189   Mem *aMem;              /* Array of memory cells for parent frame */
13190   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13191   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13192   void *token;            /* Copy of SubProgram.token */
13193   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13194   u16 nCursor;            /* Number of entries in apCsr */
13195   int pc;                 /* Program Counter in parent (calling) frame */
13196   int nOp;                /* Size of aOp array */
13197   int nMem;               /* Number of entries in aMem */
13198   int nOnceFlag;          /* Number of entries in aOnceFlag */
13199   int nChildMem;          /* Number of memory cells for child frame */
13200   int nChildCsr;          /* Number of cursors for child frame */
13201   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13202 };
13203
13204 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13205
13206 /*
13207 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13208 */
13209 #define CACHE_STALE 0
13210
13211 /*
13212 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13213 ** structures. Each Mem struct may cache multiple representations (string,
13214 ** integer etc.) of the same value.
13215 */
13216 struct Mem {
13217   sqlite3 *db;        /* The associated database connection */
13218   char *z;            /* String or BLOB value */
13219   double r;           /* Real value */
13220   union {
13221     i64 i;              /* Integer value used when MEM_Int is set in flags */
13222     int nZero;          /* Used when bit MEM_Zero is set in flags */
13223     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13224     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13225     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13226   } u;
13227   int n;              /* Number of characters in string value, excluding '\0' */
13228   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13229   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13230   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13231 #ifdef SQLITE_DEBUG
13232   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13233   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13234 #endif
13235   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13236   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13237 };
13238
13239 /* One or more of the following flags are set to indicate the validOK
13240 ** representations of the value stored in the Mem struct.
13241 **
13242 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13243 ** No other flags may be set in this case.
13244 **
13245 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13246 ** Usually this is encoded in the same unicode encoding as the main
13247 ** database (see below for exceptions). If the MEM_Term flag is also
13248 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13249 ** flags may coexist with the MEM_Str flag.
13250 */
13251 #define MEM_Null      0x0001   /* Value is NULL */
13252 #define MEM_Str       0x0002   /* Value is a string */
13253 #define MEM_Int       0x0004   /* Value is an integer */
13254 #define MEM_Real      0x0008   /* Value is a real number */
13255 #define MEM_Blob      0x0010   /* Value is a BLOB */
13256 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13257 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13258 #define MEM_Invalid   0x0080   /* Value is undefined */
13259 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13260 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
13261
13262
13263 /* Whenever Mem contains a valid string or blob representation, one of
13264 ** the following flags must be set to determine the memory management
13265 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13266 ** string is \000 or \u0000 terminated
13267 */
13268 #define MEM_Term      0x0200   /* String rep is nul terminated */
13269 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13270 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13271 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13272 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13273 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13274 #ifdef SQLITE_OMIT_INCRBLOB
13275   #undef MEM_Zero
13276   #define MEM_Zero 0x0000
13277 #endif
13278
13279 /*
13280 ** Clear any existing type flags from a Mem and replace them with f
13281 */
13282 #define MemSetTypeFlag(p, f) \
13283    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13284
13285 /*
13286 ** Return true if a memory cell is not marked as invalid.  This macro
13287 ** is for use inside assert() statements only.
13288 */
13289 #ifdef SQLITE_DEBUG
13290 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13291 #endif
13292
13293
13294 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13295 ** additional information about auxiliary information bound to arguments
13296 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13297 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13298 ** that can be associated with a constant argument to a function.  This
13299 ** allows functions such as "regexp" to compile their constant regular
13300 ** expression argument once and reused the compiled code for multiple
13301 ** invocations.
13302 */
13303 struct VdbeFunc {
13304   FuncDef *pFunc;               /* The definition of the function */
13305   int nAux;                     /* Number of entries allocated for apAux[] */
13306   struct AuxData {
13307     void *pAux;                   /* Aux data for the i-th argument */
13308     void (*xDelete)(void *);      /* Destructor for the aux data */
13309   } apAux[1];                   /* One slot for each function argument */
13310 };
13311
13312 /*
13313 ** The "context" argument for a installable function.  A pointer to an
13314 ** instance of this structure is the first argument to the routines used
13315 ** implement the SQL functions.
13316 **
13317 ** There is a typedef for this structure in sqlite.h.  So all routines,
13318 ** even the public interface to SQLite, can use a pointer to this structure.
13319 ** But this file is the only place where the internal details of this
13320 ** structure are known.
13321 **
13322 ** This structure is defined inside of vdbeInt.h because it uses substructures
13323 ** (Mem) which are only defined there.
13324 */
13325 struct sqlite3_context {
13326   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13327   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13328   Mem s;                /* The return value is stored here */
13329   Mem *pMem;            /* Memory cell used to store aggregate context */
13330   CollSeq *pColl;       /* Collating sequence */
13331   int isError;          /* Error code returned by the function. */
13332   int skipFlag;         /* Skip skip accumulator loading if true */
13333 };
13334
13335 /*
13336 ** An Explain object accumulates indented output which is helpful
13337 ** in describing recursive data structures.
13338 */
13339 struct Explain {
13340   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13341   StrAccum str;      /* The string being accumulated */
13342   int nIndent;       /* Number of elements in aIndent */
13343   u16 aIndent[100];  /* Levels of indentation */
13344   char zBase[100];   /* Initial space */
13345 };
13346
13347 /* A bitfield type for use inside of structures.  Always follow with :N where
13348 ** N is the number of bits.
13349 */
13350 typedef unsigned bft;  /* Bit Field Type */
13351
13352 /*
13353 ** An instance of the virtual machine.  This structure contains the complete
13354 ** state of the virtual machine.
13355 **
13356 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13357 ** is really a pointer to an instance of this structure.
13358 **
13359 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13360 ** any virtual table method invocations made by the vdbe program. It is
13361 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13362 ** variable is used for two purposes: to allow xDestroy methods to execute
13363 ** "DROP TABLE" statements and to prevent some nasty side effects of
13364 ** malloc failure when SQLite is invoked recursively by a virtual table 
13365 ** method function.
13366 */
13367 struct Vdbe {
13368   sqlite3 *db;            /* The database connection that owns this statement */
13369   Op *aOp;                /* Space to hold the virtual machine's program */
13370   Mem *aMem;              /* The memory locations */
13371   Mem **apArg;            /* Arguments to currently executing user function */
13372   Mem *aColName;          /* Column names to return */
13373   Mem *pResultSet;        /* Pointer to an array of results */
13374   int nMem;               /* Number of memory locations currently allocated */
13375   int nOp;                /* Number of instructions in the program */
13376   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13377   int nLabel;             /* Number of labels used */
13378   int *aLabel;            /* Space to hold the labels */
13379   u16 nResColumn;         /* Number of columns in one row of the result set */
13380   u16 nCursor;            /* Number of slots in apCsr[] */
13381   u32 magic;              /* Magic number for sanity checking */
13382   char *zErrMsg;          /* Error message written here */
13383   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13384   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13385   Mem *aVar;              /* Values for the OP_Variable opcode. */
13386   char **azVar;           /* Name of variables */
13387   ynVar nVar;             /* Number of entries in aVar[] */
13388   ynVar nzVar;            /* Number of entries in azVar[] */
13389   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13390   int pc;                 /* The program counter */
13391   int rc;                 /* Value to return */
13392   u8 errorAction;         /* Recovery action to do in case of an error */
13393   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13394   bft explain:2;          /* True if EXPLAIN present on SQL command */
13395   bft inVtabMethod:2;     /* See comments above */
13396   bft changeCntOn:1;      /* True to update the change-counter */
13397   bft expired:1;          /* True if the VM needs to be recompiled */
13398   bft runOnlyOnce:1;      /* Automatically expire on reset */
13399   bft usesStmtJournal:1;  /* True if uses a statement journal */
13400   bft readOnly:1;         /* True for read-only statements */
13401   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13402   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13403   int nChange;            /* Number of db changes made since last reset */
13404   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13405   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13406   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13407   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13408 #ifndef SQLITE_OMIT_TRACE
13409   i64 startTime;          /* Time when query started - used for profiling */
13410 #endif
13411   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13412   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13413   char *zSql;             /* Text of the SQL statement that generated this */
13414   void *pFree;            /* Free this when deleting the vdbe */
13415 #ifdef SQLITE_DEBUG
13416   FILE *trace;            /* Write an execution trace here, if not NULL */
13417 #endif
13418 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13419   Explain *pExplain;      /* The explainer */
13420   char *zExplain;         /* Explanation of data structures */
13421 #endif
13422   VdbeFrame *pFrame;      /* Parent frame */
13423   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13424   int nFrame;             /* Number of frames in pFrame list */
13425   u32 expmask;            /* Binding to these vars invalidates VM */
13426   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13427   int nOnceFlag;          /* Size of array aOnceFlag[] */
13428   u8 *aOnceFlag;          /* Flags for OP_Once */
13429 };
13430
13431 /*
13432 ** The following are allowed values for Vdbe.magic
13433 */
13434 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13435 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13436 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13437 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13438
13439 /*
13440 ** Function prototypes
13441 */
13442 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13443 void sqliteVdbePopStack(Vdbe*,int);
13444 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13445 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13446 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13447 #endif
13448 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13449 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13450 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13451 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13452 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13453
13454 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13455 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13456 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13457 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13458 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13459 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13460 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13461 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13462 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13463 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13464 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13465 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13466 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13467 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13468 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13469 #ifdef SQLITE_OMIT_FLOATING_POINT
13470 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13471 #else
13472 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13473 #endif
13474 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13475 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13476 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13477 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13478 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13479 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13480 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13481 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13482 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13483 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13484 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13485 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13486 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13487 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13488 #define VdbeMemRelease(X)  \
13489   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13490     sqlite3VdbeMemReleaseExternal(X);
13491 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13492 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13493 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13494 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13495 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13496 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13497 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13498 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13499
13500 #ifdef SQLITE_OMIT_MERGE_SORT
13501 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
13502 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
13503 # define sqlite3VdbeSorterClose(Y,Z)
13504 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
13505 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
13506 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
13507 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13508 #else
13509 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13510 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13511 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13512 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13513 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13514 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13515 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13516 #endif
13517
13518 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13519 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13520 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13521 #else
13522 # define sqlite3VdbeEnter(X)
13523 # define sqlite3VdbeLeave(X)
13524 #endif
13525
13526 #ifdef SQLITE_DEBUG
13527 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13528 #endif
13529
13530 #ifndef SQLITE_OMIT_FOREIGN_KEY
13531 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13532 #else
13533 # define sqlite3VdbeCheckFk(p,i) 0
13534 #endif
13535
13536 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13537 #ifdef SQLITE_DEBUG
13538 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13539 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13540 #endif
13541 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13542
13543 #ifndef SQLITE_OMIT_INCRBLOB
13544 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13545   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13546 #else
13547   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13548   #define ExpandBlob(P) SQLITE_OK
13549 #endif
13550
13551 #endif /* !defined(_VDBEINT_H_) */
13552
13553 /************** End of vdbeInt.h *********************************************/
13554 /************** Continuing where we left off in status.c *********************/
13555
13556 /*
13557 ** Variables in which to record status information.
13558 */
13559 typedef struct sqlite3StatType sqlite3StatType;
13560 static SQLITE_WSD struct sqlite3StatType {
13561   int nowValue[10];         /* Current value */
13562   int mxValue[10];          /* Maximum value */
13563 } sqlite3Stat = { {0,}, {0,} };
13564
13565
13566 /* The "wsdStat" macro will resolve to the status information
13567 ** state vector.  If writable static data is unsupported on the target,
13568 ** we have to locate the state vector at run-time.  In the more common
13569 ** case where writable static data is supported, wsdStat can refer directly
13570 ** to the "sqlite3Stat" state vector declared above.
13571 */
13572 #ifdef SQLITE_OMIT_WSD
13573 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13574 # define wsdStat x[0]
13575 #else
13576 # define wsdStatInit
13577 # define wsdStat sqlite3Stat
13578 #endif
13579
13580 /*
13581 ** Return the current value of a status parameter.
13582 */
13583 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13584   wsdStatInit;
13585   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13586   return wsdStat.nowValue[op];
13587 }
13588
13589 /*
13590 ** Add N to the value of a status record.  It is assumed that the
13591 ** caller holds appropriate locks.
13592 */
13593 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13594   wsdStatInit;
13595   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13596   wsdStat.nowValue[op] += N;
13597   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13598     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13599   }
13600 }
13601
13602 /*
13603 ** Set the value of a status to X.
13604 */
13605 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13606   wsdStatInit;
13607   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13608   wsdStat.nowValue[op] = X;
13609   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13610     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13611   }
13612 }
13613
13614 /*
13615 ** Query status information.
13616 **
13617 ** This implementation assumes that reading or writing an aligned
13618 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13619 ** then this routine is not threadsafe.
13620 */
13621 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13622   wsdStatInit;
13623   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13624     return SQLITE_MISUSE_BKPT;
13625   }
13626   *pCurrent = wsdStat.nowValue[op];
13627   *pHighwater = wsdStat.mxValue[op];
13628   if( resetFlag ){
13629     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13630   }
13631   return SQLITE_OK;
13632 }
13633
13634 /*
13635 ** Query status information for a single database connection
13636 */
13637 SQLITE_API int sqlite3_db_status(
13638   sqlite3 *db,          /* The database connection whose status is desired */
13639   int op,               /* Status verb */
13640   int *pCurrent,        /* Write current value here */
13641   int *pHighwater,      /* Write high-water mark here */
13642   int resetFlag         /* Reset high-water mark if true */
13643 ){
13644   int rc = SQLITE_OK;   /* Return code */
13645   sqlite3_mutex_enter(db->mutex);
13646   switch( op ){
13647     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13648       *pCurrent = db->lookaside.nOut;
13649       *pHighwater = db->lookaside.mxOut;
13650       if( resetFlag ){
13651         db->lookaside.mxOut = db->lookaside.nOut;
13652       }
13653       break;
13654     }
13655
13656     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13657     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13658     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13659       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13660       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13661       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13662       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13663       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13664       *pCurrent = 0;
13665       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13666       if( resetFlag ){
13667         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13668       }
13669       break;
13670     }
13671
13672     /* 
13673     ** Return an approximation for the amount of memory currently used
13674     ** by all pagers associated with the given database connection.  The
13675     ** highwater mark is meaningless and is returned as zero.
13676     */
13677     case SQLITE_DBSTATUS_CACHE_USED: {
13678       int totalUsed = 0;
13679       int i;
13680       sqlite3BtreeEnterAll(db);
13681       for(i=0; i<db->nDb; i++){
13682         Btree *pBt = db->aDb[i].pBt;
13683         if( pBt ){
13684           Pager *pPager = sqlite3BtreePager(pBt);
13685           totalUsed += sqlite3PagerMemUsed(pPager);
13686         }
13687       }
13688       sqlite3BtreeLeaveAll(db);
13689       *pCurrent = totalUsed;
13690       *pHighwater = 0;
13691       break;
13692     }
13693
13694     /*
13695     ** *pCurrent gets an accurate estimate of the amount of memory used
13696     ** to store the schema for all databases (main, temp, and any ATTACHed
13697     ** databases.  *pHighwater is set to zero.
13698     */
13699     case SQLITE_DBSTATUS_SCHEMA_USED: {
13700       int i;                      /* Used to iterate through schemas */
13701       int nByte = 0;              /* Used to accumulate return value */
13702
13703       sqlite3BtreeEnterAll(db);
13704       db->pnBytesFreed = &nByte;
13705       for(i=0; i<db->nDb; i++){
13706         Schema *pSchema = db->aDb[i].pSchema;
13707         if( ALWAYS(pSchema!=0) ){
13708           HashElem *p;
13709
13710           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13711               pSchema->tblHash.count 
13712             + pSchema->trigHash.count
13713             + pSchema->idxHash.count
13714             + pSchema->fkeyHash.count
13715           );
13716           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13717           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13718           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13719           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13720
13721           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13722             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13723           }
13724           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13725             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13726           }
13727         }
13728       }
13729       db->pnBytesFreed = 0;
13730       sqlite3BtreeLeaveAll(db);
13731
13732       *pHighwater = 0;
13733       *pCurrent = nByte;
13734       break;
13735     }
13736
13737     /*
13738     ** *pCurrent gets an accurate estimate of the amount of memory used
13739     ** to store all prepared statements.
13740     ** *pHighwater is set to zero.
13741     */
13742     case SQLITE_DBSTATUS_STMT_USED: {
13743       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13744       int nByte = 0;              /* Used to accumulate return value */
13745
13746       db->pnBytesFreed = &nByte;
13747       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13748         sqlite3VdbeClearObject(db, pVdbe);
13749         sqlite3DbFree(db, pVdbe);
13750       }
13751       db->pnBytesFreed = 0;
13752
13753       *pHighwater = 0;
13754       *pCurrent = nByte;
13755
13756       break;
13757     }
13758
13759     /*
13760     ** Set *pCurrent to the total cache hits or misses encountered by all
13761     ** pagers the database handle is connected to. *pHighwater is always set 
13762     ** to zero.
13763     */
13764     case SQLITE_DBSTATUS_CACHE_HIT:
13765     case SQLITE_DBSTATUS_CACHE_MISS:
13766     case SQLITE_DBSTATUS_CACHE_WRITE:{
13767       int i;
13768       int nRet = 0;
13769       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13770       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13771
13772       for(i=0; i<db->nDb; i++){
13773         if( db->aDb[i].pBt ){
13774           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13775           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13776         }
13777       }
13778       *pHighwater = 0;
13779       *pCurrent = nRet;
13780       break;
13781     }
13782
13783     default: {
13784       rc = SQLITE_ERROR;
13785     }
13786   }
13787   sqlite3_mutex_leave(db->mutex);
13788   return rc;
13789 }
13790
13791 /************** End of status.c **********************************************/
13792 /************** Begin file date.c ********************************************/
13793 /*
13794 ** 2003 October 31
13795 **
13796 ** The author disclaims copyright to this source code.  In place of
13797 ** a legal notice, here is a blessing:
13798 **
13799 **    May you do good and not evil.
13800 **    May you find forgiveness for yourself and forgive others.
13801 **    May you share freely, never taking more than you give.
13802 **
13803 *************************************************************************
13804 ** This file contains the C functions that implement date and time
13805 ** functions for SQLite.  
13806 **
13807 ** There is only one exported symbol in this file - the function
13808 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13809 ** All other code has file scope.
13810 **
13811 ** SQLite processes all times and dates as Julian Day numbers.  The
13812 ** dates and times are stored as the number of days since noon
13813 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13814 ** calendar system. 
13815 **
13816 ** 1970-01-01 00:00:00 is JD 2440587.5
13817 ** 2000-01-01 00:00:00 is JD 2451544.5
13818 **
13819 ** This implemention requires years to be expressed as a 4-digit number
13820 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13821 ** be represented, even though julian day numbers allow a much wider
13822 ** range of dates.
13823 **
13824 ** The Gregorian calendar system is used for all dates and times,
13825 ** even those that predate the Gregorian calendar.  Historians usually
13826 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13827 ** dates afterwards, depending on locale.  Beware of this difference.
13828 **
13829 ** The conversion algorithms are implemented based on descriptions
13830 ** in the following text:
13831 **
13832 **      Jean Meeus
13833 **      Astronomical Algorithms, 2nd Edition, 1998
13834 **      ISBM 0-943396-61-1
13835 **      Willmann-Bell, Inc
13836 **      Richmond, Virginia (USA)
13837 */
13838 /* #include <stdlib.h> */
13839 /* #include <assert.h> */
13840 #include <time.h>
13841
13842 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13843
13844
13845 /*
13846 ** A structure for holding a single date and time.
13847 */
13848 typedef struct DateTime DateTime;
13849 struct DateTime {
13850   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13851   int Y, M, D;       /* Year, month, and day */
13852   int h, m;          /* Hour and minutes */
13853   int tz;            /* Timezone offset in minutes */
13854   double s;          /* Seconds */
13855   char validYMD;     /* True (1) if Y,M,D are valid */
13856   char validHMS;     /* True (1) if h,m,s are valid */
13857   char validJD;      /* True (1) if iJD is valid */
13858   char validTZ;      /* True (1) if tz is valid */
13859 };
13860
13861
13862 /*
13863 ** Convert zDate into one or more integers.  Additional arguments
13864 ** come in groups of 5 as follows:
13865 **
13866 **       N       number of digits in the integer
13867 **       min     minimum allowed value of the integer
13868 **       max     maximum allowed value of the integer
13869 **       nextC   first character after the integer
13870 **       pVal    where to write the integers value.
13871 **
13872 ** Conversions continue until one with nextC==0 is encountered.
13873 ** The function returns the number of successful conversions.
13874 */
13875 static int getDigits(const char *zDate, ...){
13876   va_list ap;
13877   int val;
13878   int N;
13879   int min;
13880   int max;
13881   int nextC;
13882   int *pVal;
13883   int cnt = 0;
13884   va_start(ap, zDate);
13885   do{
13886     N = va_arg(ap, int);
13887     min = va_arg(ap, int);
13888     max = va_arg(ap, int);
13889     nextC = va_arg(ap, int);
13890     pVal = va_arg(ap, int*);
13891     val = 0;
13892     while( N-- ){
13893       if( !sqlite3Isdigit(*zDate) ){
13894         goto end_getDigits;
13895       }
13896       val = val*10 + *zDate - '0';
13897       zDate++;
13898     }
13899     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13900       goto end_getDigits;
13901     }
13902     *pVal = val;
13903     zDate++;
13904     cnt++;
13905   }while( nextC );
13906 end_getDigits:
13907   va_end(ap);
13908   return cnt;
13909 }
13910
13911 /*
13912 ** Parse a timezone extension on the end of a date-time.
13913 ** The extension is of the form:
13914 **
13915 **        (+/-)HH:MM
13916 **
13917 ** Or the "zulu" notation:
13918 **
13919 **        Z
13920 **
13921 ** If the parse is successful, write the number of minutes
13922 ** of change in p->tz and return 0.  If a parser error occurs,
13923 ** return non-zero.
13924 **
13925 ** A missing specifier is not considered an error.
13926 */
13927 static int parseTimezone(const char *zDate, DateTime *p){
13928   int sgn = 0;
13929   int nHr, nMn;
13930   int c;
13931   while( sqlite3Isspace(*zDate) ){ zDate++; }
13932   p->tz = 0;
13933   c = *zDate;
13934   if( c=='-' ){
13935     sgn = -1;
13936   }else if( c=='+' ){
13937     sgn = +1;
13938   }else if( c=='Z' || c=='z' ){
13939     zDate++;
13940     goto zulu_time;
13941   }else{
13942     return c!=0;
13943   }
13944   zDate++;
13945   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13946     return 1;
13947   }
13948   zDate += 5;
13949   p->tz = sgn*(nMn + nHr*60);
13950 zulu_time:
13951   while( sqlite3Isspace(*zDate) ){ zDate++; }
13952   return *zDate!=0;
13953 }
13954
13955 /*
13956 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13957 ** The HH, MM, and SS must each be exactly 2 digits.  The
13958 ** fractional seconds FFFF can be one or more digits.
13959 **
13960 ** Return 1 if there is a parsing error and 0 on success.
13961 */
13962 static int parseHhMmSs(const char *zDate, DateTime *p){
13963   int h, m, s;
13964   double ms = 0.0;
13965   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13966     return 1;
13967   }
13968   zDate += 5;
13969   if( *zDate==':' ){
13970     zDate++;
13971     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13972       return 1;
13973     }
13974     zDate += 2;
13975     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13976       double rScale = 1.0;
13977       zDate++;
13978       while( sqlite3Isdigit(*zDate) ){
13979         ms = ms*10.0 + *zDate - '0';
13980         rScale *= 10.0;
13981         zDate++;
13982       }
13983       ms /= rScale;
13984     }
13985   }else{
13986     s = 0;
13987   }
13988   p->validJD = 0;
13989   p->validHMS = 1;
13990   p->h = h;
13991   p->m = m;
13992   p->s = s + ms;
13993   if( parseTimezone(zDate, p) ) return 1;
13994   p->validTZ = (p->tz!=0)?1:0;
13995   return 0;
13996 }
13997
13998 /*
13999 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14000 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14001 **
14002 ** Reference:  Meeus page 61
14003 */
14004 static void computeJD(DateTime *p){
14005   int Y, M, D, A, B, X1, X2;
14006
14007   if( p->validJD ) return;
14008   if( p->validYMD ){
14009     Y = p->Y;
14010     M = p->M;
14011     D = p->D;
14012   }else{
14013     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14014     M = 1;
14015     D = 1;
14016   }
14017   if( M<=2 ){
14018     Y--;
14019     M += 12;
14020   }
14021   A = Y/100;
14022   B = 2 - A + (A/4);
14023   X1 = 36525*(Y+4716)/100;
14024   X2 = 306001*(M+1)/10000;
14025   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14026   p->validJD = 1;
14027   if( p->validHMS ){
14028     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14029     if( p->validTZ ){
14030       p->iJD -= p->tz*60000;
14031       p->validYMD = 0;
14032       p->validHMS = 0;
14033       p->validTZ = 0;
14034     }
14035   }
14036 }
14037
14038 /*
14039 ** Parse dates of the form
14040 **
14041 **     YYYY-MM-DD HH:MM:SS.FFF
14042 **     YYYY-MM-DD HH:MM:SS
14043 **     YYYY-MM-DD HH:MM
14044 **     YYYY-MM-DD
14045 **
14046 ** Write the result into the DateTime structure and return 0
14047 ** on success and 1 if the input string is not a well-formed
14048 ** date.
14049 */
14050 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14051   int Y, M, D, neg;
14052
14053   if( zDate[0]=='-' ){
14054     zDate++;
14055     neg = 1;
14056   }else{
14057     neg = 0;
14058   }
14059   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14060     return 1;
14061   }
14062   zDate += 10;
14063   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14064   if( parseHhMmSs(zDate, p)==0 ){
14065     /* We got the time */
14066   }else if( *zDate==0 ){
14067     p->validHMS = 0;
14068   }else{
14069     return 1;
14070   }
14071   p->validJD = 0;
14072   p->validYMD = 1;
14073   p->Y = neg ? -Y : Y;
14074   p->M = M;
14075   p->D = D;
14076   if( p->validTZ ){
14077     computeJD(p);
14078   }
14079   return 0;
14080 }
14081
14082 /*
14083 ** Set the time to the current time reported by the VFS.
14084 **
14085 ** Return the number of errors.
14086 */
14087 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14088   sqlite3 *db = sqlite3_context_db_handle(context);
14089   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14090     p->validJD = 1;
14091     return 0;
14092   }else{
14093     return 1;
14094   }
14095 }
14096
14097 /*
14098 ** Attempt to parse the given string into a Julian Day Number.  Return
14099 ** the number of errors.
14100 **
14101 ** The following are acceptable forms for the input string:
14102 **
14103 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14104 **      DDDD.DD 
14105 **      now
14106 **
14107 ** In the first form, the +/-HH:MM is always optional.  The fractional
14108 ** seconds extension (the ".FFF") is optional.  The seconds portion
14109 ** (":SS.FFF") is option.  The year and date can be omitted as long
14110 ** as there is a time string.  The time string can be omitted as long
14111 ** as there is a year and date.
14112 */
14113 static int parseDateOrTime(
14114   sqlite3_context *context, 
14115   const char *zDate, 
14116   DateTime *p
14117 ){
14118   double r;
14119   if( parseYyyyMmDd(zDate,p)==0 ){
14120     return 0;
14121   }else if( parseHhMmSs(zDate, p)==0 ){
14122     return 0;
14123   }else if( sqlite3StrICmp(zDate,"now")==0){
14124     return setDateTimeToCurrent(context, p);
14125   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14126     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14127     p->validJD = 1;
14128     return 0;
14129   }
14130   return 1;
14131 }
14132
14133 /*
14134 ** Compute the Year, Month, and Day from the julian day number.
14135 */
14136 static void computeYMD(DateTime *p){
14137   int Z, A, B, C, D, E, X1;
14138   if( p->validYMD ) return;
14139   if( !p->validJD ){
14140     p->Y = 2000;
14141     p->M = 1;
14142     p->D = 1;
14143   }else{
14144     Z = (int)((p->iJD + 43200000)/86400000);
14145     A = (int)((Z - 1867216.25)/36524.25);
14146     A = Z + 1 + A - (A/4);
14147     B = A + 1524;
14148     C = (int)((B - 122.1)/365.25);
14149     D = (36525*C)/100;
14150     E = (int)((B-D)/30.6001);
14151     X1 = (int)(30.6001*E);
14152     p->D = B - D - X1;
14153     p->M = E<14 ? E-1 : E-13;
14154     p->Y = p->M>2 ? C - 4716 : C - 4715;
14155   }
14156   p->validYMD = 1;
14157 }
14158
14159 /*
14160 ** Compute the Hour, Minute, and Seconds from the julian day number.
14161 */
14162 static void computeHMS(DateTime *p){
14163   int s;
14164   if( p->validHMS ) return;
14165   computeJD(p);
14166   s = (int)((p->iJD + 43200000) % 86400000);
14167   p->s = s/1000.0;
14168   s = (int)p->s;
14169   p->s -= s;
14170   p->h = s/3600;
14171   s -= p->h*3600;
14172   p->m = s/60;
14173   p->s += s - p->m*60;
14174   p->validHMS = 1;
14175 }
14176
14177 /*
14178 ** Compute both YMD and HMS
14179 */
14180 static void computeYMD_HMS(DateTime *p){
14181   computeYMD(p);
14182   computeHMS(p);
14183 }
14184
14185 /*
14186 ** Clear the YMD and HMS and the TZ
14187 */
14188 static void clearYMD_HMS_TZ(DateTime *p){
14189   p->validYMD = 0;
14190   p->validHMS = 0;
14191   p->validTZ = 0;
14192 }
14193
14194 /*
14195 ** On recent Windows platforms, the localtime_s() function is available
14196 ** as part of the "Secure CRT". It is essentially equivalent to 
14197 ** localtime_r() available under most POSIX platforms, except that the 
14198 ** order of the parameters is reversed.
14199 **
14200 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14201 **
14202 ** If the user has not indicated to use localtime_r() or localtime_s()
14203 ** already, check for an MSVC build environment that provides 
14204 ** localtime_s().
14205 */
14206 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14207      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14208 #define HAVE_LOCALTIME_S 1
14209 #endif
14210
14211 #ifndef SQLITE_OMIT_LOCALTIME
14212 /*
14213 ** The following routine implements the rough equivalent of localtime_r()
14214 ** using whatever operating-system specific localtime facility that
14215 ** is available.  This routine returns 0 on success and
14216 ** non-zero on any kind of error.
14217 **
14218 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14219 ** routine will always fail.
14220 */
14221 static int osLocaltime(time_t *t, struct tm *pTm){
14222   int rc;
14223 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14224       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14225   struct tm *pX;
14226 #if SQLITE_THREADSAFE>0
14227   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14228 #endif
14229   sqlite3_mutex_enter(mutex);
14230   pX = localtime(t);
14231 #ifndef SQLITE_OMIT_BUILTIN_TEST
14232   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14233 #endif
14234   if( pX ) *pTm = *pX;
14235   sqlite3_mutex_leave(mutex);
14236   rc = pX==0;
14237 #else
14238 #ifndef SQLITE_OMIT_BUILTIN_TEST
14239   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14240 #endif
14241 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14242   rc = localtime_r(t, pTm)==0;
14243 #else
14244   rc = localtime_s(pTm, t);
14245 #endif /* HAVE_LOCALTIME_R */
14246 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14247   return rc;
14248 }
14249 #endif /* SQLITE_OMIT_LOCALTIME */
14250
14251
14252 #ifndef SQLITE_OMIT_LOCALTIME
14253 /*
14254 ** Compute the difference (in milliseconds) between localtime and UTC
14255 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14256 ** return this value and set *pRc to SQLITE_OK. 
14257 **
14258 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14259 ** is undefined in this case.
14260 */
14261 static sqlite3_int64 localtimeOffset(
14262   DateTime *p,                    /* Date at which to calculate offset */
14263   sqlite3_context *pCtx,          /* Write error here if one occurs */
14264   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14265 ){
14266   DateTime x, y;
14267   time_t t;
14268   struct tm sLocal;
14269
14270   /* Initialize the contents of sLocal to avoid a compiler warning. */
14271   memset(&sLocal, 0, sizeof(sLocal));
14272
14273   x = *p;
14274   computeYMD_HMS(&x);
14275   if( x.Y<1971 || x.Y>=2038 ){
14276     x.Y = 2000;
14277     x.M = 1;
14278     x.D = 1;
14279     x.h = 0;
14280     x.m = 0;
14281     x.s = 0.0;
14282   } else {
14283     int s = (int)(x.s + 0.5);
14284     x.s = s;
14285   }
14286   x.tz = 0;
14287   x.validJD = 0;
14288   computeJD(&x);
14289   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14290   if( osLocaltime(&t, &sLocal) ){
14291     sqlite3_result_error(pCtx, "local time unavailable", -1);
14292     *pRc = SQLITE_ERROR;
14293     return 0;
14294   }
14295   y.Y = sLocal.tm_year + 1900;
14296   y.M = sLocal.tm_mon + 1;
14297   y.D = sLocal.tm_mday;
14298   y.h = sLocal.tm_hour;
14299   y.m = sLocal.tm_min;
14300   y.s = sLocal.tm_sec;
14301   y.validYMD = 1;
14302   y.validHMS = 1;
14303   y.validJD = 0;
14304   y.validTZ = 0;
14305   computeJD(&y);
14306   *pRc = SQLITE_OK;
14307   return y.iJD - x.iJD;
14308 }
14309 #endif /* SQLITE_OMIT_LOCALTIME */
14310
14311 /*
14312 ** Process a modifier to a date-time stamp.  The modifiers are
14313 ** as follows:
14314 **
14315 **     NNN days
14316 **     NNN hours
14317 **     NNN minutes
14318 **     NNN.NNNN seconds
14319 **     NNN months
14320 **     NNN years
14321 **     start of month
14322 **     start of year
14323 **     start of week
14324 **     start of day
14325 **     weekday N
14326 **     unixepoch
14327 **     localtime
14328 **     utc
14329 **
14330 ** Return 0 on success and 1 if there is any kind of error. If the error
14331 ** is in a system call (i.e. localtime()), then an error message is written
14332 ** to context pCtx. If the error is an unrecognized modifier, no error is
14333 ** written to pCtx.
14334 */
14335 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14336   int rc = 1;
14337   int n;
14338   double r;
14339   char *z, zBuf[30];
14340   z = zBuf;
14341   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14342     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14343   }
14344   z[n] = 0;
14345   switch( z[0] ){
14346 #ifndef SQLITE_OMIT_LOCALTIME
14347     case 'l': {
14348       /*    localtime
14349       **
14350       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14351       ** show local time.
14352       */
14353       if( strcmp(z, "localtime")==0 ){
14354         computeJD(p);
14355         p->iJD += localtimeOffset(p, pCtx, &rc);
14356         clearYMD_HMS_TZ(p);
14357       }
14358       break;
14359     }
14360 #endif
14361     case 'u': {
14362       /*
14363       **    unixepoch
14364       **
14365       ** Treat the current value of p->iJD as the number of
14366       ** seconds since 1970.  Convert to a real julian day number.
14367       */
14368       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14369         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14370         clearYMD_HMS_TZ(p);
14371         rc = 0;
14372       }
14373 #ifndef SQLITE_OMIT_LOCALTIME
14374       else if( strcmp(z, "utc")==0 ){
14375         sqlite3_int64 c1;
14376         computeJD(p);
14377         c1 = localtimeOffset(p, pCtx, &rc);
14378         if( rc==SQLITE_OK ){
14379           p->iJD -= c1;
14380           clearYMD_HMS_TZ(p);
14381           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14382         }
14383       }
14384 #endif
14385       break;
14386     }
14387     case 'w': {
14388       /*
14389       **    weekday N
14390       **
14391       ** Move the date to the same time on the next occurrence of
14392       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14393       ** date is already on the appropriate weekday, this is a no-op.
14394       */
14395       if( strncmp(z, "weekday ", 8)==0
14396                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14397                && (n=(int)r)==r && n>=0 && r<7 ){
14398         sqlite3_int64 Z;
14399         computeYMD_HMS(p);
14400         p->validTZ = 0;
14401         p->validJD = 0;
14402         computeJD(p);
14403         Z = ((p->iJD + 129600000)/86400000) % 7;
14404         if( Z>n ) Z -= 7;
14405         p->iJD += (n - Z)*86400000;
14406         clearYMD_HMS_TZ(p);
14407         rc = 0;
14408       }
14409       break;
14410     }
14411     case 's': {
14412       /*
14413       **    start of TTTTT
14414       **
14415       ** Move the date backwards to the beginning of the current day,
14416       ** or month or year.
14417       */
14418       if( strncmp(z, "start of ", 9)!=0 ) break;
14419       z += 9;
14420       computeYMD(p);
14421       p->validHMS = 1;
14422       p->h = p->m = 0;
14423       p->s = 0.0;
14424       p->validTZ = 0;
14425       p->validJD = 0;
14426       if( strcmp(z,"month")==0 ){
14427         p->D = 1;
14428         rc = 0;
14429       }else if( strcmp(z,"year")==0 ){
14430         computeYMD(p);
14431         p->M = 1;
14432         p->D = 1;
14433         rc = 0;
14434       }else if( strcmp(z,"day")==0 ){
14435         rc = 0;
14436       }
14437       break;
14438     }
14439     case '+':
14440     case '-':
14441     case '0':
14442     case '1':
14443     case '2':
14444     case '3':
14445     case '4':
14446     case '5':
14447     case '6':
14448     case '7':
14449     case '8':
14450     case '9': {
14451       double rRounder;
14452       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14453       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14454         rc = 1;
14455         break;
14456       }
14457       if( z[n]==':' ){
14458         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14459         ** specified number of hours, minutes, seconds, and fractional seconds
14460         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14461         ** omitted.
14462         */
14463         const char *z2 = z;
14464         DateTime tx;
14465         sqlite3_int64 day;
14466         if( !sqlite3Isdigit(*z2) ) z2++;
14467         memset(&tx, 0, sizeof(tx));
14468         if( parseHhMmSs(z2, &tx) ) break;
14469         computeJD(&tx);
14470         tx.iJD -= 43200000;
14471         day = tx.iJD/86400000;
14472         tx.iJD -= day*86400000;
14473         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14474         computeJD(p);
14475         clearYMD_HMS_TZ(p);
14476         p->iJD += tx.iJD;
14477         rc = 0;
14478         break;
14479       }
14480       z += n;
14481       while( sqlite3Isspace(*z) ) z++;
14482       n = sqlite3Strlen30(z);
14483       if( n>10 || n<3 ) break;
14484       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14485       computeJD(p);
14486       rc = 0;
14487       rRounder = r<0 ? -0.5 : +0.5;
14488       if( n==3 && strcmp(z,"day")==0 ){
14489         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14490       }else if( n==4 && strcmp(z,"hour")==0 ){
14491         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14492       }else if( n==6 && strcmp(z,"minute")==0 ){
14493         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14494       }else if( n==6 && strcmp(z,"second")==0 ){
14495         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14496       }else if( n==5 && strcmp(z,"month")==0 ){
14497         int x, y;
14498         computeYMD_HMS(p);
14499         p->M += (int)r;
14500         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14501         p->Y += x;
14502         p->M -= x*12;
14503         p->validJD = 0;
14504         computeJD(p);
14505         y = (int)r;
14506         if( y!=r ){
14507           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14508         }
14509       }else if( n==4 && strcmp(z,"year")==0 ){
14510         int y = (int)r;
14511         computeYMD_HMS(p);
14512         p->Y += y;
14513         p->validJD = 0;
14514         computeJD(p);
14515         if( y!=r ){
14516           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14517         }
14518       }else{
14519         rc = 1;
14520       }
14521       clearYMD_HMS_TZ(p);
14522       break;
14523     }
14524     default: {
14525       break;
14526     }
14527   }
14528   return rc;
14529 }
14530
14531 /*
14532 ** Process time function arguments.  argv[0] is a date-time stamp.
14533 ** argv[1] and following are modifiers.  Parse them all and write
14534 ** the resulting time into the DateTime structure p.  Return 0
14535 ** on success and 1 if there are any errors.
14536 **
14537 ** If there are zero parameters (if even argv[0] is undefined)
14538 ** then assume a default value of "now" for argv[0].
14539 */
14540 static int isDate(
14541   sqlite3_context *context, 
14542   int argc, 
14543   sqlite3_value **argv, 
14544   DateTime *p
14545 ){
14546   int i;
14547   const unsigned char *z;
14548   int eType;
14549   memset(p, 0, sizeof(*p));
14550   if( argc==0 ){
14551     return setDateTimeToCurrent(context, p);
14552   }
14553   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14554                    || eType==SQLITE_INTEGER ){
14555     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14556     p->validJD = 1;
14557   }else{
14558     z = sqlite3_value_text(argv[0]);
14559     if( !z || parseDateOrTime(context, (char*)z, p) ){
14560       return 1;
14561     }
14562   }
14563   for(i=1; i<argc; i++){
14564     z = sqlite3_value_text(argv[i]);
14565     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14566   }
14567   return 0;
14568 }
14569
14570
14571 /*
14572 ** The following routines implement the various date and time functions
14573 ** of SQLite.
14574 */
14575
14576 /*
14577 **    julianday( TIMESTRING, MOD, MOD, ...)
14578 **
14579 ** Return the julian day number of the date specified in the arguments
14580 */
14581 static void juliandayFunc(
14582   sqlite3_context *context,
14583   int argc,
14584   sqlite3_value **argv
14585 ){
14586   DateTime x;
14587   if( isDate(context, argc, argv, &x)==0 ){
14588     computeJD(&x);
14589     sqlite3_result_double(context, x.iJD/86400000.0);
14590   }
14591 }
14592
14593 /*
14594 **    datetime( TIMESTRING, MOD, MOD, ...)
14595 **
14596 ** Return YYYY-MM-DD HH:MM:SS
14597 */
14598 static void datetimeFunc(
14599   sqlite3_context *context,
14600   int argc,
14601   sqlite3_value **argv
14602 ){
14603   DateTime x;
14604   if( isDate(context, argc, argv, &x)==0 ){
14605     char zBuf[100];
14606     computeYMD_HMS(&x);
14607     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14608                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14609     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14610   }
14611 }
14612
14613 /*
14614 **    time( TIMESTRING, MOD, MOD, ...)
14615 **
14616 ** Return HH:MM:SS
14617 */
14618 static void timeFunc(
14619   sqlite3_context *context,
14620   int argc,
14621   sqlite3_value **argv
14622 ){
14623   DateTime x;
14624   if( isDate(context, argc, argv, &x)==0 ){
14625     char zBuf[100];
14626     computeHMS(&x);
14627     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14628     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14629   }
14630 }
14631
14632 /*
14633 **    date( TIMESTRING, MOD, MOD, ...)
14634 **
14635 ** Return YYYY-MM-DD
14636 */
14637 static void dateFunc(
14638   sqlite3_context *context,
14639   int argc,
14640   sqlite3_value **argv
14641 ){
14642   DateTime x;
14643   if( isDate(context, argc, argv, &x)==0 ){
14644     char zBuf[100];
14645     computeYMD(&x);
14646     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14647     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14648   }
14649 }
14650
14651 /*
14652 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14653 **
14654 ** Return a string described by FORMAT.  Conversions as follows:
14655 **
14656 **   %d  day of month
14657 **   %f  ** fractional seconds  SS.SSS
14658 **   %H  hour 00-24
14659 **   %j  day of year 000-366
14660 **   %J  ** Julian day number
14661 **   %m  month 01-12
14662 **   %M  minute 00-59
14663 **   %s  seconds since 1970-01-01
14664 **   %S  seconds 00-59
14665 **   %w  day of week 0-6  sunday==0
14666 **   %W  week of year 00-53
14667 **   %Y  year 0000-9999
14668 **   %%  %
14669 */
14670 static void strftimeFunc(
14671   sqlite3_context *context,
14672   int argc,
14673   sqlite3_value **argv
14674 ){
14675   DateTime x;
14676   u64 n;
14677   size_t i,j;
14678   char *z;
14679   sqlite3 *db;
14680   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14681   char zBuf[100];
14682   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14683   db = sqlite3_context_db_handle(context);
14684   for(i=0, n=1; zFmt[i]; i++, n++){
14685     if( zFmt[i]=='%' ){
14686       switch( zFmt[i+1] ){
14687         case 'd':
14688         case 'H':
14689         case 'm':
14690         case 'M':
14691         case 'S':
14692         case 'W':
14693           n++;
14694           /* fall thru */
14695         case 'w':
14696         case '%':
14697           break;
14698         case 'f':
14699           n += 8;
14700           break;
14701         case 'j':
14702           n += 3;
14703           break;
14704         case 'Y':
14705           n += 8;
14706           break;
14707         case 's':
14708         case 'J':
14709           n += 50;
14710           break;
14711         default:
14712           return;  /* ERROR.  return a NULL */
14713       }
14714       i++;
14715     }
14716   }
14717   testcase( n==sizeof(zBuf)-1 );
14718   testcase( n==sizeof(zBuf) );
14719   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14720   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14721   if( n<sizeof(zBuf) ){
14722     z = zBuf;
14723   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14724     sqlite3_result_error_toobig(context);
14725     return;
14726   }else{
14727     z = sqlite3DbMallocRaw(db, (int)n);
14728     if( z==0 ){
14729       sqlite3_result_error_nomem(context);
14730       return;
14731     }
14732   }
14733   computeJD(&x);
14734   computeYMD_HMS(&x);
14735   for(i=j=0; zFmt[i]; i++){
14736     if( zFmt[i]!='%' ){
14737       z[j++] = zFmt[i];
14738     }else{
14739       i++;
14740       switch( zFmt[i] ){
14741         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14742         case 'f': {
14743           double s = x.s;
14744           if( s>59.999 ) s = 59.999;
14745           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14746           j += sqlite3Strlen30(&z[j]);
14747           break;
14748         }
14749         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14750         case 'W': /* Fall thru */
14751         case 'j': {
14752           int nDay;             /* Number of days since 1st day of year */
14753           DateTime y = x;
14754           y.validJD = 0;
14755           y.M = 1;
14756           y.D = 1;
14757           computeJD(&y);
14758           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14759           if( zFmt[i]=='W' ){
14760             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14761             wd = (int)(((x.iJD+43200000)/86400000)%7);
14762             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14763             j += 2;
14764           }else{
14765             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14766             j += 3;
14767           }
14768           break;
14769         }
14770         case 'J': {
14771           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14772           j+=sqlite3Strlen30(&z[j]);
14773           break;
14774         }
14775         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14776         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14777         case 's': {
14778           sqlite3_snprintf(30,&z[j],"%lld",
14779                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14780           j += sqlite3Strlen30(&z[j]);
14781           break;
14782         }
14783         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14784         case 'w': {
14785           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14786           break;
14787         }
14788         case 'Y': {
14789           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14790           break;
14791         }
14792         default:   z[j++] = '%'; break;
14793       }
14794     }
14795   }
14796   z[j] = 0;
14797   sqlite3_result_text(context, z, -1,
14798                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14799 }
14800
14801 /*
14802 ** current_time()
14803 **
14804 ** This function returns the same value as time('now').
14805 */
14806 static void ctimeFunc(
14807   sqlite3_context *context,
14808   int NotUsed,
14809   sqlite3_value **NotUsed2
14810 ){
14811   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14812   timeFunc(context, 0, 0);
14813 }
14814
14815 /*
14816 ** current_date()
14817 **
14818 ** This function returns the same value as date('now').
14819 */
14820 static void cdateFunc(
14821   sqlite3_context *context,
14822   int NotUsed,
14823   sqlite3_value **NotUsed2
14824 ){
14825   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14826   dateFunc(context, 0, 0);
14827 }
14828
14829 /*
14830 ** current_timestamp()
14831 **
14832 ** This function returns the same value as datetime('now').
14833 */
14834 static void ctimestampFunc(
14835   sqlite3_context *context,
14836   int NotUsed,
14837   sqlite3_value **NotUsed2
14838 ){
14839   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14840   datetimeFunc(context, 0, 0);
14841 }
14842 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14843
14844 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14845 /*
14846 ** If the library is compiled to omit the full-scale date and time
14847 ** handling (to get a smaller binary), the following minimal version
14848 ** of the functions current_time(), current_date() and current_timestamp()
14849 ** are included instead. This is to support column declarations that
14850 ** include "DEFAULT CURRENT_TIME" etc.
14851 **
14852 ** This function uses the C-library functions time(), gmtime()
14853 ** and strftime(). The format string to pass to strftime() is supplied
14854 ** as the user-data for the function.
14855 */
14856 static void currentTimeFunc(
14857   sqlite3_context *context,
14858   int argc,
14859   sqlite3_value **argv
14860 ){
14861   time_t t;
14862   char *zFormat = (char *)sqlite3_user_data(context);
14863   sqlite3 *db;
14864   sqlite3_int64 iT;
14865   struct tm *pTm;
14866   struct tm sNow;
14867   char zBuf[20];
14868
14869   UNUSED_PARAMETER(argc);
14870   UNUSED_PARAMETER(argv);
14871
14872   db = sqlite3_context_db_handle(context);
14873   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14874   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14875 #ifdef HAVE_GMTIME_R
14876   pTm = gmtime_r(&t, &sNow);
14877 #else
14878   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14879   pTm = gmtime(&t);
14880   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14881   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14882 #endif
14883   if( pTm ){
14884     strftime(zBuf, 20, zFormat, &sNow);
14885     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14886   }
14887 }
14888 #endif
14889
14890 /*
14891 ** This function registered all of the above C functions as SQL
14892 ** functions.  This should be the only routine in this file with
14893 ** external linkage.
14894 */
14895 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14896   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14897 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14898     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14899     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14900     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14901     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14902     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14903     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14904     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14905     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14906 #else
14907     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14908     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14909     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14910 #endif
14911   };
14912   int i;
14913   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14914   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14915
14916   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14917     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14918   }
14919 }
14920
14921 /************** End of date.c ************************************************/
14922 /************** Begin file os.c **********************************************/
14923 /*
14924 ** 2005 November 29
14925 **
14926 ** The author disclaims copyright to this source code.  In place of
14927 ** a legal notice, here is a blessing:
14928 **
14929 **    May you do good and not evil.
14930 **    May you find forgiveness for yourself and forgive others.
14931 **    May you share freely, never taking more than you give.
14932 **
14933 ******************************************************************************
14934 **
14935 ** This file contains OS interface code that is common to all
14936 ** architectures.
14937 */
14938 #define _SQLITE_OS_C_ 1
14939 #undef _SQLITE_OS_C_
14940
14941 /*
14942 ** The default SQLite sqlite3_vfs implementations do not allocate
14943 ** memory (actually, os_unix.c allocates a small amount of memory
14944 ** from within OsOpen()), but some third-party implementations may.
14945 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14946 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14947 **
14948 ** The following functions are instrumented for malloc() failure 
14949 ** testing:
14950 **
14951 **     sqlite3OsRead()
14952 **     sqlite3OsWrite()
14953 **     sqlite3OsSync()
14954 **     sqlite3OsFileSize()
14955 **     sqlite3OsLock()
14956 **     sqlite3OsCheckReservedLock()
14957 **     sqlite3OsFileControl()
14958 **     sqlite3OsShmMap()
14959 **     sqlite3OsOpen()
14960 **     sqlite3OsDelete()
14961 **     sqlite3OsAccess()
14962 **     sqlite3OsFullPathname()
14963 **
14964 */
14965 #if defined(SQLITE_TEST)
14966 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14967   #define DO_OS_MALLOC_TEST(x)                                       \
14968   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14969     void *pTstAlloc = sqlite3Malloc(10);                             \
14970     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14971     sqlite3_free(pTstAlloc);                                         \
14972   }
14973 #else
14974   #define DO_OS_MALLOC_TEST(x)
14975 #endif
14976
14977 /*
14978 ** The following routines are convenience wrappers around methods
14979 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14980 ** of this would be completely automatic if SQLite were coded using
14981 ** C++ instead of plain old C.
14982 */
14983 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14984   int rc = SQLITE_OK;
14985   if( pId->pMethods ){
14986     rc = pId->pMethods->xClose(pId);
14987     pId->pMethods = 0;
14988   }
14989   return rc;
14990 }
14991 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14992   DO_OS_MALLOC_TEST(id);
14993   return id->pMethods->xRead(id, pBuf, amt, offset);
14994 }
14995 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14996   DO_OS_MALLOC_TEST(id);
14997   return id->pMethods->xWrite(id, pBuf, amt, offset);
14998 }
14999 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15000   return id->pMethods->xTruncate(id, size);
15001 }
15002 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15003   DO_OS_MALLOC_TEST(id);
15004   return id->pMethods->xSync(id, flags);
15005 }
15006 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15007   DO_OS_MALLOC_TEST(id);
15008   return id->pMethods->xFileSize(id, pSize);
15009 }
15010 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15011   DO_OS_MALLOC_TEST(id);
15012   return id->pMethods->xLock(id, lockType);
15013 }
15014 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15015   return id->pMethods->xUnlock(id, lockType);
15016 }
15017 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15018   DO_OS_MALLOC_TEST(id);
15019   return id->pMethods->xCheckReservedLock(id, pResOut);
15020 }
15021
15022 /*
15023 ** Use sqlite3OsFileControl() when we are doing something that might fail
15024 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15025 ** when simply tossing information over the wall to the VFS and we do not
15026 ** really care if the VFS receives and understands the information since it
15027 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15028 ** routine has no return value since the return value would be meaningless.
15029 */
15030 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15031   DO_OS_MALLOC_TEST(id);
15032   return id->pMethods->xFileControl(id, op, pArg);
15033 }
15034 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15035   (void)id->pMethods->xFileControl(id, op, pArg);
15036 }
15037
15038 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15039   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15040   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15041 }
15042 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15043   return id->pMethods->xDeviceCharacteristics(id);
15044 }
15045 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15046   return id->pMethods->xShmLock(id, offset, n, flags);
15047 }
15048 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15049   id->pMethods->xShmBarrier(id);
15050 }
15051 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15052   return id->pMethods->xShmUnmap(id, deleteFlag);
15053 }
15054 SQLITE_PRIVATE int sqlite3OsShmMap(
15055   sqlite3_file *id,               /* Database file handle */
15056   int iPage,
15057   int pgsz,
15058   int bExtend,                    /* True to extend file if necessary */
15059   void volatile **pp              /* OUT: Pointer to mapping */
15060 ){
15061   DO_OS_MALLOC_TEST(id);
15062   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15063 }
15064
15065 /*
15066 ** The next group of routines are convenience wrappers around the
15067 ** VFS methods.
15068 */
15069 SQLITE_PRIVATE int sqlite3OsOpen(
15070   sqlite3_vfs *pVfs, 
15071   const char *zPath, 
15072   sqlite3_file *pFile, 
15073   int flags, 
15074   int *pFlagsOut
15075 ){
15076   int rc;
15077   DO_OS_MALLOC_TEST(0);
15078   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15079   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15080   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15081   ** reaching the VFS. */
15082   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15083   assert( rc==SQLITE_OK || pFile->pMethods==0 );
15084   return rc;
15085 }
15086 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15087   DO_OS_MALLOC_TEST(0);
15088   assert( dirSync==0 || dirSync==1 );
15089   return pVfs->xDelete(pVfs, zPath, dirSync);
15090 }
15091 SQLITE_PRIVATE int sqlite3OsAccess(
15092   sqlite3_vfs *pVfs, 
15093   const char *zPath, 
15094   int flags, 
15095   int *pResOut
15096 ){
15097   DO_OS_MALLOC_TEST(0);
15098   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15099 }
15100 SQLITE_PRIVATE int sqlite3OsFullPathname(
15101   sqlite3_vfs *pVfs, 
15102   const char *zPath, 
15103   int nPathOut, 
15104   char *zPathOut
15105 ){
15106   DO_OS_MALLOC_TEST(0);
15107   zPathOut[0] = 0;
15108   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15109 }
15110 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15111 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15112   return pVfs->xDlOpen(pVfs, zPath);
15113 }
15114 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15115   pVfs->xDlError(pVfs, nByte, zBufOut);
15116 }
15117 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15118   return pVfs->xDlSym(pVfs, pHdle, zSym);
15119 }
15120 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15121   pVfs->xDlClose(pVfs, pHandle);
15122 }
15123 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15124 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15125   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15126 }
15127 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15128   return pVfs->xSleep(pVfs, nMicro);
15129 }
15130 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15131   int rc;
15132   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15133   ** method to get the current date and time if that method is available
15134   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15135   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15136   ** unavailable.
15137   */
15138   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15139     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15140   }else{
15141     double r;
15142     rc = pVfs->xCurrentTime(pVfs, &r);
15143     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15144   }
15145   return rc;
15146 }
15147
15148 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15149   sqlite3_vfs *pVfs, 
15150   const char *zFile, 
15151   sqlite3_file **ppFile, 
15152   int flags,
15153   int *pOutFlags
15154 ){
15155   int rc = SQLITE_NOMEM;
15156   sqlite3_file *pFile;
15157   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15158   if( pFile ){
15159     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15160     if( rc!=SQLITE_OK ){
15161       sqlite3_free(pFile);
15162     }else{
15163       *ppFile = pFile;
15164     }
15165   }
15166   return rc;
15167 }
15168 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15169   int rc = SQLITE_OK;
15170   assert( pFile );
15171   rc = sqlite3OsClose(pFile);
15172   sqlite3_free(pFile);
15173   return rc;
15174 }
15175
15176 /*
15177 ** This function is a wrapper around the OS specific implementation of
15178 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15179 ** ability to simulate a malloc failure, so that the handling of an
15180 ** error in sqlite3_os_init() by the upper layers can be tested.
15181 */
15182 SQLITE_PRIVATE int sqlite3OsInit(void){
15183   void *p = sqlite3_malloc(10);
15184   if( p==0 ) return SQLITE_NOMEM;
15185   sqlite3_free(p);
15186   return sqlite3_os_init();
15187 }
15188
15189 /*
15190 ** The list of all registered VFS implementations.
15191 */
15192 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15193 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15194
15195 /*
15196 ** Locate a VFS by name.  If no name is given, simply return the
15197 ** first VFS on the list.
15198 */
15199 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15200   sqlite3_vfs *pVfs = 0;
15201 #if SQLITE_THREADSAFE
15202   sqlite3_mutex *mutex;
15203 #endif
15204 #ifndef SQLITE_OMIT_AUTOINIT
15205   int rc = sqlite3_initialize();
15206   if( rc ) return 0;
15207 #endif
15208 #if SQLITE_THREADSAFE
15209   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15210 #endif
15211   sqlite3_mutex_enter(mutex);
15212   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15213     if( zVfs==0 ) break;
15214     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15215   }
15216   sqlite3_mutex_leave(mutex);
15217   return pVfs;
15218 }
15219
15220 /*
15221 ** Unlink a VFS from the linked list
15222 */
15223 static void vfsUnlink(sqlite3_vfs *pVfs){
15224   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15225   if( pVfs==0 ){
15226     /* No-op */
15227   }else if( vfsList==pVfs ){
15228     vfsList = pVfs->pNext;
15229   }else if( vfsList ){
15230     sqlite3_vfs *p = vfsList;
15231     while( p->pNext && p->pNext!=pVfs ){
15232       p = p->pNext;
15233     }
15234     if( p->pNext==pVfs ){
15235       p->pNext = pVfs->pNext;
15236     }
15237   }
15238 }
15239
15240 /*
15241 ** Register a VFS with the system.  It is harmless to register the same
15242 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15243 ** true.
15244 */
15245 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15246   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15247 #ifndef SQLITE_OMIT_AUTOINIT
15248   int rc = sqlite3_initialize();
15249   if( rc ) return rc;
15250 #endif
15251   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15252   sqlite3_mutex_enter(mutex);
15253   vfsUnlink(pVfs);
15254   if( makeDflt || vfsList==0 ){
15255     pVfs->pNext = vfsList;
15256     vfsList = pVfs;
15257   }else{
15258     pVfs->pNext = vfsList->pNext;
15259     vfsList->pNext = pVfs;
15260   }
15261   assert(vfsList);
15262   sqlite3_mutex_leave(mutex);
15263   return SQLITE_OK;
15264 }
15265
15266 /*
15267 ** Unregister a VFS so that it is no longer accessible.
15268 */
15269 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15270 #if SQLITE_THREADSAFE
15271   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15272 #endif
15273   sqlite3_mutex_enter(mutex);
15274   vfsUnlink(pVfs);
15275   sqlite3_mutex_leave(mutex);
15276   return SQLITE_OK;
15277 }
15278
15279 /************** End of os.c **************************************************/
15280 /************** Begin file fault.c *******************************************/
15281 /*
15282 ** 2008 Jan 22
15283 **
15284 ** The author disclaims copyright to this source code.  In place of
15285 ** a legal notice, here is a blessing:
15286 **
15287 **    May you do good and not evil.
15288 **    May you find forgiveness for yourself and forgive others.
15289 **    May you share freely, never taking more than you give.
15290 **
15291 *************************************************************************
15292 **
15293 ** This file contains code to support the concept of "benign" 
15294 ** malloc failures (when the xMalloc() or xRealloc() method of the
15295 ** sqlite3_mem_methods structure fails to allocate a block of memory
15296 ** and returns 0). 
15297 **
15298 ** Most malloc failures are non-benign. After they occur, SQLite
15299 ** abandons the current operation and returns an error code (usually
15300 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15301 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15302 ** is completely recoverable simply by not carrying out the resize. The 
15303 ** hash table will continue to function normally.  So a malloc failure 
15304 ** during a hash table resize is a benign fault.
15305 */
15306
15307
15308 #ifndef SQLITE_OMIT_BUILTIN_TEST
15309
15310 /*
15311 ** Global variables.
15312 */
15313 typedef struct BenignMallocHooks BenignMallocHooks;
15314 static SQLITE_WSD struct BenignMallocHooks {
15315   void (*xBenignBegin)(void);
15316   void (*xBenignEnd)(void);
15317 } sqlite3Hooks = { 0, 0 };
15318
15319 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15320 ** structure.  If writable static data is unsupported on the target,
15321 ** we have to locate the state vector at run-time.  In the more common
15322 ** case where writable static data is supported, wsdHooks can refer directly
15323 ** to the "sqlite3Hooks" state vector declared above.
15324 */
15325 #ifdef SQLITE_OMIT_WSD
15326 # define wsdHooksInit \
15327   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15328 # define wsdHooks x[0]
15329 #else
15330 # define wsdHooksInit
15331 # define wsdHooks sqlite3Hooks
15332 #endif
15333
15334
15335 /*
15336 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15337 ** sqlite3EndBenignMalloc() are called, respectively.
15338 */
15339 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15340   void (*xBenignBegin)(void),
15341   void (*xBenignEnd)(void)
15342 ){
15343   wsdHooksInit;
15344   wsdHooks.xBenignBegin = xBenignBegin;
15345   wsdHooks.xBenignEnd = xBenignEnd;
15346 }
15347
15348 /*
15349 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15350 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15351 ** indicates that subsequent malloc failures are non-benign.
15352 */
15353 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15354   wsdHooksInit;
15355   if( wsdHooks.xBenignBegin ){
15356     wsdHooks.xBenignBegin();
15357   }
15358 }
15359 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15360   wsdHooksInit;
15361   if( wsdHooks.xBenignEnd ){
15362     wsdHooks.xBenignEnd();
15363   }
15364 }
15365
15366 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15367
15368 /************** End of fault.c ***********************************************/
15369 /************** Begin file mem0.c ********************************************/
15370 /*
15371 ** 2008 October 28
15372 **
15373 ** The author disclaims copyright to this source code.  In place of
15374 ** a legal notice, here is a blessing:
15375 **
15376 **    May you do good and not evil.
15377 **    May you find forgiveness for yourself and forgive others.
15378 **    May you share freely, never taking more than you give.
15379 **
15380 *************************************************************************
15381 **
15382 ** This file contains a no-op memory allocation drivers for use when
15383 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15384 ** here always fail.  SQLite will not operate with these drivers.  These
15385 ** are merely placeholders.  Real drivers must be substituted using
15386 ** sqlite3_config() before SQLite will operate.
15387 */
15388
15389 /*
15390 ** This version of the memory allocator is the default.  It is
15391 ** used when no other memory allocator is specified using compile-time
15392 ** macros.
15393 */
15394 #ifdef SQLITE_ZERO_MALLOC
15395
15396 /*
15397 ** No-op versions of all memory allocation routines
15398 */
15399 static void *sqlite3MemMalloc(int nByte){ return 0; }
15400 static void sqlite3MemFree(void *pPrior){ return; }
15401 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15402 static int sqlite3MemSize(void *pPrior){ return 0; }
15403 static int sqlite3MemRoundup(int n){ return n; }
15404 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15405 static void sqlite3MemShutdown(void *NotUsed){ return; }
15406
15407 /*
15408 ** This routine is the only routine in this file with external linkage.
15409 **
15410 ** Populate the low-level memory allocation function pointers in
15411 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15412 */
15413 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15414   static const sqlite3_mem_methods defaultMethods = {
15415      sqlite3MemMalloc,
15416      sqlite3MemFree,
15417      sqlite3MemRealloc,
15418      sqlite3MemSize,
15419      sqlite3MemRoundup,
15420      sqlite3MemInit,
15421      sqlite3MemShutdown,
15422      0
15423   };
15424   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15425 }
15426
15427 #endif /* SQLITE_ZERO_MALLOC */
15428
15429 /************** End of mem0.c ************************************************/
15430 /************** Begin file mem1.c ********************************************/
15431 /*
15432 ** 2007 August 14
15433 **
15434 ** The author disclaims copyright to this source code.  In place of
15435 ** a legal notice, here is a blessing:
15436 **
15437 **    May you do good and not evil.
15438 **    May you find forgiveness for yourself and forgive others.
15439 **    May you share freely, never taking more than you give.
15440 **
15441 *************************************************************************
15442 **
15443 ** This file contains low-level memory allocation drivers for when
15444 ** SQLite will use the standard C-library malloc/realloc/free interface
15445 ** to obtain the memory it needs.
15446 **
15447 ** This file contains implementations of the low-level memory allocation
15448 ** routines specified in the sqlite3_mem_methods object.  The content of
15449 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15450 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15451 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15452 ** default configuration is to use memory allocation routines in this
15453 ** file.
15454 **
15455 ** C-preprocessor macro summary:
15456 **
15457 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15458 **                                the malloc_usable_size() interface exists
15459 **                                on the target platform.  Or, this symbol
15460 **                                can be set manually, if desired.
15461 **                                If an equivalent interface exists by
15462 **                                a different name, using a separate -D
15463 **                                option to rename it.
15464 **
15465 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15466 **                                memory allocator.  Set this symbol to enable
15467 **                                building on older macs.
15468 **
15469 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15470 **                                _msize() on windows systems.  This might
15471 **                                be necessary when compiling for Delphi,
15472 **                                for example.
15473 */
15474
15475 /*
15476 ** This version of the memory allocator is the default.  It is
15477 ** used when no other memory allocator is specified using compile-time
15478 ** macros.
15479 */
15480 #ifdef SQLITE_SYSTEM_MALLOC
15481
15482 /*
15483 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15484 ** The use of _msize() is automatic, but can be disabled by compiling
15485 ** with -DSQLITE_WITHOUT_MSIZE
15486 */
15487 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15488 # define SQLITE_MALLOCSIZE _msize
15489 #endif
15490
15491 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15492
15493 /*
15494 ** Use the zone allocator available on apple products unless the
15495 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15496 */
15497 #include <sys/sysctl.h>
15498 #include <malloc/malloc.h>
15499 #include <libkern/OSAtomic.h>
15500 static malloc_zone_t* _sqliteZone_;
15501 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15502 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15503 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15504 #define SQLITE_MALLOCSIZE(x) \
15505         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15506
15507 #else /* if not __APPLE__ */
15508
15509 /*
15510 ** Use standard C library malloc and free on non-Apple systems.  
15511 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15512 */
15513 #define SQLITE_MALLOC(x)    malloc(x)
15514 #define SQLITE_FREE(x)      free(x)
15515 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15516
15517 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15518       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15519 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15520 #endif
15521 #ifdef HAVE_MALLOC_USABLE_SIZE
15522 # ifndef SQLITE_MALLOCSIZE
15523 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15524 # endif
15525 #else
15526 # undef SQLITE_MALLOCSIZE
15527 #endif
15528
15529 #endif /* __APPLE__ or not __APPLE__ */
15530
15531 /*
15532 ** Like malloc(), but remember the size of the allocation
15533 ** so that we can find it later using sqlite3MemSize().
15534 **
15535 ** For this low-level routine, we are guaranteed that nByte>0 because
15536 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15537 ** routines.
15538 */
15539 static void *sqlite3MemMalloc(int nByte){
15540 #ifdef SQLITE_MALLOCSIZE
15541   void *p = SQLITE_MALLOC( nByte );
15542   if( p==0 ){
15543     testcase( sqlite3GlobalConfig.xLog!=0 );
15544     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15545   }
15546   return p;
15547 #else
15548   sqlite3_int64 *p;
15549   assert( nByte>0 );
15550   nByte = ROUND8(nByte);
15551   p = SQLITE_MALLOC( nByte+8 );
15552   if( p ){
15553     p[0] = nByte;
15554     p++;
15555   }else{
15556     testcase( sqlite3GlobalConfig.xLog!=0 );
15557     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15558   }
15559   return (void *)p;
15560 #endif
15561 }
15562
15563 /*
15564 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15565 ** or sqlite3MemRealloc().
15566 **
15567 ** For this low-level routine, we already know that pPrior!=0 since
15568 ** cases where pPrior==0 will have been intecepted and dealt with
15569 ** by higher-level routines.
15570 */
15571 static void sqlite3MemFree(void *pPrior){
15572 #ifdef SQLITE_MALLOCSIZE
15573   SQLITE_FREE(pPrior);
15574 #else
15575   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15576   assert( pPrior!=0 );
15577   p--;
15578   SQLITE_FREE(p);
15579 #endif
15580 }
15581
15582 /*
15583 ** Report the allocated size of a prior return from xMalloc()
15584 ** or xRealloc().
15585 */
15586 static int sqlite3MemSize(void *pPrior){
15587 #ifdef SQLITE_MALLOCSIZE
15588   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15589 #else
15590   sqlite3_int64 *p;
15591   if( pPrior==0 ) return 0;
15592   p = (sqlite3_int64*)pPrior;
15593   p--;
15594   return (int)p[0];
15595 #endif
15596 }
15597
15598 /*
15599 ** Like realloc().  Resize an allocation previously obtained from
15600 ** sqlite3MemMalloc().
15601 **
15602 ** For this low-level interface, we know that pPrior!=0.  Cases where
15603 ** pPrior==0 while have been intercepted by higher-level routine and
15604 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15605 ** cases where nByte<=0 will have been intercepted by higher-level
15606 ** routines and redirected to xFree.
15607 */
15608 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15609 #ifdef SQLITE_MALLOCSIZE
15610   void *p = SQLITE_REALLOC(pPrior, nByte);
15611   if( p==0 ){
15612     testcase( sqlite3GlobalConfig.xLog!=0 );
15613     sqlite3_log(SQLITE_NOMEM,
15614       "failed memory resize %u to %u bytes",
15615       SQLITE_MALLOCSIZE(pPrior), nByte);
15616   }
15617   return p;
15618 #else
15619   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15620   assert( pPrior!=0 && nByte>0 );
15621   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15622   p--;
15623   p = SQLITE_REALLOC(p, nByte+8 );
15624   if( p ){
15625     p[0] = nByte;
15626     p++;
15627   }else{
15628     testcase( sqlite3GlobalConfig.xLog!=0 );
15629     sqlite3_log(SQLITE_NOMEM,
15630       "failed memory resize %u to %u bytes",
15631       sqlite3MemSize(pPrior), nByte);
15632   }
15633   return (void*)p;
15634 #endif
15635 }
15636
15637 /*
15638 ** Round up a request size to the next valid allocation size.
15639 */
15640 static int sqlite3MemRoundup(int n){
15641   return ROUND8(n);
15642 }
15643
15644 /*
15645 ** Initialize this module.
15646 */
15647 static int sqlite3MemInit(void *NotUsed){
15648 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15649   int cpuCount;
15650   size_t len;
15651   if( _sqliteZone_ ){
15652     return SQLITE_OK;
15653   }
15654   len = sizeof(cpuCount);
15655   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15656   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15657   if( cpuCount>1 ){
15658     /* defer MT decisions to system malloc */
15659     _sqliteZone_ = malloc_default_zone();
15660   }else{
15661     /* only 1 core, use our own zone to contention over global locks, 
15662     ** e.g. we have our own dedicated locks */
15663     bool success;
15664     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15665     malloc_set_zone_name(newzone, "Sqlite_Heap");
15666     do{
15667       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
15668                                  (void * volatile *)&_sqliteZone_);
15669     }while(!_sqliteZone_);
15670     if( !success ){
15671       /* somebody registered a zone first */
15672       malloc_destroy_zone(newzone);
15673     }
15674   }
15675 #endif
15676   UNUSED_PARAMETER(NotUsed);
15677   return SQLITE_OK;
15678 }
15679
15680 /*
15681 ** Deinitialize this module.
15682 */
15683 static void sqlite3MemShutdown(void *NotUsed){
15684   UNUSED_PARAMETER(NotUsed);
15685   return;
15686 }
15687
15688 /*
15689 ** This routine is the only routine in this file with external linkage.
15690 **
15691 ** Populate the low-level memory allocation function pointers in
15692 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15693 */
15694 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15695   static const sqlite3_mem_methods defaultMethods = {
15696      sqlite3MemMalloc,
15697      sqlite3MemFree,
15698      sqlite3MemRealloc,
15699      sqlite3MemSize,
15700      sqlite3MemRoundup,
15701      sqlite3MemInit,
15702      sqlite3MemShutdown,
15703      0
15704   };
15705   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15706 }
15707
15708 #endif /* SQLITE_SYSTEM_MALLOC */
15709
15710 /************** End of mem1.c ************************************************/
15711 /************** Begin file mem2.c ********************************************/
15712 /*
15713 ** 2007 August 15
15714 **
15715 ** The author disclaims copyright to this source code.  In place of
15716 ** a legal notice, here is a blessing:
15717 **
15718 **    May you do good and not evil.
15719 **    May you find forgiveness for yourself and forgive others.
15720 **    May you share freely, never taking more than you give.
15721 **
15722 *************************************************************************
15723 **
15724 ** This file contains low-level memory allocation drivers for when
15725 ** SQLite will use the standard C-library malloc/realloc/free interface
15726 ** to obtain the memory it needs while adding lots of additional debugging
15727 ** information to each allocation in order to help detect and fix memory
15728 ** leaks and memory usage errors.
15729 **
15730 ** This file contains implementations of the low-level memory allocation
15731 ** routines specified in the sqlite3_mem_methods object.
15732 */
15733
15734 /*
15735 ** This version of the memory allocator is used only if the
15736 ** SQLITE_MEMDEBUG macro is defined
15737 */
15738 #ifdef SQLITE_MEMDEBUG
15739
15740 /*
15741 ** The backtrace functionality is only available with GLIBC
15742 */
15743 #ifdef __GLIBC__
15744   extern int backtrace(void**,int);
15745   extern void backtrace_symbols_fd(void*const*,int,int);
15746 #else
15747 # define backtrace(A,B) 1
15748 # define backtrace_symbols_fd(A,B,C)
15749 #endif
15750 /* #include <stdio.h> */
15751
15752 /*
15753 ** Each memory allocation looks like this:
15754 **
15755 **  ------------------------------------------------------------------------
15756 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15757 **  ------------------------------------------------------------------------
15758 **
15759 ** The application code sees only a pointer to the allocation.  We have
15760 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15761 ** MemBlockHdr tells us the size of the allocation and the number of
15762 ** backtrace pointers.  There is also a guard word at the end of the
15763 ** MemBlockHdr.
15764 */
15765 struct MemBlockHdr {
15766   i64 iSize;                          /* Size of this allocation */
15767   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15768   char nBacktrace;                    /* Number of backtraces on this alloc */
15769   char nBacktraceSlots;               /* Available backtrace slots */
15770   u8 nTitle;                          /* Bytes of title; includes '\0' */
15771   u8 eType;                           /* Allocation type code */
15772   int iForeGuard;                     /* Guard word for sanity */
15773 };
15774
15775 /*
15776 ** Guard words
15777 */
15778 #define FOREGUARD 0x80F5E153
15779 #define REARGUARD 0xE4676B53
15780
15781 /*
15782 ** Number of malloc size increments to track.
15783 */
15784 #define NCSIZE  1000
15785
15786 /*
15787 ** All of the static variables used by this module are collected
15788 ** into a single structure named "mem".  This is to keep the
15789 ** static variables organized and to reduce namespace pollution
15790 ** when this module is combined with other in the amalgamation.
15791 */
15792 static struct {
15793   
15794   /*
15795   ** Mutex to control access to the memory allocation subsystem.
15796   */
15797   sqlite3_mutex *mutex;
15798
15799   /*
15800   ** Head and tail of a linked list of all outstanding allocations
15801   */
15802   struct MemBlockHdr *pFirst;
15803   struct MemBlockHdr *pLast;
15804   
15805   /*
15806   ** The number of levels of backtrace to save in new allocations.
15807   */
15808   int nBacktrace;
15809   void (*xBacktrace)(int, int, void **);
15810
15811   /*
15812   ** Title text to insert in front of each block
15813   */
15814   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15815   char zTitle[100];  /* The title text */
15816
15817   /* 
15818   ** sqlite3MallocDisallow() increments the following counter.
15819   ** sqlite3MallocAllow() decrements it.
15820   */
15821   int disallow; /* Do not allow memory allocation */
15822
15823   /*
15824   ** Gather statistics on the sizes of memory allocations.
15825   ** nAlloc[i] is the number of allocation attempts of i*8
15826   ** bytes.  i==NCSIZE is the number of allocation attempts for
15827   ** sizes more than NCSIZE*8 bytes.
15828   */
15829   int nAlloc[NCSIZE];      /* Total number of allocations */
15830   int nCurrent[NCSIZE];    /* Current number of allocations */
15831   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15832
15833 } mem;
15834
15835
15836 /*
15837 ** Adjust memory usage statistics
15838 */
15839 static void adjustStats(int iSize, int increment){
15840   int i = ROUND8(iSize)/8;
15841   if( i>NCSIZE-1 ){
15842     i = NCSIZE - 1;
15843   }
15844   if( increment>0 ){
15845     mem.nAlloc[i]++;
15846     mem.nCurrent[i]++;
15847     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15848       mem.mxCurrent[i] = mem.nCurrent[i];
15849     }
15850   }else{
15851     mem.nCurrent[i]--;
15852     assert( mem.nCurrent[i]>=0 );
15853   }
15854 }
15855
15856 /*
15857 ** Given an allocation, find the MemBlockHdr for that allocation.
15858 **
15859 ** This routine checks the guards at either end of the allocation and
15860 ** if they are incorrect it asserts.
15861 */
15862 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15863   struct MemBlockHdr *p;
15864   int *pInt;
15865   u8 *pU8;
15866   int nReserve;
15867
15868   p = (struct MemBlockHdr*)pAllocation;
15869   p--;
15870   assert( p->iForeGuard==(int)FOREGUARD );
15871   nReserve = ROUND8(p->iSize);
15872   pInt = (int*)pAllocation;
15873   pU8 = (u8*)pAllocation;
15874   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15875   /* This checks any of the "extra" bytes allocated due
15876   ** to rounding up to an 8 byte boundary to ensure 
15877   ** they haven't been overwritten.
15878   */
15879   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15880   return p;
15881 }
15882
15883 /*
15884 ** Return the number of bytes currently allocated at address p.
15885 */
15886 static int sqlite3MemSize(void *p){
15887   struct MemBlockHdr *pHdr;
15888   if( !p ){
15889     return 0;
15890   }
15891   pHdr = sqlite3MemsysGetHeader(p);
15892   return pHdr->iSize;
15893 }
15894
15895 /*
15896 ** Initialize the memory allocation subsystem.
15897 */
15898 static int sqlite3MemInit(void *NotUsed){
15899   UNUSED_PARAMETER(NotUsed);
15900   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15901   if( !sqlite3GlobalConfig.bMemstat ){
15902     /* If memory status is enabled, then the malloc.c wrapper will already
15903     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15904     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15905   }
15906   return SQLITE_OK;
15907 }
15908
15909 /*
15910 ** Deinitialize the memory allocation subsystem.
15911 */
15912 static void sqlite3MemShutdown(void *NotUsed){
15913   UNUSED_PARAMETER(NotUsed);
15914   mem.mutex = 0;
15915 }
15916
15917 /*
15918 ** Round up a request size to the next valid allocation size.
15919 */
15920 static int sqlite3MemRoundup(int n){
15921   return ROUND8(n);
15922 }
15923
15924 /*
15925 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15926 ** the content of a new memory allocation to unpredictable values and
15927 ** to clear the content of a freed allocation to unpredictable values.
15928 */
15929 static void randomFill(char *pBuf, int nByte){
15930   unsigned int x, y, r;
15931   x = SQLITE_PTR_TO_INT(pBuf);
15932   y = nByte | 1;
15933   while( nByte >= 4 ){
15934     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15935     y = y*1103515245 + 12345;
15936     r = x ^ y;
15937     *(int*)pBuf = r;
15938     pBuf += 4;
15939     nByte -= 4;
15940   }
15941   while( nByte-- > 0 ){
15942     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15943     y = y*1103515245 + 12345;
15944     r = x ^ y;
15945     *(pBuf++) = r & 0xff;
15946   }
15947 }
15948
15949 /*
15950 ** Allocate nByte bytes of memory.
15951 */
15952 static void *sqlite3MemMalloc(int nByte){
15953   struct MemBlockHdr *pHdr;
15954   void **pBt;
15955   char *z;
15956   int *pInt;
15957   void *p = 0;
15958   int totalSize;
15959   int nReserve;
15960   sqlite3_mutex_enter(mem.mutex);
15961   assert( mem.disallow==0 );
15962   nReserve = ROUND8(nByte);
15963   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15964                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15965   p = malloc(totalSize);
15966   if( p ){
15967     z = p;
15968     pBt = (void**)&z[mem.nTitle];
15969     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15970     pHdr->pNext = 0;
15971     pHdr->pPrev = mem.pLast;
15972     if( mem.pLast ){
15973       mem.pLast->pNext = pHdr;
15974     }else{
15975       mem.pFirst = pHdr;
15976     }
15977     mem.pLast = pHdr;
15978     pHdr->iForeGuard = FOREGUARD;
15979     pHdr->eType = MEMTYPE_HEAP;
15980     pHdr->nBacktraceSlots = mem.nBacktrace;
15981     pHdr->nTitle = mem.nTitle;
15982     if( mem.nBacktrace ){
15983       void *aAddr[40];
15984       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15985       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15986       assert(pBt[0]);
15987       if( mem.xBacktrace ){
15988         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15989       }
15990     }else{
15991       pHdr->nBacktrace = 0;
15992     }
15993     if( mem.nTitle ){
15994       memcpy(z, mem.zTitle, mem.nTitle);
15995     }
15996     pHdr->iSize = nByte;
15997     adjustStats(nByte, +1);
15998     pInt = (int*)&pHdr[1];
15999     pInt[nReserve/sizeof(int)] = REARGUARD;
16000     randomFill((char*)pInt, nByte);
16001     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16002     p = (void*)pInt;
16003   }
16004   sqlite3_mutex_leave(mem.mutex);
16005   return p; 
16006 }
16007
16008 /*
16009 ** Free memory.
16010 */
16011 static void sqlite3MemFree(void *pPrior){
16012   struct MemBlockHdr *pHdr;
16013   void **pBt;
16014   char *z;
16015   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
16016        || mem.mutex!=0 );
16017   pHdr = sqlite3MemsysGetHeader(pPrior);
16018   pBt = (void**)pHdr;
16019   pBt -= pHdr->nBacktraceSlots;
16020   sqlite3_mutex_enter(mem.mutex);
16021   if( pHdr->pPrev ){
16022     assert( pHdr->pPrev->pNext==pHdr );
16023     pHdr->pPrev->pNext = pHdr->pNext;
16024   }else{
16025     assert( mem.pFirst==pHdr );
16026     mem.pFirst = pHdr->pNext;
16027   }
16028   if( pHdr->pNext ){
16029     assert( pHdr->pNext->pPrev==pHdr );
16030     pHdr->pNext->pPrev = pHdr->pPrev;
16031   }else{
16032     assert( mem.pLast==pHdr );
16033     mem.pLast = pHdr->pPrev;
16034   }
16035   z = (char*)pBt;
16036   z -= pHdr->nTitle;
16037   adjustStats(pHdr->iSize, -1);
16038   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16039                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
16040   free(z);
16041   sqlite3_mutex_leave(mem.mutex);  
16042 }
16043
16044 /*
16045 ** Change the size of an existing memory allocation.
16046 **
16047 ** For this debugging implementation, we *always* make a copy of the
16048 ** allocation into a new place in memory.  In this way, if the 
16049 ** higher level code is using pointer to the old allocation, it is 
16050 ** much more likely to break and we are much more liking to find
16051 ** the error.
16052 */
16053 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16054   struct MemBlockHdr *pOldHdr;
16055   void *pNew;
16056   assert( mem.disallow==0 );
16057   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16058   pOldHdr = sqlite3MemsysGetHeader(pPrior);
16059   pNew = sqlite3MemMalloc(nByte);
16060   if( pNew ){
16061     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16062     if( nByte>pOldHdr->iSize ){
16063       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16064     }
16065     sqlite3MemFree(pPrior);
16066   }
16067   return pNew;
16068 }
16069
16070 /*
16071 ** Populate the low-level memory allocation function pointers in
16072 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16073 */
16074 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16075   static const sqlite3_mem_methods defaultMethods = {
16076      sqlite3MemMalloc,
16077      sqlite3MemFree,
16078      sqlite3MemRealloc,
16079      sqlite3MemSize,
16080      sqlite3MemRoundup,
16081      sqlite3MemInit,
16082      sqlite3MemShutdown,
16083      0
16084   };
16085   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16086 }
16087
16088 /*
16089 ** Set the "type" of an allocation.
16090 */
16091 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16092   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16093     struct MemBlockHdr *pHdr;
16094     pHdr = sqlite3MemsysGetHeader(p);
16095     assert( pHdr->iForeGuard==FOREGUARD );
16096     pHdr->eType = eType;
16097   }
16098 }
16099
16100 /*
16101 ** Return TRUE if the mask of type in eType matches the type of the
16102 ** allocation p.  Also return true if p==NULL.
16103 **
16104 ** This routine is designed for use within an assert() statement, to
16105 ** verify the type of an allocation.  For example:
16106 **
16107 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16108 */
16109 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16110   int rc = 1;
16111   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16112     struct MemBlockHdr *pHdr;
16113     pHdr = sqlite3MemsysGetHeader(p);
16114     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16115     if( (pHdr->eType&eType)==0 ){
16116       rc = 0;
16117     }
16118   }
16119   return rc;
16120 }
16121
16122 /*
16123 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16124 ** allocation p.  Also return true if p==NULL.
16125 **
16126 ** This routine is designed for use within an assert() statement, to
16127 ** verify the type of an allocation.  For example:
16128 **
16129 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16130 */
16131 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16132   int rc = 1;
16133   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16134     struct MemBlockHdr *pHdr;
16135     pHdr = sqlite3MemsysGetHeader(p);
16136     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16137     if( (pHdr->eType&eType)!=0 ){
16138       rc = 0;
16139     }
16140   }
16141   return rc;
16142 }
16143
16144 /*
16145 ** Set the number of backtrace levels kept for each allocation.
16146 ** A value of zero turns off backtracing.  The number is always rounded
16147 ** up to a multiple of 2.
16148 */
16149 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16150   if( depth<0 ){ depth = 0; }
16151   if( depth>20 ){ depth = 20; }
16152   depth = (depth+1)&0xfe;
16153   mem.nBacktrace = depth;
16154 }
16155
16156 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16157   mem.xBacktrace = xBacktrace;
16158 }
16159
16160 /*
16161 ** Set the title string for subsequent allocations.
16162 */
16163 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16164   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16165   sqlite3_mutex_enter(mem.mutex);
16166   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16167   memcpy(mem.zTitle, zTitle, n);
16168   mem.zTitle[n] = 0;
16169   mem.nTitle = ROUND8(n);
16170   sqlite3_mutex_leave(mem.mutex);
16171 }
16172
16173 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16174   struct MemBlockHdr *pHdr;
16175   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16176     void **pBt = (void**)pHdr;
16177     pBt -= pHdr->nBacktraceSlots;
16178     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16179   }
16180 }
16181
16182 /*
16183 ** Open the file indicated and write a log of all unfreed memory 
16184 ** allocations into that log.
16185 */
16186 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16187   FILE *out;
16188   struct MemBlockHdr *pHdr;
16189   void **pBt;
16190   int i;
16191   out = fopen(zFilename, "w");
16192   if( out==0 ){
16193     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16194                     zFilename);
16195     return;
16196   }
16197   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16198     char *z = (char*)pHdr;
16199     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16200     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16201             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16202     if( pHdr->nBacktrace ){
16203       fflush(out);
16204       pBt = (void**)pHdr;
16205       pBt -= pHdr->nBacktraceSlots;
16206       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16207       fprintf(out, "\n");
16208     }
16209   }
16210   fprintf(out, "COUNTS:\n");
16211   for(i=0; i<NCSIZE-1; i++){
16212     if( mem.nAlloc[i] ){
16213       fprintf(out, "   %5d: %10d %10d %10d\n", 
16214             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16215     }
16216   }
16217   if( mem.nAlloc[NCSIZE-1] ){
16218     fprintf(out, "   %5d: %10d %10d %10d\n",
16219              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16220              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16221   }
16222   fclose(out);
16223 }
16224
16225 /*
16226 ** Return the number of times sqlite3MemMalloc() has been called.
16227 */
16228 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16229   int i;
16230   int nTotal = 0;
16231   for(i=0; i<NCSIZE; i++){
16232     nTotal += mem.nAlloc[i];
16233   }
16234   return nTotal;
16235 }
16236
16237
16238 #endif /* SQLITE_MEMDEBUG */
16239
16240 /************** End of mem2.c ************************************************/
16241 /************** Begin file mem3.c ********************************************/
16242 /*
16243 ** 2007 October 14
16244 **
16245 ** The author disclaims copyright to this source code.  In place of
16246 ** a legal notice, here is a blessing:
16247 **
16248 **    May you do good and not evil.
16249 **    May you find forgiveness for yourself and forgive others.
16250 **    May you share freely, never taking more than you give.
16251 **
16252 *************************************************************************
16253 ** This file contains the C functions that implement a memory
16254 ** allocation subsystem for use by SQLite. 
16255 **
16256 ** This version of the memory allocation subsystem omits all
16257 ** use of malloc(). The SQLite user supplies a block of memory
16258 ** before calling sqlite3_initialize() from which allocations
16259 ** are made and returned by the xMalloc() and xRealloc() 
16260 ** implementations. Once sqlite3_initialize() has been called,
16261 ** the amount of memory available to SQLite is fixed and cannot
16262 ** be changed.
16263 **
16264 ** This version of the memory allocation subsystem is included
16265 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16266 */
16267
16268 /*
16269 ** This version of the memory allocator is only built into the library
16270 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16271 ** mean that the library will use a memory-pool by default, just that
16272 ** it is available. The mempool allocator is activated by calling
16273 ** sqlite3_config().
16274 */
16275 #ifdef SQLITE_ENABLE_MEMSYS3
16276
16277 /*
16278 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16279 */
16280 #define MX_SMALL 10
16281
16282
16283 /*
16284 ** Number of freelist hash slots
16285 */
16286 #define N_HASH  61
16287
16288 /*
16289 ** A memory allocation (also called a "chunk") consists of two or 
16290 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16291 ** a header that is not returned to the user.
16292 **
16293 ** A chunk is two or more blocks that is either checked out or
16294 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16295 ** size of the allocation in blocks if the allocation is free.
16296 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16297 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16298 ** is true if the previous chunk is checked out and false if the
16299 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16300 ** the previous chunk in blocks if the previous chunk is on the
16301 ** freelist. If the previous chunk is checked out, then
16302 ** u.hdr.prevSize can be part of the data for that chunk and should
16303 ** not be read or written.
16304 **
16305 ** We often identify a chunk by its index in mem3.aPool[].  When
16306 ** this is done, the chunk index refers to the second block of
16307 ** the chunk.  In this way, the first chunk has an index of 1.
16308 ** A chunk index of 0 means "no such chunk" and is the equivalent
16309 ** of a NULL pointer.
16310 **
16311 ** The second block of free chunks is of the form u.list.  The
16312 ** two fields form a double-linked list of chunks of related sizes.
16313 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16314 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16315 **
16316 ** The second block of a chunk is user data if the chunk is checked 
16317 ** out.  If a chunk is checked out, the user data may extend into
16318 ** the u.hdr.prevSize value of the following chunk.
16319 */
16320 typedef struct Mem3Block Mem3Block;
16321 struct Mem3Block {
16322   union {
16323     struct {
16324       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16325       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16326     } hdr;
16327     struct {
16328       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16329       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16330     } list;
16331   } u;
16332 };
16333
16334 /*
16335 ** All of the static variables used by this module are collected
16336 ** into a single structure named "mem3".  This is to keep the
16337 ** static variables organized and to reduce namespace pollution
16338 ** when this module is combined with other in the amalgamation.
16339 */
16340 static SQLITE_WSD struct Mem3Global {
16341   /*
16342   ** Memory available for allocation. nPool is the size of the array
16343   ** (in Mem3Blocks) pointed to by aPool less 2.
16344   */
16345   u32 nPool;
16346   Mem3Block *aPool;
16347
16348   /*
16349   ** True if we are evaluating an out-of-memory callback.
16350   */
16351   int alarmBusy;
16352   
16353   /*
16354   ** Mutex to control access to the memory allocation subsystem.
16355   */
16356   sqlite3_mutex *mutex;
16357   
16358   /*
16359   ** The minimum amount of free space that we have seen.
16360   */
16361   u32 mnMaster;
16362
16363   /*
16364   ** iMaster is the index of the master chunk.  Most new allocations
16365   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16366   ** of the current master.  iMaster is 0 if there is not master chunk.
16367   ** The master chunk is not in either the aiHash[] or aiSmall[].
16368   */
16369   u32 iMaster;
16370   u32 szMaster;
16371
16372   /*
16373   ** Array of lists of free blocks according to the block size 
16374   ** for smaller chunks, or a hash on the block size for larger
16375   ** chunks.
16376   */
16377   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16378   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16379 } mem3 = { 97535575 };
16380
16381 #define mem3 GLOBAL(struct Mem3Global, mem3)
16382
16383 /*
16384 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16385 ** on.  *pRoot is the list that i is a member of.
16386 */
16387 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16388   u32 next = mem3.aPool[i].u.list.next;
16389   u32 prev = mem3.aPool[i].u.list.prev;
16390   assert( sqlite3_mutex_held(mem3.mutex) );
16391   if( prev==0 ){
16392     *pRoot = next;
16393   }else{
16394     mem3.aPool[prev].u.list.next = next;
16395   }
16396   if( next ){
16397     mem3.aPool[next].u.list.prev = prev;
16398   }
16399   mem3.aPool[i].u.list.next = 0;
16400   mem3.aPool[i].u.list.prev = 0;
16401 }
16402
16403 /*
16404 ** Unlink the chunk at index i from 
16405 ** whatever list is currently a member of.
16406 */
16407 static void memsys3Unlink(u32 i){
16408   u32 size, hash;
16409   assert( sqlite3_mutex_held(mem3.mutex) );
16410   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16411   assert( i>=1 );
16412   size = mem3.aPool[i-1].u.hdr.size4x/4;
16413   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16414   assert( size>=2 );
16415   if( size <= MX_SMALL ){
16416     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16417   }else{
16418     hash = size % N_HASH;
16419     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16420   }
16421 }
16422
16423 /*
16424 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16425 ** at *pRoot.
16426 */
16427 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16428   assert( sqlite3_mutex_held(mem3.mutex) );
16429   mem3.aPool[i].u.list.next = *pRoot;
16430   mem3.aPool[i].u.list.prev = 0;
16431   if( *pRoot ){
16432     mem3.aPool[*pRoot].u.list.prev = i;
16433   }
16434   *pRoot = i;
16435 }
16436
16437 /*
16438 ** Link the chunk at index i into either the appropriate
16439 ** small chunk list, or into the large chunk hash table.
16440 */
16441 static void memsys3Link(u32 i){
16442   u32 size, hash;
16443   assert( sqlite3_mutex_held(mem3.mutex) );
16444   assert( i>=1 );
16445   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16446   size = mem3.aPool[i-1].u.hdr.size4x/4;
16447   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16448   assert( size>=2 );
16449   if( size <= MX_SMALL ){
16450     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16451   }else{
16452     hash = size % N_HASH;
16453     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16454   }
16455 }
16456
16457 /*
16458 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16459 ** will already be held (obtained by code in malloc.c) if
16460 ** sqlite3GlobalConfig.bMemStat is true.
16461 */
16462 static void memsys3Enter(void){
16463   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16464     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16465   }
16466   sqlite3_mutex_enter(mem3.mutex);
16467 }
16468 static void memsys3Leave(void){
16469   sqlite3_mutex_leave(mem3.mutex);
16470 }
16471
16472 /*
16473 ** Called when we are unable to satisfy an allocation of nBytes.
16474 */
16475 static void memsys3OutOfMemory(int nByte){
16476   if( !mem3.alarmBusy ){
16477     mem3.alarmBusy = 1;
16478     assert( sqlite3_mutex_held(mem3.mutex) );
16479     sqlite3_mutex_leave(mem3.mutex);
16480     sqlite3_release_memory(nByte);
16481     sqlite3_mutex_enter(mem3.mutex);
16482     mem3.alarmBusy = 0;
16483   }
16484 }
16485
16486
16487 /*
16488 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16489 ** size parameters for check-out and return a pointer to the 
16490 ** user portion of the chunk.
16491 */
16492 static void *memsys3Checkout(u32 i, u32 nBlock){
16493   u32 x;
16494   assert( sqlite3_mutex_held(mem3.mutex) );
16495   assert( i>=1 );
16496   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16497   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16498   x = mem3.aPool[i-1].u.hdr.size4x;
16499   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16500   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16501   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16502   return &mem3.aPool[i];
16503 }
16504
16505 /*
16506 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16507 ** Return a pointer to the new allocation.  Or, if the master chunk
16508 ** is not large enough, return 0.
16509 */
16510 static void *memsys3FromMaster(u32 nBlock){
16511   assert( sqlite3_mutex_held(mem3.mutex) );
16512   assert( mem3.szMaster>=nBlock );
16513   if( nBlock>=mem3.szMaster-1 ){
16514     /* Use the entire master */
16515     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16516     mem3.iMaster = 0;
16517     mem3.szMaster = 0;
16518     mem3.mnMaster = 0;
16519     return p;
16520   }else{
16521     /* Split the master block.  Return the tail. */
16522     u32 newi, x;
16523     newi = mem3.iMaster + mem3.szMaster - nBlock;
16524     assert( newi > mem3.iMaster+1 );
16525     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16526     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16527     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16528     mem3.szMaster -= nBlock;
16529     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16530     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16531     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16532     if( mem3.szMaster < mem3.mnMaster ){
16533       mem3.mnMaster = mem3.szMaster;
16534     }
16535     return (void*)&mem3.aPool[newi];
16536   }
16537 }
16538
16539 /*
16540 ** *pRoot is the head of a list of free chunks of the same size
16541 ** or same size hash.  In other words, *pRoot is an entry in either
16542 ** mem3.aiSmall[] or mem3.aiHash[].  
16543 **
16544 ** This routine examines all entries on the given list and tries
16545 ** to coalesce each entries with adjacent free chunks.  
16546 **
16547 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16548 ** the current mem3.iMaster with the new larger chunk.  In order for
16549 ** this mem3.iMaster replacement to work, the master chunk must be
16550 ** linked into the hash tables.  That is not the normal state of
16551 ** affairs, of course.  The calling routine must link the master
16552 ** chunk before invoking this routine, then must unlink the (possibly
16553 ** changed) master chunk once this routine has finished.
16554 */
16555 static void memsys3Merge(u32 *pRoot){
16556   u32 iNext, prev, size, i, x;
16557
16558   assert( sqlite3_mutex_held(mem3.mutex) );
16559   for(i=*pRoot; i>0; i=iNext){
16560     iNext = mem3.aPool[i].u.list.next;
16561     size = mem3.aPool[i-1].u.hdr.size4x;
16562     assert( (size&1)==0 );
16563     if( (size&2)==0 ){
16564       memsys3UnlinkFromList(i, pRoot);
16565       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16566       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16567       if( prev==iNext ){
16568         iNext = mem3.aPool[prev].u.list.next;
16569       }
16570       memsys3Unlink(prev);
16571       size = i + size/4 - prev;
16572       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16573       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16574       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16575       memsys3Link(prev);
16576       i = prev;
16577     }else{
16578       size /= 4;
16579     }
16580     if( size>mem3.szMaster ){
16581       mem3.iMaster = i;
16582       mem3.szMaster = size;
16583     }
16584   }
16585 }
16586
16587 /*
16588 ** Return a block of memory of at least nBytes in size.
16589 ** Return NULL if unable.
16590 **
16591 ** This function assumes that the necessary mutexes, if any, are
16592 ** already held by the caller. Hence "Unsafe".
16593 */
16594 static void *memsys3MallocUnsafe(int nByte){
16595   u32 i;
16596   u32 nBlock;
16597   u32 toFree;
16598
16599   assert( sqlite3_mutex_held(mem3.mutex) );
16600   assert( sizeof(Mem3Block)==8 );
16601   if( nByte<=12 ){
16602     nBlock = 2;
16603   }else{
16604     nBlock = (nByte + 11)/8;
16605   }
16606   assert( nBlock>=2 );
16607
16608   /* STEP 1:
16609   ** Look for an entry of the correct size in either the small
16610   ** chunk table or in the large chunk hash table.  This is
16611   ** successful most of the time (about 9 times out of 10).
16612   */
16613   if( nBlock <= MX_SMALL ){
16614     i = mem3.aiSmall[nBlock-2];
16615     if( i>0 ){
16616       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16617       return memsys3Checkout(i, nBlock);
16618     }
16619   }else{
16620     int hash = nBlock % N_HASH;
16621     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16622       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16623         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16624         return memsys3Checkout(i, nBlock);
16625       }
16626     }
16627   }
16628
16629   /* STEP 2:
16630   ** Try to satisfy the allocation by carving a piece off of the end
16631   ** of the master chunk.  This step usually works if step 1 fails.
16632   */
16633   if( mem3.szMaster>=nBlock ){
16634     return memsys3FromMaster(nBlock);
16635   }
16636
16637
16638   /* STEP 3:  
16639   ** Loop through the entire memory pool.  Coalesce adjacent free
16640   ** chunks.  Recompute the master chunk as the largest free chunk.
16641   ** Then try again to satisfy the allocation by carving a piece off
16642   ** of the end of the master chunk.  This step happens very
16643   ** rarely (we hope!)
16644   */
16645   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16646     memsys3OutOfMemory(toFree);
16647     if( mem3.iMaster ){
16648       memsys3Link(mem3.iMaster);
16649       mem3.iMaster = 0;
16650       mem3.szMaster = 0;
16651     }
16652     for(i=0; i<N_HASH; i++){
16653       memsys3Merge(&mem3.aiHash[i]);
16654     }
16655     for(i=0; i<MX_SMALL-1; i++){
16656       memsys3Merge(&mem3.aiSmall[i]);
16657     }
16658     if( mem3.szMaster ){
16659       memsys3Unlink(mem3.iMaster);
16660       if( mem3.szMaster>=nBlock ){
16661         return memsys3FromMaster(nBlock);
16662       }
16663     }
16664   }
16665
16666   /* If none of the above worked, then we fail. */
16667   return 0;
16668 }
16669
16670 /*
16671 ** Free an outstanding memory allocation.
16672 **
16673 ** This function assumes that the necessary mutexes, if any, are
16674 ** already held by the caller. Hence "Unsafe".
16675 */
16676 static void memsys3FreeUnsafe(void *pOld){
16677   Mem3Block *p = (Mem3Block*)pOld;
16678   int i;
16679   u32 size, x;
16680   assert( sqlite3_mutex_held(mem3.mutex) );
16681   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16682   i = p - mem3.aPool;
16683   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16684   size = mem3.aPool[i-1].u.hdr.size4x/4;
16685   assert( i+size<=mem3.nPool+1 );
16686   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16687   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16688   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16689   memsys3Link(i);
16690
16691   /* Try to expand the master using the newly freed chunk */
16692   if( mem3.iMaster ){
16693     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16694       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16695       mem3.iMaster -= size;
16696       mem3.szMaster += size;
16697       memsys3Unlink(mem3.iMaster);
16698       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16699       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16700       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16701     }
16702     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16703     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16704       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16705       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16706       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16707       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16708     }
16709   }
16710 }
16711
16712 /*
16713 ** Return the size of an outstanding allocation, in bytes.  The
16714 ** size returned omits the 8-byte header overhead.  This only
16715 ** works for chunks that are currently checked out.
16716 */
16717 static int memsys3Size(void *p){
16718   Mem3Block *pBlock;
16719   if( p==0 ) return 0;
16720   pBlock = (Mem3Block*)p;
16721   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16722   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16723 }
16724
16725 /*
16726 ** Round up a request size to the next valid allocation size.
16727 */
16728 static int memsys3Roundup(int n){
16729   if( n<=12 ){
16730     return 12;
16731   }else{
16732     return ((n+11)&~7) - 4;
16733   }
16734 }
16735
16736 /*
16737 ** Allocate nBytes of memory.
16738 */
16739 static void *memsys3Malloc(int nBytes){
16740   sqlite3_int64 *p;
16741   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16742   memsys3Enter();
16743   p = memsys3MallocUnsafe(nBytes);
16744   memsys3Leave();
16745   return (void*)p; 
16746 }
16747
16748 /*
16749 ** Free memory.
16750 */
16751 static void memsys3Free(void *pPrior){
16752   assert( pPrior );
16753   memsys3Enter();
16754   memsys3FreeUnsafe(pPrior);
16755   memsys3Leave();
16756 }
16757
16758 /*
16759 ** Change the size of an existing memory allocation
16760 */
16761 static void *memsys3Realloc(void *pPrior, int nBytes){
16762   int nOld;
16763   void *p;
16764   if( pPrior==0 ){
16765     return sqlite3_malloc(nBytes);
16766   }
16767   if( nBytes<=0 ){
16768     sqlite3_free(pPrior);
16769     return 0;
16770   }
16771   nOld = memsys3Size(pPrior);
16772   if( nBytes<=nOld && nBytes>=nOld-128 ){
16773     return pPrior;
16774   }
16775   memsys3Enter();
16776   p = memsys3MallocUnsafe(nBytes);
16777   if( p ){
16778     if( nOld<nBytes ){
16779       memcpy(p, pPrior, nOld);
16780     }else{
16781       memcpy(p, pPrior, nBytes);
16782     }
16783     memsys3FreeUnsafe(pPrior);
16784   }
16785   memsys3Leave();
16786   return p;
16787 }
16788
16789 /*
16790 ** Initialize this module.
16791 */
16792 static int memsys3Init(void *NotUsed){
16793   UNUSED_PARAMETER(NotUsed);
16794   if( !sqlite3GlobalConfig.pHeap ){
16795     return SQLITE_ERROR;
16796   }
16797
16798   /* Store a pointer to the memory block in global structure mem3. */
16799   assert( sizeof(Mem3Block)==8 );
16800   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16801   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16802
16803   /* Initialize the master block. */
16804   mem3.szMaster = mem3.nPool;
16805   mem3.mnMaster = mem3.szMaster;
16806   mem3.iMaster = 1;
16807   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16808   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16809   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16810
16811   return SQLITE_OK;
16812 }
16813
16814 /*
16815 ** Deinitialize this module.
16816 */
16817 static void memsys3Shutdown(void *NotUsed){
16818   UNUSED_PARAMETER(NotUsed);
16819   mem3.mutex = 0;
16820   return;
16821 }
16822
16823
16824
16825 /*
16826 ** Open the file indicated and write a log of all unfreed memory 
16827 ** allocations into that log.
16828 */
16829 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16830 #ifdef SQLITE_DEBUG
16831   FILE *out;
16832   u32 i, j;
16833   u32 size;
16834   if( zFilename==0 || zFilename[0]==0 ){
16835     out = stdout;
16836   }else{
16837     out = fopen(zFilename, "w");
16838     if( out==0 ){
16839       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16840                       zFilename);
16841       return;
16842     }
16843   }
16844   memsys3Enter();
16845   fprintf(out, "CHUNKS:\n");
16846   for(i=1; i<=mem3.nPool; i+=size/4){
16847     size = mem3.aPool[i-1].u.hdr.size4x;
16848     if( size/4<=1 ){
16849       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16850       assert( 0 );
16851       break;
16852     }
16853     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16854       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16855       assert( 0 );
16856       break;
16857     }
16858     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16859       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16860       assert( 0 );
16861       break;
16862     }
16863     if( size&1 ){
16864       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16865     }else{
16866       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16867                   i==mem3.iMaster ? " **master**" : "");
16868     }
16869   }
16870   for(i=0; i<MX_SMALL-1; i++){
16871     if( mem3.aiSmall[i]==0 ) continue;
16872     fprintf(out, "small(%2d):", i);
16873     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16874       fprintf(out, " %p(%d)", &mem3.aPool[j],
16875               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16876     }
16877     fprintf(out, "\n"); 
16878   }
16879   for(i=0; i<N_HASH; i++){
16880     if( mem3.aiHash[i]==0 ) continue;
16881     fprintf(out, "hash(%2d):", i);
16882     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16883       fprintf(out, " %p(%d)", &mem3.aPool[j],
16884               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16885     }
16886     fprintf(out, "\n"); 
16887   }
16888   fprintf(out, "master=%d\n", mem3.iMaster);
16889   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16890   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16891   sqlite3_mutex_leave(mem3.mutex);
16892   if( out==stdout ){
16893     fflush(stdout);
16894   }else{
16895     fclose(out);
16896   }
16897 #else
16898   UNUSED_PARAMETER(zFilename);
16899 #endif
16900 }
16901
16902 /*
16903 ** This routine is the only routine in this file with external 
16904 ** linkage.
16905 **
16906 ** Populate the low-level memory allocation function pointers in
16907 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16908 ** arguments specify the block of memory to manage.
16909 **
16910 ** This routine is only called by sqlite3_config(), and therefore
16911 ** is not required to be threadsafe (it is not).
16912 */
16913 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16914   static const sqlite3_mem_methods mempoolMethods = {
16915      memsys3Malloc,
16916      memsys3Free,
16917      memsys3Realloc,
16918      memsys3Size,
16919      memsys3Roundup,
16920      memsys3Init,
16921      memsys3Shutdown,
16922      0
16923   };
16924   return &mempoolMethods;
16925 }
16926
16927 #endif /* SQLITE_ENABLE_MEMSYS3 */
16928
16929 /************** End of mem3.c ************************************************/
16930 /************** Begin file mem5.c ********************************************/
16931 /*
16932 ** 2007 October 14
16933 **
16934 ** The author disclaims copyright to this source code.  In place of
16935 ** a legal notice, here is a blessing:
16936 **
16937 **    May you do good and not evil.
16938 **    May you find forgiveness for yourself and forgive others.
16939 **    May you share freely, never taking more than you give.
16940 **
16941 *************************************************************************
16942 ** This file contains the C functions that implement a memory
16943 ** allocation subsystem for use by SQLite. 
16944 **
16945 ** This version of the memory allocation subsystem omits all
16946 ** use of malloc(). The application gives SQLite a block of memory
16947 ** before calling sqlite3_initialize() from which allocations
16948 ** are made and returned by the xMalloc() and xRealloc() 
16949 ** implementations. Once sqlite3_initialize() has been called,
16950 ** the amount of memory available to SQLite is fixed and cannot
16951 ** be changed.
16952 **
16953 ** This version of the memory allocation subsystem is included
16954 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16955 **
16956 ** This memory allocator uses the following algorithm:
16957 **
16958 **   1.  All memory allocations sizes are rounded up to a power of 2.
16959 **
16960 **   2.  If two adjacent free blocks are the halves of a larger block,
16961 **       then the two blocks are coalesed into the single larger block.
16962 **
16963 **   3.  New memory is allocated from the first available free block.
16964 **
16965 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16966 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16967 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16968 ** 
16969 ** Let n be the size of the largest allocation divided by the minimum
16970 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
16971 ** be the maximum amount of memory ever outstanding at one time.  Let
16972 ** N be the total amount of memory available for allocation.  Robson
16973 ** proved that this memory allocator will never breakdown due to 
16974 ** fragmentation as long as the following constraint holds:
16975 **
16976 **      N >=  M*(1 + log2(n)/2) - n + 1
16977 **
16978 ** The sqlite3_status() logic tracks the maximum values of n and M so
16979 ** that an application can, at any time, verify this constraint.
16980 */
16981
16982 /*
16983 ** This version of the memory allocator is used only when 
16984 ** SQLITE_ENABLE_MEMSYS5 is defined.
16985 */
16986 #ifdef SQLITE_ENABLE_MEMSYS5
16987
16988 /*
16989 ** A minimum allocation is an instance of the following structure.
16990 ** Larger allocations are an array of these structures where the
16991 ** size of the array is a power of 2.
16992 **
16993 ** The size of this object must be a power of two.  That fact is
16994 ** verified in memsys5Init().
16995 */
16996 typedef struct Mem5Link Mem5Link;
16997 struct Mem5Link {
16998   int next;       /* Index of next free chunk */
16999   int prev;       /* Index of previous free chunk */
17000 };
17001
17002 /*
17003 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17004 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17005 ** it is not actually possible to reach this limit.
17006 */
17007 #define LOGMAX 30
17008
17009 /*
17010 ** Masks used for mem5.aCtrl[] elements.
17011 */
17012 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17013 #define CTRL_FREE     0x20    /* True if not checked out */
17014
17015 /*
17016 ** All of the static variables used by this module are collected
17017 ** into a single structure named "mem5".  This is to keep the
17018 ** static variables organized and to reduce namespace pollution
17019 ** when this module is combined with other in the amalgamation.
17020 */
17021 static SQLITE_WSD struct Mem5Global {
17022   /*
17023   ** Memory available for allocation
17024   */
17025   int szAtom;      /* Smallest possible allocation in bytes */
17026   int nBlock;      /* Number of szAtom sized blocks in zPool */
17027   u8 *zPool;       /* Memory available to be allocated */
17028   
17029   /*
17030   ** Mutex to control access to the memory allocation subsystem.
17031   */
17032   sqlite3_mutex *mutex;
17033
17034   /*
17035   ** Performance statistics
17036   */
17037   u64 nAlloc;         /* Total number of calls to malloc */
17038   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17039   u64 totalExcess;    /* Total internal fragmentation */
17040   u32 currentOut;     /* Current checkout, including internal fragmentation */
17041   u32 currentCount;   /* Current number of distinct checkouts */
17042   u32 maxOut;         /* Maximum instantaneous currentOut */
17043   u32 maxCount;       /* Maximum instantaneous currentCount */
17044   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17045   
17046   /*
17047   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17048   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17049   ** and so forth.
17050   */
17051   int aiFreelist[LOGMAX+1];
17052
17053   /*
17054   ** Space for tracking which blocks are checked out and the size
17055   ** of each block.  One byte per block.
17056   */
17057   u8 *aCtrl;
17058
17059 } mem5;
17060
17061 /*
17062 ** Access the static variable through a macro for SQLITE_OMIT_WSD
17063 */
17064 #define mem5 GLOBAL(struct Mem5Global, mem5)
17065
17066 /*
17067 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17068 ** structures, return a pointer to the idx-th such lik.
17069 */
17070 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17071
17072 /*
17073 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17074 ** on.  It should be found on mem5.aiFreelist[iLogsize].
17075 */
17076 static void memsys5Unlink(int i, int iLogsize){
17077   int next, prev;
17078   assert( i>=0 && i<mem5.nBlock );
17079   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17080   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17081
17082   next = MEM5LINK(i)->next;
17083   prev = MEM5LINK(i)->prev;
17084   if( prev<0 ){
17085     mem5.aiFreelist[iLogsize] = next;
17086   }else{
17087     MEM5LINK(prev)->next = next;
17088   }
17089   if( next>=0 ){
17090     MEM5LINK(next)->prev = prev;
17091   }
17092 }
17093
17094 /*
17095 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17096 ** free list.
17097 */
17098 static void memsys5Link(int i, int iLogsize){
17099   int x;
17100   assert( sqlite3_mutex_held(mem5.mutex) );
17101   assert( i>=0 && i<mem5.nBlock );
17102   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17103   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17104
17105   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17106   MEM5LINK(i)->prev = -1;
17107   if( x>=0 ){
17108     assert( x<mem5.nBlock );
17109     MEM5LINK(x)->prev = i;
17110   }
17111   mem5.aiFreelist[iLogsize] = i;
17112 }
17113
17114 /*
17115 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17116 ** will already be held (obtained by code in malloc.c) if
17117 ** sqlite3GlobalConfig.bMemStat is true.
17118 */
17119 static void memsys5Enter(void){
17120   sqlite3_mutex_enter(mem5.mutex);
17121 }
17122 static void memsys5Leave(void){
17123   sqlite3_mutex_leave(mem5.mutex);
17124 }
17125
17126 /*
17127 ** Return the size of an outstanding allocation, in bytes.  The
17128 ** size returned omits the 8-byte header overhead.  This only
17129 ** works for chunks that are currently checked out.
17130 */
17131 static int memsys5Size(void *p){
17132   int iSize = 0;
17133   if( p ){
17134     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17135     assert( i>=0 && i<mem5.nBlock );
17136     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17137   }
17138   return iSize;
17139 }
17140
17141 /*
17142 ** Find the first entry on the freelist iLogsize.  Unlink that
17143 ** entry and return its index. 
17144 */
17145 static int memsys5UnlinkFirst(int iLogsize){
17146   int i;
17147   int iFirst;
17148
17149   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17150   i = iFirst = mem5.aiFreelist[iLogsize];
17151   assert( iFirst>=0 );
17152   while( i>0 ){
17153     if( i<iFirst ) iFirst = i;
17154     i = MEM5LINK(i)->next;
17155   }
17156   memsys5Unlink(iFirst, iLogsize);
17157   return iFirst;
17158 }
17159
17160 /*
17161 ** Return a block of memory of at least nBytes in size.
17162 ** Return NULL if unable.  Return NULL if nBytes==0.
17163 **
17164 ** The caller guarantees that nByte positive.
17165 **
17166 ** The caller has obtained a mutex prior to invoking this
17167 ** routine so there is never any chance that two or more
17168 ** threads can be in this routine at the same time.
17169 */
17170 static void *memsys5MallocUnsafe(int nByte){
17171   int i;           /* Index of a mem5.aPool[] slot */
17172   int iBin;        /* Index into mem5.aiFreelist[] */
17173   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17174   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17175
17176   /* nByte must be a positive */
17177   assert( nByte>0 );
17178
17179   /* Keep track of the maximum allocation request.  Even unfulfilled
17180   ** requests are counted */
17181   if( (u32)nByte>mem5.maxRequest ){
17182     mem5.maxRequest = nByte;
17183   }
17184
17185   /* Abort if the requested allocation size is larger than the largest
17186   ** power of two that we can represent using 32-bit signed integers.
17187   */
17188   if( nByte > 0x40000000 ){
17189     return 0;
17190   }
17191
17192   /* Round nByte up to the next valid power of two */
17193   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17194
17195   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17196   ** block.  If not, then split a block of the next larger power of
17197   ** two in order to create a new free block of size iLogsize.
17198   */
17199   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17200   if( iBin>LOGMAX ){
17201     testcase( sqlite3GlobalConfig.xLog!=0 );
17202     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17203     return 0;
17204   }
17205   i = memsys5UnlinkFirst(iBin);
17206   while( iBin>iLogsize ){
17207     int newSize;
17208
17209     iBin--;
17210     newSize = 1 << iBin;
17211     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17212     memsys5Link(i+newSize, iBin);
17213   }
17214   mem5.aCtrl[i] = iLogsize;
17215
17216   /* Update allocator performance statistics. */
17217   mem5.nAlloc++;
17218   mem5.totalAlloc += iFullSz;
17219   mem5.totalExcess += iFullSz - nByte;
17220   mem5.currentCount++;
17221   mem5.currentOut += iFullSz;
17222   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17223   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17224
17225   /* Return a pointer to the allocated memory. */
17226   return (void*)&mem5.zPool[i*mem5.szAtom];
17227 }
17228
17229 /*
17230 ** Free an outstanding memory allocation.
17231 */
17232 static void memsys5FreeUnsafe(void *pOld){
17233   u32 size, iLogsize;
17234   int iBlock;
17235
17236   /* Set iBlock to the index of the block pointed to by pOld in 
17237   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17238   */
17239   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17240
17241   /* Check that the pointer pOld points to a valid, non-free block. */
17242   assert( iBlock>=0 && iBlock<mem5.nBlock );
17243   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17244   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17245
17246   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17247   size = 1<<iLogsize;
17248   assert( iBlock+size-1<(u32)mem5.nBlock );
17249
17250   mem5.aCtrl[iBlock] |= CTRL_FREE;
17251   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17252   assert( mem5.currentCount>0 );
17253   assert( mem5.currentOut>=(size*mem5.szAtom) );
17254   mem5.currentCount--;
17255   mem5.currentOut -= size*mem5.szAtom;
17256   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17257   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17258
17259   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17260   while( ALWAYS(iLogsize<LOGMAX) ){
17261     int iBuddy;
17262     if( (iBlock>>iLogsize) & 1 ){
17263       iBuddy = iBlock - size;
17264     }else{
17265       iBuddy = iBlock + size;
17266     }
17267     assert( iBuddy>=0 );
17268     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17269     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17270     memsys5Unlink(iBuddy, iLogsize);
17271     iLogsize++;
17272     if( iBuddy<iBlock ){
17273       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17274       mem5.aCtrl[iBlock] = 0;
17275       iBlock = iBuddy;
17276     }else{
17277       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17278       mem5.aCtrl[iBuddy] = 0;
17279     }
17280     size *= 2;
17281   }
17282   memsys5Link(iBlock, iLogsize);
17283 }
17284
17285 /*
17286 ** Allocate nBytes of memory
17287 */
17288 static void *memsys5Malloc(int nBytes){
17289   sqlite3_int64 *p = 0;
17290   if( nBytes>0 ){
17291     memsys5Enter();
17292     p = memsys5MallocUnsafe(nBytes);
17293     memsys5Leave();
17294   }
17295   return (void*)p; 
17296 }
17297
17298 /*
17299 ** Free memory.
17300 **
17301 ** The outer layer memory allocator prevents this routine from
17302 ** being called with pPrior==0.
17303 */
17304 static void memsys5Free(void *pPrior){
17305   assert( pPrior!=0 );
17306   memsys5Enter();
17307   memsys5FreeUnsafe(pPrior);
17308   memsys5Leave();  
17309 }
17310
17311 /*
17312 ** Change the size of an existing memory allocation.
17313 **
17314 ** The outer layer memory allocator prevents this routine from
17315 ** being called with pPrior==0.  
17316 **
17317 ** nBytes is always a value obtained from a prior call to
17318 ** memsys5Round().  Hence nBytes is always a non-negative power
17319 ** of two.  If nBytes==0 that means that an oversize allocation
17320 ** (an allocation larger than 0x40000000) was requested and this
17321 ** routine should return 0 without freeing pPrior.
17322 */
17323 static void *memsys5Realloc(void *pPrior, int nBytes){
17324   int nOld;
17325   void *p;
17326   assert( pPrior!=0 );
17327   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17328   assert( nBytes>=0 );
17329   if( nBytes==0 ){
17330     return 0;
17331   }
17332   nOld = memsys5Size(pPrior);
17333   if( nBytes<=nOld ){
17334     return pPrior;
17335   }
17336   memsys5Enter();
17337   p = memsys5MallocUnsafe(nBytes);
17338   if( p ){
17339     memcpy(p, pPrior, nOld);
17340     memsys5FreeUnsafe(pPrior);
17341   }
17342   memsys5Leave();
17343   return p;
17344 }
17345
17346 /*
17347 ** Round up a request size to the next valid allocation size.  If
17348 ** the allocation is too large to be handled by this allocation system,
17349 ** return 0.
17350 **
17351 ** All allocations must be a power of two and must be expressed by a
17352 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17353 ** or 1073741824 bytes.
17354 */
17355 static int memsys5Roundup(int n){
17356   int iFullSz;
17357   if( n > 0x40000000 ) return 0;
17358   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17359   return iFullSz;
17360 }
17361
17362 /*
17363 ** Return the ceiling of the logarithm base 2 of iValue.
17364 **
17365 ** Examples:   memsys5Log(1) -> 0
17366 **             memsys5Log(2) -> 1
17367 **             memsys5Log(4) -> 2
17368 **             memsys5Log(5) -> 3
17369 **             memsys5Log(8) -> 3
17370 **             memsys5Log(9) -> 4
17371 */
17372 static int memsys5Log(int iValue){
17373   int iLog;
17374   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17375   return iLog;
17376 }
17377
17378 /*
17379 ** Initialize the memory allocator.
17380 **
17381 ** This routine is not threadsafe.  The caller must be holding a mutex
17382 ** to prevent multiple threads from entering at the same time.
17383 */
17384 static int memsys5Init(void *NotUsed){
17385   int ii;            /* Loop counter */
17386   int nByte;         /* Number of bytes of memory available to this allocator */
17387   u8 *zByte;         /* Memory usable by this allocator */
17388   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17389   int iOffset;       /* An offset into mem5.aCtrl[] */
17390
17391   UNUSED_PARAMETER(NotUsed);
17392
17393   /* For the purposes of this routine, disable the mutex */
17394   mem5.mutex = 0;
17395
17396   /* The size of a Mem5Link object must be a power of two.  Verify that
17397   ** this is case.
17398   */
17399   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17400
17401   nByte = sqlite3GlobalConfig.nHeap;
17402   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17403   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17404
17405   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17406   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17407   mem5.szAtom = (1<<nMinLog);
17408   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17409     mem5.szAtom = mem5.szAtom << 1;
17410   }
17411
17412   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17413   mem5.zPool = zByte;
17414   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17415
17416   for(ii=0; ii<=LOGMAX; ii++){
17417     mem5.aiFreelist[ii] = -1;
17418   }
17419
17420   iOffset = 0;
17421   for(ii=LOGMAX; ii>=0; ii--){
17422     int nAlloc = (1<<ii);
17423     if( (iOffset+nAlloc)<=mem5.nBlock ){
17424       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17425       memsys5Link(iOffset, ii);
17426       iOffset += nAlloc;
17427     }
17428     assert((iOffset+nAlloc)>mem5.nBlock);
17429   }
17430
17431   /* If a mutex is required for normal operation, allocate one */
17432   if( sqlite3GlobalConfig.bMemstat==0 ){
17433     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17434   }
17435
17436   return SQLITE_OK;
17437 }
17438
17439 /*
17440 ** Deinitialize this module.
17441 */
17442 static void memsys5Shutdown(void *NotUsed){
17443   UNUSED_PARAMETER(NotUsed);
17444   mem5.mutex = 0;
17445   return;
17446 }
17447
17448 #ifdef SQLITE_TEST
17449 /*
17450 ** Open the file indicated and write a log of all unfreed memory 
17451 ** allocations into that log.
17452 */
17453 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17454   FILE *out;
17455   int i, j, n;
17456   int nMinLog;
17457
17458   if( zFilename==0 || zFilename[0]==0 ){
17459     out = stdout;
17460   }else{
17461     out = fopen(zFilename, "w");
17462     if( out==0 ){
17463       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17464                       zFilename);
17465       return;
17466     }
17467   }
17468   memsys5Enter();
17469   nMinLog = memsys5Log(mem5.szAtom);
17470   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17471     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17472     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17473   }
17474   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17475   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17476   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17477   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17478   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17479   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17480   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17481   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17482   memsys5Leave();
17483   if( out==stdout ){
17484     fflush(stdout);
17485   }else{
17486     fclose(out);
17487   }
17488 }
17489 #endif
17490
17491 /*
17492 ** This routine is the only routine in this file with external 
17493 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17494 ** struct populated with the memsys5 methods.
17495 */
17496 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17497   static const sqlite3_mem_methods memsys5Methods = {
17498      memsys5Malloc,
17499      memsys5Free,
17500      memsys5Realloc,
17501      memsys5Size,
17502      memsys5Roundup,
17503      memsys5Init,
17504      memsys5Shutdown,
17505      0
17506   };
17507   return &memsys5Methods;
17508 }
17509
17510 #endif /* SQLITE_ENABLE_MEMSYS5 */
17511
17512 /************** End of mem5.c ************************************************/
17513 /************** Begin file mutex.c *******************************************/
17514 /*
17515 ** 2007 August 14
17516 **
17517 ** The author disclaims copyright to this source code.  In place of
17518 ** a legal notice, here is a blessing:
17519 **
17520 **    May you do good and not evil.
17521 **    May you find forgiveness for yourself and forgive others.
17522 **    May you share freely, never taking more than you give.
17523 **
17524 *************************************************************************
17525 ** This file contains the C functions that implement mutexes.
17526 **
17527 ** This file contains code that is common across all mutex implementations.
17528 */
17529
17530 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17531 /*
17532 ** For debugging purposes, record when the mutex subsystem is initialized
17533 ** and uninitialized so that we can assert() if there is an attempt to
17534 ** allocate a mutex while the system is uninitialized.
17535 */
17536 static SQLITE_WSD int mutexIsInit = 0;
17537 #endif /* SQLITE_DEBUG */
17538
17539
17540 #ifndef SQLITE_MUTEX_OMIT
17541 /*
17542 ** Initialize the mutex system.
17543 */
17544 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17545   int rc = SQLITE_OK;
17546   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17547     /* If the xMutexAlloc method has not been set, then the user did not
17548     ** install a mutex implementation via sqlite3_config() prior to 
17549     ** sqlite3_initialize() being called. This block copies pointers to
17550     ** the default implementation into the sqlite3GlobalConfig structure.
17551     */
17552     sqlite3_mutex_methods const *pFrom;
17553     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17554
17555     if( sqlite3GlobalConfig.bCoreMutex ){
17556       pFrom = sqlite3DefaultMutex();
17557     }else{
17558       pFrom = sqlite3NoopMutex();
17559     }
17560     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17561     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17562            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17563     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17564   }
17565   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17566
17567 #ifdef SQLITE_DEBUG
17568   GLOBAL(int, mutexIsInit) = 1;
17569 #endif
17570
17571   return rc;
17572 }
17573
17574 /*
17575 ** Shutdown the mutex system. This call frees resources allocated by
17576 ** sqlite3MutexInit().
17577 */
17578 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17579   int rc = SQLITE_OK;
17580   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17581     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17582   }
17583
17584 #ifdef SQLITE_DEBUG
17585   GLOBAL(int, mutexIsInit) = 0;
17586 #endif
17587
17588   return rc;
17589 }
17590
17591 /*
17592 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17593 */
17594 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17595 #ifndef SQLITE_OMIT_AUTOINIT
17596   if( sqlite3_initialize() ) return 0;
17597 #endif
17598   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17599 }
17600
17601 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17602   if( !sqlite3GlobalConfig.bCoreMutex ){
17603     return 0;
17604   }
17605   assert( GLOBAL(int, mutexIsInit) );
17606   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17607 }
17608
17609 /*
17610 ** Free a dynamic mutex.
17611 */
17612 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17613   if( p ){
17614     sqlite3GlobalConfig.mutex.xMutexFree(p);
17615   }
17616 }
17617
17618 /*
17619 ** Obtain the mutex p. If some other thread already has the mutex, block
17620 ** until it can be obtained.
17621 */
17622 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17623   if( p ){
17624     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17625   }
17626 }
17627
17628 /*
17629 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17630 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17631 */
17632 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17633   int rc = SQLITE_OK;
17634   if( p ){
17635     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17636   }
17637   return rc;
17638 }
17639
17640 /*
17641 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17642 ** entered by the same thread.  The behavior is undefined if the mutex 
17643 ** is not currently entered. If a NULL pointer is passed as an argument
17644 ** this function is a no-op.
17645 */
17646 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17647   if( p ){
17648     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17649   }
17650 }
17651
17652 #ifndef NDEBUG
17653 /*
17654 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17655 ** intended for use inside assert() statements.
17656 */
17657 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17658   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17659 }
17660 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17661   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17662 }
17663 #endif
17664
17665 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17666
17667 /************** End of mutex.c ***********************************************/
17668 /************** Begin file mutex_noop.c **************************************/
17669 /*
17670 ** 2008 October 07
17671 **
17672 ** The author disclaims copyright to this source code.  In place of
17673 ** a legal notice, here is a blessing:
17674 **
17675 **    May you do good and not evil.
17676 **    May you find forgiveness for yourself and forgive others.
17677 **    May you share freely, never taking more than you give.
17678 **
17679 *************************************************************************
17680 ** This file contains the C functions that implement mutexes.
17681 **
17682 ** This implementation in this file does not provide any mutual
17683 ** exclusion and is thus suitable for use only in applications
17684 ** that use SQLite in a single thread.  The routines defined
17685 ** here are place-holders.  Applications can substitute working
17686 ** mutex routines at start-time using the
17687 **
17688 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17689 **
17690 ** interface.
17691 **
17692 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17693 ** that does error checking on mutexes to make sure they are being
17694 ** called correctly.
17695 */
17696
17697 #ifndef SQLITE_MUTEX_OMIT
17698
17699 #ifndef SQLITE_DEBUG
17700 /*
17701 ** Stub routines for all mutex methods.
17702 **
17703 ** This routines provide no mutual exclusion or error checking.
17704 */
17705 static int noopMutexInit(void){ return SQLITE_OK; }
17706 static int noopMutexEnd(void){ return SQLITE_OK; }
17707 static sqlite3_mutex *noopMutexAlloc(int id){ 
17708   UNUSED_PARAMETER(id);
17709   return (sqlite3_mutex*)8; 
17710 }
17711 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17712 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17713 static int noopMutexTry(sqlite3_mutex *p){
17714   UNUSED_PARAMETER(p);
17715   return SQLITE_OK;
17716 }
17717 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17718
17719 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17720   static const sqlite3_mutex_methods sMutex = {
17721     noopMutexInit,
17722     noopMutexEnd,
17723     noopMutexAlloc,
17724     noopMutexFree,
17725     noopMutexEnter,
17726     noopMutexTry,
17727     noopMutexLeave,
17728
17729     0,
17730     0,
17731   };
17732
17733   return &sMutex;
17734 }
17735 #endif /* !SQLITE_DEBUG */
17736
17737 #ifdef SQLITE_DEBUG
17738 /*
17739 ** In this implementation, error checking is provided for testing
17740 ** and debugging purposes.  The mutexes still do not provide any
17741 ** mutual exclusion.
17742 */
17743
17744 /*
17745 ** The mutex object
17746 */
17747 typedef struct sqlite3_debug_mutex {
17748   int id;     /* The mutex type */
17749   int cnt;    /* Number of entries without a matching leave */
17750 } sqlite3_debug_mutex;
17751
17752 /*
17753 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17754 ** intended for use inside assert() statements.
17755 */
17756 static int debugMutexHeld(sqlite3_mutex *pX){
17757   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17758   return p==0 || p->cnt>0;
17759 }
17760 static int debugMutexNotheld(sqlite3_mutex *pX){
17761   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17762   return p==0 || p->cnt==0;
17763 }
17764
17765 /*
17766 ** Initialize and deinitialize the mutex subsystem.
17767 */
17768 static int debugMutexInit(void){ return SQLITE_OK; }
17769 static int debugMutexEnd(void){ return SQLITE_OK; }
17770
17771 /*
17772 ** The sqlite3_mutex_alloc() routine allocates a new
17773 ** mutex and returns a pointer to it.  If it returns NULL
17774 ** that means that a mutex could not be allocated. 
17775 */
17776 static sqlite3_mutex *debugMutexAlloc(int id){
17777   static sqlite3_debug_mutex aStatic[6];
17778   sqlite3_debug_mutex *pNew = 0;
17779   switch( id ){
17780     case SQLITE_MUTEX_FAST:
17781     case SQLITE_MUTEX_RECURSIVE: {
17782       pNew = sqlite3Malloc(sizeof(*pNew));
17783       if( pNew ){
17784         pNew->id = id;
17785         pNew->cnt = 0;
17786       }
17787       break;
17788     }
17789     default: {
17790       assert( id-2 >= 0 );
17791       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17792       pNew = &aStatic[id-2];
17793       pNew->id = id;
17794       break;
17795     }
17796   }
17797   return (sqlite3_mutex*)pNew;
17798 }
17799
17800 /*
17801 ** This routine deallocates a previously allocated mutex.
17802 */
17803 static void debugMutexFree(sqlite3_mutex *pX){
17804   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17805   assert( p->cnt==0 );
17806   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17807   sqlite3_free(p);
17808 }
17809
17810 /*
17811 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17812 ** to enter a mutex.  If another thread is already within the mutex,
17813 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17814 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17815 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17816 ** be entered multiple times by the same thread.  In such cases the,
17817 ** mutex must be exited an equal number of times before another thread
17818 ** can enter.  If the same thread tries to enter any other kind of mutex
17819 ** more than once, the behavior is undefined.
17820 */
17821 static void debugMutexEnter(sqlite3_mutex *pX){
17822   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17823   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17824   p->cnt++;
17825 }
17826 static int debugMutexTry(sqlite3_mutex *pX){
17827   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17828   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17829   p->cnt++;
17830   return SQLITE_OK;
17831 }
17832
17833 /*
17834 ** The sqlite3_mutex_leave() routine exits a mutex that was
17835 ** previously entered by the same thread.  The behavior
17836 ** is undefined if the mutex is not currently entered or
17837 ** is not currently allocated.  SQLite will never do either.
17838 */
17839 static void debugMutexLeave(sqlite3_mutex *pX){
17840   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17841   assert( debugMutexHeld(pX) );
17842   p->cnt--;
17843   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17844 }
17845
17846 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17847   static const sqlite3_mutex_methods sMutex = {
17848     debugMutexInit,
17849     debugMutexEnd,
17850     debugMutexAlloc,
17851     debugMutexFree,
17852     debugMutexEnter,
17853     debugMutexTry,
17854     debugMutexLeave,
17855
17856     debugMutexHeld,
17857     debugMutexNotheld
17858   };
17859
17860   return &sMutex;
17861 }
17862 #endif /* SQLITE_DEBUG */
17863
17864 /*
17865 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17866 ** is used regardless of the run-time threadsafety setting.
17867 */
17868 #ifdef SQLITE_MUTEX_NOOP
17869 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17870   return sqlite3NoopMutex();
17871 }
17872 #endif /* defined(SQLITE_MUTEX_NOOP) */
17873 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17874
17875 /************** End of mutex_noop.c ******************************************/
17876 /************** Begin file mutex_unix.c **************************************/
17877 /*
17878 ** 2007 August 28
17879 **
17880 ** The author disclaims copyright to this source code.  In place of
17881 ** a legal notice, here is a blessing:
17882 **
17883 **    May you do good and not evil.
17884 **    May you find forgiveness for yourself and forgive others.
17885 **    May you share freely, never taking more than you give.
17886 **
17887 *************************************************************************
17888 ** This file contains the C functions that implement mutexes for pthreads
17889 */
17890
17891 /*
17892 ** The code in this file is only used if we are compiling threadsafe
17893 ** under unix with pthreads.
17894 **
17895 ** Note that this implementation requires a version of pthreads that
17896 ** supports recursive mutexes.
17897 */
17898 #ifdef SQLITE_MUTEX_PTHREADS
17899
17900 #include <pthread.h>
17901
17902 /*
17903 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17904 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17905 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17906 */
17907 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17908 # define SQLITE_MUTEX_NREF 1
17909 #else
17910 # define SQLITE_MUTEX_NREF 0
17911 #endif
17912
17913 /*
17914 ** Each recursive mutex is an instance of the following structure.
17915 */
17916 struct sqlite3_mutex {
17917   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17918 #if SQLITE_MUTEX_NREF
17919   int id;                    /* Mutex type */
17920   volatile int nRef;         /* Number of entrances */
17921   volatile pthread_t owner;  /* Thread that is within this mutex */
17922   int trace;                 /* True to trace changes */
17923 #endif
17924 };
17925 #if SQLITE_MUTEX_NREF
17926 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17927 #else
17928 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17929 #endif
17930
17931 /*
17932 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17933 ** intended for use only inside assert() statements.  On some platforms,
17934 ** there might be race conditions that can cause these routines to
17935 ** deliver incorrect results.  In particular, if pthread_equal() is
17936 ** not an atomic operation, then these routines might delivery
17937 ** incorrect results.  On most platforms, pthread_equal() is a 
17938 ** comparison of two integers and is therefore atomic.  But we are
17939 ** told that HPUX is not such a platform.  If so, then these routines
17940 ** will not always work correctly on HPUX.
17941 **
17942 ** On those platforms where pthread_equal() is not atomic, SQLite
17943 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17944 ** make sure no assert() statements are evaluated and hence these
17945 ** routines are never called.
17946 */
17947 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17948 static int pthreadMutexHeld(sqlite3_mutex *p){
17949   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17950 }
17951 static int pthreadMutexNotheld(sqlite3_mutex *p){
17952   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17953 }
17954 #endif
17955
17956 /*
17957 ** Initialize and deinitialize the mutex subsystem.
17958 */
17959 static int pthreadMutexInit(void){ return SQLITE_OK; }
17960 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17961
17962 /*
17963 ** The sqlite3_mutex_alloc() routine allocates a new
17964 ** mutex and returns a pointer to it.  If it returns NULL
17965 ** that means that a mutex could not be allocated.  SQLite
17966 ** will unwind its stack and return an error.  The argument
17967 ** to sqlite3_mutex_alloc() is one of these integer constants:
17968 **
17969 ** <ul>
17970 ** <li>  SQLITE_MUTEX_FAST
17971 ** <li>  SQLITE_MUTEX_RECURSIVE
17972 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17973 ** <li>  SQLITE_MUTEX_STATIC_MEM
17974 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17975 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17976 ** <li>  SQLITE_MUTEX_STATIC_LRU
17977 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17978 ** </ul>
17979 **
17980 ** The first two constants cause sqlite3_mutex_alloc() to create
17981 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17982 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17983 ** The mutex implementation does not need to make a distinction
17984 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17985 ** not want to.  But SQLite will only request a recursive mutex in
17986 ** cases where it really needs one.  If a faster non-recursive mutex
17987 ** implementation is available on the host platform, the mutex subsystem
17988 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17989 **
17990 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17991 ** a pointer to a static preexisting mutex.  Six static mutexes are
17992 ** used by the current version of SQLite.  Future versions of SQLite
17993 ** may add additional static mutexes.  Static mutexes are for internal
17994 ** use by SQLite only.  Applications that use SQLite mutexes should
17995 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17996 ** SQLITE_MUTEX_RECURSIVE.
17997 **
17998 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17999 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18000 ** returns a different mutex on every call.  But for the static 
18001 ** mutex types, the same mutex is returned on every call that has
18002 ** the same type number.
18003 */
18004 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18005   static sqlite3_mutex staticMutexes[] = {
18006     SQLITE3_MUTEX_INITIALIZER,
18007     SQLITE3_MUTEX_INITIALIZER,
18008     SQLITE3_MUTEX_INITIALIZER,
18009     SQLITE3_MUTEX_INITIALIZER,
18010     SQLITE3_MUTEX_INITIALIZER,
18011     SQLITE3_MUTEX_INITIALIZER
18012   };
18013   sqlite3_mutex *p;
18014   switch( iType ){
18015     case SQLITE_MUTEX_RECURSIVE: {
18016       p = sqlite3MallocZero( sizeof(*p) );
18017       if( p ){
18018 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18019         /* If recursive mutexes are not available, we will have to
18020         ** build our own.  See below. */
18021         pthread_mutex_init(&p->mutex, 0);
18022 #else
18023         /* Use a recursive mutex if it is available */
18024         pthread_mutexattr_t recursiveAttr;
18025         pthread_mutexattr_init(&recursiveAttr);
18026         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18027         pthread_mutex_init(&p->mutex, &recursiveAttr);
18028         pthread_mutexattr_destroy(&recursiveAttr);
18029 #endif
18030 #if SQLITE_MUTEX_NREF
18031         p->id = iType;
18032 #endif
18033       }
18034       break;
18035     }
18036     case SQLITE_MUTEX_FAST: {
18037       p = sqlite3MallocZero( sizeof(*p) );
18038       if( p ){
18039 #if SQLITE_MUTEX_NREF
18040         p->id = iType;
18041 #endif
18042         pthread_mutex_init(&p->mutex, 0);
18043       }
18044       break;
18045     }
18046     default: {
18047       assert( iType-2 >= 0 );
18048       assert( iType-2 < ArraySize(staticMutexes) );
18049       p = &staticMutexes[iType-2];
18050 #if SQLITE_MUTEX_NREF
18051       p->id = iType;
18052 #endif
18053       break;
18054     }
18055   }
18056   return p;
18057 }
18058
18059
18060 /*
18061 ** This routine deallocates a previously
18062 ** allocated mutex.  SQLite is careful to deallocate every
18063 ** mutex that it allocates.
18064 */
18065 static void pthreadMutexFree(sqlite3_mutex *p){
18066   assert( p->nRef==0 );
18067   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18068   pthread_mutex_destroy(&p->mutex);
18069   sqlite3_free(p);
18070 }
18071
18072 /*
18073 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18074 ** to enter a mutex.  If another thread is already within the mutex,
18075 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18076 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18077 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18078 ** be entered multiple times by the same thread.  In such cases the,
18079 ** mutex must be exited an equal number of times before another thread
18080 ** can enter.  If the same thread tries to enter any other kind of mutex
18081 ** more than once, the behavior is undefined.
18082 */
18083 static void pthreadMutexEnter(sqlite3_mutex *p){
18084   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18085
18086 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18087   /* If recursive mutexes are not available, then we have to grow
18088   ** our own.  This implementation assumes that pthread_equal()
18089   ** is atomic - that it cannot be deceived into thinking self
18090   ** and p->owner are equal if p->owner changes between two values
18091   ** that are not equal to self while the comparison is taking place.
18092   ** This implementation also assumes a coherent cache - that 
18093   ** separate processes cannot read different values from the same
18094   ** address at the same time.  If either of these two conditions
18095   ** are not met, then the mutexes will fail and problems will result.
18096   */
18097   {
18098     pthread_t self = pthread_self();
18099     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18100       p->nRef++;
18101     }else{
18102       pthread_mutex_lock(&p->mutex);
18103       assert( p->nRef==0 );
18104       p->owner = self;
18105       p->nRef = 1;
18106     }
18107   }
18108 #else
18109   /* Use the built-in recursive mutexes if they are available.
18110   */
18111   pthread_mutex_lock(&p->mutex);
18112 #if SQLITE_MUTEX_NREF
18113   assert( p->nRef>0 || p->owner==0 );
18114   p->owner = pthread_self();
18115   p->nRef++;
18116 #endif
18117 #endif
18118
18119 #ifdef SQLITE_DEBUG
18120   if( p->trace ){
18121     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18122   }
18123 #endif
18124 }
18125 static int pthreadMutexTry(sqlite3_mutex *p){
18126   int rc;
18127   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18128
18129 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18130   /* If recursive mutexes are not available, then we have to grow
18131   ** our own.  This implementation assumes that pthread_equal()
18132   ** is atomic - that it cannot be deceived into thinking self
18133   ** and p->owner are equal if p->owner changes between two values
18134   ** that are not equal to self while the comparison is taking place.
18135   ** This implementation also assumes a coherent cache - that 
18136   ** separate processes cannot read different values from the same
18137   ** address at the same time.  If either of these two conditions
18138   ** are not met, then the mutexes will fail and problems will result.
18139   */
18140   {
18141     pthread_t self = pthread_self();
18142     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18143       p->nRef++;
18144       rc = SQLITE_OK;
18145     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18146       assert( p->nRef==0 );
18147       p->owner = self;
18148       p->nRef = 1;
18149       rc = SQLITE_OK;
18150     }else{
18151       rc = SQLITE_BUSY;
18152     }
18153   }
18154 #else
18155   /* Use the built-in recursive mutexes if they are available.
18156   */
18157   if( pthread_mutex_trylock(&p->mutex)==0 ){
18158 #if SQLITE_MUTEX_NREF
18159     p->owner = pthread_self();
18160     p->nRef++;
18161 #endif
18162     rc = SQLITE_OK;
18163   }else{
18164     rc = SQLITE_BUSY;
18165   }
18166 #endif
18167
18168 #ifdef SQLITE_DEBUG
18169   if( rc==SQLITE_OK && p->trace ){
18170     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18171   }
18172 #endif
18173   return rc;
18174 }
18175
18176 /*
18177 ** The sqlite3_mutex_leave() routine exits a mutex that was
18178 ** previously entered by the same thread.  The behavior
18179 ** is undefined if the mutex is not currently entered or
18180 ** is not currently allocated.  SQLite will never do either.
18181 */
18182 static void pthreadMutexLeave(sqlite3_mutex *p){
18183   assert( pthreadMutexHeld(p) );
18184 #if SQLITE_MUTEX_NREF
18185   p->nRef--;
18186   if( p->nRef==0 ) p->owner = 0;
18187 #endif
18188   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18189
18190 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18191   if( p->nRef==0 ){
18192     pthread_mutex_unlock(&p->mutex);
18193   }
18194 #else
18195   pthread_mutex_unlock(&p->mutex);
18196 #endif
18197
18198 #ifdef SQLITE_DEBUG
18199   if( p->trace ){
18200     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18201   }
18202 #endif
18203 }
18204
18205 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18206   static const sqlite3_mutex_methods sMutex = {
18207     pthreadMutexInit,
18208     pthreadMutexEnd,
18209     pthreadMutexAlloc,
18210     pthreadMutexFree,
18211     pthreadMutexEnter,
18212     pthreadMutexTry,
18213     pthreadMutexLeave,
18214 #ifdef SQLITE_DEBUG
18215     pthreadMutexHeld,
18216     pthreadMutexNotheld
18217 #else
18218     0,
18219     0
18220 #endif
18221   };
18222
18223   return &sMutex;
18224 }
18225
18226 #endif /* SQLITE_MUTEX_PTHREADS */
18227
18228 /************** End of mutex_unix.c ******************************************/
18229 /************** Begin file mutex_w32.c ***************************************/
18230 /*
18231 ** 2007 August 14
18232 **
18233 ** The author disclaims copyright to this source code.  In place of
18234 ** a legal notice, here is a blessing:
18235 **
18236 **    May you do good and not evil.
18237 **    May you find forgiveness for yourself and forgive others.
18238 **    May you share freely, never taking more than you give.
18239 **
18240 *************************************************************************
18241 ** This file contains the C functions that implement mutexes for win32
18242 */
18243
18244 /*
18245 ** The code in this file is only used if we are compiling multithreaded
18246 ** on a win32 system.
18247 */
18248 #ifdef SQLITE_MUTEX_W32
18249
18250 /*
18251 ** Each recursive mutex is an instance of the following structure.
18252 */
18253 struct sqlite3_mutex {
18254   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18255   int id;                    /* Mutex type */
18256 #ifdef SQLITE_DEBUG
18257   volatile int nRef;         /* Number of enterances */
18258   volatile DWORD owner;      /* Thread holding this mutex */
18259   int trace;                 /* True to trace changes */
18260 #endif
18261 };
18262 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18263 #ifdef SQLITE_DEBUG
18264 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18265 #else
18266 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18267 #endif
18268
18269 /*
18270 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18271 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18272 **
18273 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18274 ** the LockFileEx() API.  But we can still statically link against that
18275 ** API as long as we don't call it win running Win95/98/ME.  A call to
18276 ** this routine is used to determine if the host is Win95/98/ME or
18277 ** WinNT/2K/XP so that we will know whether or not we can safely call
18278 ** the LockFileEx() API.
18279 **
18280 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18281 ** which is only available if your application was compiled with 
18282 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18283 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18284 ** this out as well.
18285 */
18286 #if 0
18287 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18288 # define mutexIsNT()  (1)
18289 #else
18290   static int mutexIsNT(void){
18291     static int osType = 0;
18292     if( osType==0 ){
18293       OSVERSIONINFO sInfo;
18294       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18295       GetVersionEx(&sInfo);
18296       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18297     }
18298     return osType==2;
18299   }
18300 #endif /* SQLITE_OS_WINCE */
18301 #endif
18302
18303 #ifdef SQLITE_DEBUG
18304 /*
18305 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18306 ** intended for use only inside assert() statements.
18307 */
18308 static int winMutexHeld(sqlite3_mutex *p){
18309   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18310 }
18311 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18312   return p->nRef==0 || p->owner!=tid;
18313 }
18314 static int winMutexNotheld(sqlite3_mutex *p){
18315   DWORD tid = GetCurrentThreadId(); 
18316   return winMutexNotheld2(p, tid);
18317 }
18318 #endif
18319
18320
18321 /*
18322 ** Initialize and deinitialize the mutex subsystem.
18323 */
18324 static sqlite3_mutex winMutex_staticMutexes[6] = {
18325   SQLITE3_MUTEX_INITIALIZER,
18326   SQLITE3_MUTEX_INITIALIZER,
18327   SQLITE3_MUTEX_INITIALIZER,
18328   SQLITE3_MUTEX_INITIALIZER,
18329   SQLITE3_MUTEX_INITIALIZER,
18330   SQLITE3_MUTEX_INITIALIZER
18331 };
18332 static int winMutex_isInit = 0;
18333 /* As winMutexInit() and winMutexEnd() are called as part
18334 ** of the sqlite3_initialize and sqlite3_shutdown()
18335 ** processing, the "interlocked" magic is probably not
18336 ** strictly necessary.
18337 */
18338 static long winMutex_lock = 0;
18339
18340 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18341
18342 static int winMutexInit(void){ 
18343   /* The first to increment to 1 does actual initialization */
18344   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18345     int i;
18346     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18347 #if SQLITE_OS_WINRT
18348       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18349 #else
18350       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18351 #endif
18352     }
18353     winMutex_isInit = 1;
18354   }else{
18355     /* Someone else is in the process of initing the static mutexes */
18356     while( !winMutex_isInit ){
18357       sqlite3_win32_sleep(1);
18358     }
18359   }
18360   return SQLITE_OK; 
18361 }
18362
18363 static int winMutexEnd(void){ 
18364   /* The first to decrement to 0 does actual shutdown 
18365   ** (which should be the last to shutdown.) */
18366   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18367     if( winMutex_isInit==1 ){
18368       int i;
18369       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18370         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18371       }
18372       winMutex_isInit = 0;
18373     }
18374   }
18375   return SQLITE_OK; 
18376 }
18377
18378 /*
18379 ** The sqlite3_mutex_alloc() routine allocates a new
18380 ** mutex and returns a pointer to it.  If it returns NULL
18381 ** that means that a mutex could not be allocated.  SQLite
18382 ** will unwind its stack and return an error.  The argument
18383 ** to sqlite3_mutex_alloc() is one of these integer constants:
18384 **
18385 ** <ul>
18386 ** <li>  SQLITE_MUTEX_FAST
18387 ** <li>  SQLITE_MUTEX_RECURSIVE
18388 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18389 ** <li>  SQLITE_MUTEX_STATIC_MEM
18390 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18391 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18392 ** <li>  SQLITE_MUTEX_STATIC_LRU
18393 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18394 ** </ul>
18395 **
18396 ** The first two constants cause sqlite3_mutex_alloc() to create
18397 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18398 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18399 ** The mutex implementation does not need to make a distinction
18400 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18401 ** not want to.  But SQLite will only request a recursive mutex in
18402 ** cases where it really needs one.  If a faster non-recursive mutex
18403 ** implementation is available on the host platform, the mutex subsystem
18404 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18405 **
18406 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18407 ** a pointer to a static preexisting mutex.  Six static mutexes are
18408 ** used by the current version of SQLite.  Future versions of SQLite
18409 ** may add additional static mutexes.  Static mutexes are for internal
18410 ** use by SQLite only.  Applications that use SQLite mutexes should
18411 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18412 ** SQLITE_MUTEX_RECURSIVE.
18413 **
18414 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18415 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18416 ** returns a different mutex on every call.  But for the static 
18417 ** mutex types, the same mutex is returned on every call that has
18418 ** the same type number.
18419 */
18420 static sqlite3_mutex *winMutexAlloc(int iType){
18421   sqlite3_mutex *p;
18422
18423   switch( iType ){
18424     case SQLITE_MUTEX_FAST:
18425     case SQLITE_MUTEX_RECURSIVE: {
18426       p = sqlite3MallocZero( sizeof(*p) );
18427       if( p ){  
18428 #ifdef SQLITE_DEBUG
18429         p->id = iType;
18430 #endif
18431 #if SQLITE_OS_WINRT
18432         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18433 #else
18434         InitializeCriticalSection(&p->mutex);
18435 #endif
18436       }
18437       break;
18438     }
18439     default: {
18440       assert( winMutex_isInit==1 );
18441       assert( iType-2 >= 0 );
18442       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18443       p = &winMutex_staticMutexes[iType-2];
18444 #ifdef SQLITE_DEBUG
18445       p->id = iType;
18446 #endif
18447       break;
18448     }
18449   }
18450   return p;
18451 }
18452
18453
18454 /*
18455 ** This routine deallocates a previously
18456 ** allocated mutex.  SQLite is careful to deallocate every
18457 ** mutex that it allocates.
18458 */
18459 static void winMutexFree(sqlite3_mutex *p){
18460   assert( p );
18461   assert( p->nRef==0 && p->owner==0 );
18462   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18463   DeleteCriticalSection(&p->mutex);
18464   sqlite3_free(p);
18465 }
18466
18467 /*
18468 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18469 ** to enter a mutex.  If another thread is already within the mutex,
18470 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18471 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18472 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18473 ** be entered multiple times by the same thread.  In such cases the,
18474 ** mutex must be exited an equal number of times before another thread
18475 ** can enter.  If the same thread tries to enter any other kind of mutex
18476 ** more than once, the behavior is undefined.
18477 */
18478 static void winMutexEnter(sqlite3_mutex *p){
18479 #ifdef SQLITE_DEBUG
18480   DWORD tid = GetCurrentThreadId(); 
18481   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18482 #endif
18483   EnterCriticalSection(&p->mutex);
18484 #ifdef SQLITE_DEBUG
18485   assert( p->nRef>0 || p->owner==0 );
18486   p->owner = tid; 
18487   p->nRef++;
18488   if( p->trace ){
18489     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18490   }
18491 #endif
18492 }
18493 static int winMutexTry(sqlite3_mutex *p){
18494 #ifndef NDEBUG
18495   DWORD tid = GetCurrentThreadId(); 
18496 #endif
18497   int rc = SQLITE_BUSY;
18498   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18499   /*
18500   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18501   ** is used it is merely an optimization.  So it is OK for it to always
18502   ** fail.  
18503   **
18504   ** The TryEnterCriticalSection() interface is only available on WinNT.
18505   ** And some windows compilers complain if you try to use it without
18506   ** first doing some #defines that prevent SQLite from building on Win98.
18507   ** For that reason, we will omit this optimization for now.  See
18508   ** ticket #2685.
18509   */
18510 #if 0
18511   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18512     p->owner = tid;
18513     p->nRef++;
18514     rc = SQLITE_OK;
18515   }
18516 #else
18517   UNUSED_PARAMETER(p);
18518 #endif
18519 #ifdef SQLITE_DEBUG
18520   if( rc==SQLITE_OK && p->trace ){
18521     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18522   }
18523 #endif
18524   return rc;
18525 }
18526
18527 /*
18528 ** The sqlite3_mutex_leave() routine exits a mutex that was
18529 ** previously entered by the same thread.  The behavior
18530 ** is undefined if the mutex is not currently entered or
18531 ** is not currently allocated.  SQLite will never do either.
18532 */
18533 static void winMutexLeave(sqlite3_mutex *p){
18534 #ifndef NDEBUG
18535   DWORD tid = GetCurrentThreadId();
18536   assert( p->nRef>0 );
18537   assert( p->owner==tid );
18538   p->nRef--;
18539   if( p->nRef==0 ) p->owner = 0;
18540   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18541 #endif
18542   LeaveCriticalSection(&p->mutex);
18543 #ifdef SQLITE_DEBUG
18544   if( p->trace ){
18545     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18546   }
18547 #endif
18548 }
18549
18550 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18551   static const sqlite3_mutex_methods sMutex = {
18552     winMutexInit,
18553     winMutexEnd,
18554     winMutexAlloc,
18555     winMutexFree,
18556     winMutexEnter,
18557     winMutexTry,
18558     winMutexLeave,
18559 #ifdef SQLITE_DEBUG
18560     winMutexHeld,
18561     winMutexNotheld
18562 #else
18563     0,
18564     0
18565 #endif
18566   };
18567
18568   return &sMutex;
18569 }
18570 #endif /* SQLITE_MUTEX_W32 */
18571
18572 /************** End of mutex_w32.c *******************************************/
18573 /************** Begin file malloc.c ******************************************/
18574 /*
18575 ** 2001 September 15
18576 **
18577 ** The author disclaims copyright to this source code.  In place of
18578 ** a legal notice, here is a blessing:
18579 **
18580 **    May you do good and not evil.
18581 **    May you find forgiveness for yourself and forgive others.
18582 **    May you share freely, never taking more than you give.
18583 **
18584 *************************************************************************
18585 **
18586 ** Memory allocation functions used throughout sqlite.
18587 */
18588 /* #include <stdarg.h> */
18589
18590 /*
18591 ** Attempt to release up to n bytes of non-essential memory currently
18592 ** held by SQLite. An example of non-essential memory is memory used to
18593 ** cache database pages that are not currently in use.
18594 */
18595 SQLITE_API int sqlite3_release_memory(int n){
18596 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18597   return sqlite3PcacheReleaseMemory(n);
18598 #else
18599   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18600   ** is a no-op returning zero if SQLite is not compiled with
18601   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18602   UNUSED_PARAMETER(n);
18603   return 0;
18604 #endif
18605 }
18606
18607 /*
18608 ** An instance of the following object records the location of
18609 ** each unused scratch buffer.
18610 */
18611 typedef struct ScratchFreeslot {
18612   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18613 } ScratchFreeslot;
18614
18615 /*
18616 ** State information local to the memory allocation subsystem.
18617 */
18618 static SQLITE_WSD struct Mem0Global {
18619   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18620
18621   /*
18622   ** The alarm callback and its arguments.  The mem0.mutex lock will
18623   ** be held while the callback is running.  Recursive calls into
18624   ** the memory subsystem are allowed, but no new callbacks will be
18625   ** issued.
18626   */
18627   sqlite3_int64 alarmThreshold;
18628   void (*alarmCallback)(void*, sqlite3_int64,int);
18629   void *alarmArg;
18630
18631   /*
18632   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18633   ** (so that a range test can be used to determine if an allocation
18634   ** being freed came from pScratch) and a pointer to the list of
18635   ** unused scratch allocations.
18636   */
18637   void *pScratchEnd;
18638   ScratchFreeslot *pScratchFree;
18639   u32 nScratchFree;
18640
18641   /*
18642   ** True if heap is nearly "full" where "full" is defined by the
18643   ** sqlite3_soft_heap_limit() setting.
18644   */
18645   int nearlyFull;
18646 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18647
18648 #define mem0 GLOBAL(struct Mem0Global, mem0)
18649
18650 /*
18651 ** This routine runs when the memory allocator sees that the
18652 ** total memory allocation is about to exceed the soft heap
18653 ** limit.
18654 */
18655 static void softHeapLimitEnforcer(
18656   void *NotUsed, 
18657   sqlite3_int64 NotUsed2,
18658   int allocSize
18659 ){
18660   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18661   sqlite3_release_memory(allocSize);
18662 }
18663
18664 /*
18665 ** Change the alarm callback
18666 */
18667 static int sqlite3MemoryAlarm(
18668   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18669   void *pArg,
18670   sqlite3_int64 iThreshold
18671 ){
18672   int nUsed;
18673   sqlite3_mutex_enter(mem0.mutex);
18674   mem0.alarmCallback = xCallback;
18675   mem0.alarmArg = pArg;
18676   mem0.alarmThreshold = iThreshold;
18677   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18678   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18679   sqlite3_mutex_leave(mem0.mutex);
18680   return SQLITE_OK;
18681 }
18682
18683 #ifndef SQLITE_OMIT_DEPRECATED
18684 /*
18685 ** Deprecated external interface.  Internal/core SQLite code
18686 ** should call sqlite3MemoryAlarm.
18687 */
18688 SQLITE_API int sqlite3_memory_alarm(
18689   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18690   void *pArg,
18691   sqlite3_int64 iThreshold
18692 ){
18693   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18694 }
18695 #endif
18696
18697 /*
18698 ** Set the soft heap-size limit for the library. Passing a zero or 
18699 ** negative value indicates no limit.
18700 */
18701 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18702   sqlite3_int64 priorLimit;
18703   sqlite3_int64 excess;
18704 #ifndef SQLITE_OMIT_AUTOINIT
18705   int rc = sqlite3_initialize();
18706   if( rc ) return -1;
18707 #endif
18708   sqlite3_mutex_enter(mem0.mutex);
18709   priorLimit = mem0.alarmThreshold;
18710   sqlite3_mutex_leave(mem0.mutex);
18711   if( n<0 ) return priorLimit;
18712   if( n>0 ){
18713     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18714   }else{
18715     sqlite3MemoryAlarm(0, 0, 0);
18716   }
18717   excess = sqlite3_memory_used() - n;
18718   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18719   return priorLimit;
18720 }
18721 SQLITE_API void sqlite3_soft_heap_limit(int n){
18722   if( n<0 ) n = 0;
18723   sqlite3_soft_heap_limit64(n);
18724 }
18725
18726 /*
18727 ** Initialize the memory allocation subsystem.
18728 */
18729 SQLITE_PRIVATE int sqlite3MallocInit(void){
18730   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18731     sqlite3MemSetDefault();
18732   }
18733   memset(&mem0, 0, sizeof(mem0));
18734   if( sqlite3GlobalConfig.bCoreMutex ){
18735     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18736   }
18737   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18738       && sqlite3GlobalConfig.nScratch>0 ){
18739     int i, n, sz;
18740     ScratchFreeslot *pSlot;
18741     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18742     sqlite3GlobalConfig.szScratch = sz;
18743     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18744     n = sqlite3GlobalConfig.nScratch;
18745     mem0.pScratchFree = pSlot;
18746     mem0.nScratchFree = n;
18747     for(i=0; i<n-1; i++){
18748       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18749       pSlot = pSlot->pNext;
18750     }
18751     pSlot->pNext = 0;
18752     mem0.pScratchEnd = (void*)&pSlot[1];
18753   }else{
18754     mem0.pScratchEnd = 0;
18755     sqlite3GlobalConfig.pScratch = 0;
18756     sqlite3GlobalConfig.szScratch = 0;
18757     sqlite3GlobalConfig.nScratch = 0;
18758   }
18759   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18760       || sqlite3GlobalConfig.nPage<1 ){
18761     sqlite3GlobalConfig.pPage = 0;
18762     sqlite3GlobalConfig.szPage = 0;
18763     sqlite3GlobalConfig.nPage = 0;
18764   }
18765   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18766 }
18767
18768 /*
18769 ** Return true if the heap is currently under memory pressure - in other
18770 ** words if the amount of heap used is close to the limit set by
18771 ** sqlite3_soft_heap_limit().
18772 */
18773 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18774   return mem0.nearlyFull;
18775 }
18776
18777 /*
18778 ** Deinitialize the memory allocation subsystem.
18779 */
18780 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18781   if( sqlite3GlobalConfig.m.xShutdown ){
18782     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18783   }
18784   memset(&mem0, 0, sizeof(mem0));
18785 }
18786
18787 /*
18788 ** Return the amount of memory currently checked out.
18789 */
18790 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18791   int n, mx;
18792   sqlite3_int64 res;
18793   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18794   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18795   return res;
18796 }
18797
18798 /*
18799 ** Return the maximum amount of memory that has ever been
18800 ** checked out since either the beginning of this process
18801 ** or since the most recent reset.
18802 */
18803 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18804   int n, mx;
18805   sqlite3_int64 res;
18806   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18807   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18808   return res;
18809 }
18810
18811 /*
18812 ** Trigger the alarm 
18813 */
18814 static void sqlite3MallocAlarm(int nByte){
18815   void (*xCallback)(void*,sqlite3_int64,int);
18816   sqlite3_int64 nowUsed;
18817   void *pArg;
18818   if( mem0.alarmCallback==0 ) return;
18819   xCallback = mem0.alarmCallback;
18820   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18821   pArg = mem0.alarmArg;
18822   mem0.alarmCallback = 0;
18823   sqlite3_mutex_leave(mem0.mutex);
18824   xCallback(pArg, nowUsed, nByte);
18825   sqlite3_mutex_enter(mem0.mutex);
18826   mem0.alarmCallback = xCallback;
18827   mem0.alarmArg = pArg;
18828 }
18829
18830 /*
18831 ** Do a memory allocation with statistics and alarms.  Assume the
18832 ** lock is already held.
18833 */
18834 static int mallocWithAlarm(int n, void **pp){
18835   int nFull;
18836   void *p;
18837   assert( sqlite3_mutex_held(mem0.mutex) );
18838   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18839   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18840   if( mem0.alarmCallback!=0 ){
18841     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18842     if( nUsed >= mem0.alarmThreshold - nFull ){
18843       mem0.nearlyFull = 1;
18844       sqlite3MallocAlarm(nFull);
18845     }else{
18846       mem0.nearlyFull = 0;
18847     }
18848   }
18849   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18850 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18851   if( p==0 && mem0.alarmCallback ){
18852     sqlite3MallocAlarm(nFull);
18853     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18854   }
18855 #endif
18856   if( p ){
18857     nFull = sqlite3MallocSize(p);
18858     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18859     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18860   }
18861   *pp = p;
18862   return nFull;
18863 }
18864
18865 /*
18866 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18867 ** assumes the memory subsystem has already been initialized.
18868 */
18869 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18870   void *p;
18871   if( n<=0               /* IMP: R-65312-04917 */ 
18872    || n>=0x7fffff00
18873   ){
18874     /* A memory allocation of a number of bytes which is near the maximum
18875     ** signed integer value might cause an integer overflow inside of the
18876     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18877     ** 255 bytes of overhead.  SQLite itself will never use anything near
18878     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18879     p = 0;
18880   }else if( sqlite3GlobalConfig.bMemstat ){
18881     sqlite3_mutex_enter(mem0.mutex);
18882     mallocWithAlarm(n, &p);
18883     sqlite3_mutex_leave(mem0.mutex);
18884   }else{
18885     p = sqlite3GlobalConfig.m.xMalloc(n);
18886   }
18887   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18888   return p;
18889 }
18890
18891 /*
18892 ** This version of the memory allocation is for use by the application.
18893 ** First make sure the memory subsystem is initialized, then do the
18894 ** allocation.
18895 */
18896 SQLITE_API void *sqlite3_malloc(int n){
18897 #ifndef SQLITE_OMIT_AUTOINIT
18898   if( sqlite3_initialize() ) return 0;
18899 #endif
18900   return sqlite3Malloc(n);
18901 }
18902
18903 /*
18904 ** Each thread may only have a single outstanding allocation from
18905 ** xScratchMalloc().  We verify this constraint in the single-threaded
18906 ** case by setting scratchAllocOut to 1 when an allocation
18907 ** is outstanding clearing it when the allocation is freed.
18908 */
18909 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18910 static int scratchAllocOut = 0;
18911 #endif
18912
18913
18914 /*
18915 ** Allocate memory that is to be used and released right away.
18916 ** This routine is similar to alloca() in that it is not intended
18917 ** for situations where the memory might be held long-term.  This
18918 ** routine is intended to get memory to old large transient data
18919 ** structures that would not normally fit on the stack of an
18920 ** embedded processor.
18921 */
18922 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18923   void *p;
18924   assert( n>0 );
18925
18926   sqlite3_mutex_enter(mem0.mutex);
18927   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18928     p = mem0.pScratchFree;
18929     mem0.pScratchFree = mem0.pScratchFree->pNext;
18930     mem0.nScratchFree--;
18931     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18932     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18933     sqlite3_mutex_leave(mem0.mutex);
18934   }else{
18935     if( sqlite3GlobalConfig.bMemstat ){
18936       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18937       n = mallocWithAlarm(n, &p);
18938       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18939       sqlite3_mutex_leave(mem0.mutex);
18940     }else{
18941       sqlite3_mutex_leave(mem0.mutex);
18942       p = sqlite3GlobalConfig.m.xMalloc(n);
18943     }
18944     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18945   }
18946   assert( sqlite3_mutex_notheld(mem0.mutex) );
18947
18948
18949 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18950   /* Verify that no more than two scratch allocations per thread
18951   ** are outstanding at one time.  (This is only checked in the
18952   ** single-threaded case since checking in the multi-threaded case
18953   ** would be much more complicated.) */
18954   assert( scratchAllocOut<=1 );
18955   if( p ) scratchAllocOut++;
18956 #endif
18957
18958   return p;
18959 }
18960 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18961   if( p ){
18962
18963 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18964     /* Verify that no more than two scratch allocation per thread
18965     ** is outstanding at one time.  (This is only checked in the
18966     ** single-threaded case since checking in the multi-threaded case
18967     ** would be much more complicated.) */
18968     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18969     scratchAllocOut--;
18970 #endif
18971
18972     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18973       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18974       ScratchFreeslot *pSlot;
18975       pSlot = (ScratchFreeslot*)p;
18976       sqlite3_mutex_enter(mem0.mutex);
18977       pSlot->pNext = mem0.pScratchFree;
18978       mem0.pScratchFree = pSlot;
18979       mem0.nScratchFree++;
18980       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18981       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18982       sqlite3_mutex_leave(mem0.mutex);
18983     }else{
18984       /* Release memory back to the heap */
18985       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18986       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18987       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18988       if( sqlite3GlobalConfig.bMemstat ){
18989         int iSize = sqlite3MallocSize(p);
18990         sqlite3_mutex_enter(mem0.mutex);
18991         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18992         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18993         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18994         sqlite3GlobalConfig.m.xFree(p);
18995         sqlite3_mutex_leave(mem0.mutex);
18996       }else{
18997         sqlite3GlobalConfig.m.xFree(p);
18998       }
18999     }
19000   }
19001 }
19002
19003 /*
19004 ** TRUE if p is a lookaside memory allocation from db
19005 */
19006 #ifndef SQLITE_OMIT_LOOKASIDE
19007 static int isLookaside(sqlite3 *db, void *p){
19008   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19009 }
19010 #else
19011 #define isLookaside(A,B) 0
19012 #endif
19013
19014 /*
19015 ** Return the size of a memory allocation previously obtained from
19016 ** sqlite3Malloc() or sqlite3_malloc().
19017 */
19018 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19019   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19020   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19021   return sqlite3GlobalConfig.m.xSize(p);
19022 }
19023 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19024   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19025   if( db && isLookaside(db, p) ){
19026     return db->lookaside.sz;
19027   }else{
19028     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19029     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19030     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19031     return sqlite3GlobalConfig.m.xSize(p);
19032   }
19033 }
19034
19035 /*
19036 ** Free memory previously obtained from sqlite3Malloc().
19037 */
19038 SQLITE_API void sqlite3_free(void *p){
19039   if( p==0 ) return;  /* IMP: R-49053-54554 */
19040   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19041   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19042   if( sqlite3GlobalConfig.bMemstat ){
19043     sqlite3_mutex_enter(mem0.mutex);
19044     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19045     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19046     sqlite3GlobalConfig.m.xFree(p);
19047     sqlite3_mutex_leave(mem0.mutex);
19048   }else{
19049     sqlite3GlobalConfig.m.xFree(p);
19050   }
19051 }
19052
19053 /*
19054 ** Free memory that might be associated with a particular database
19055 ** connection.
19056 */
19057 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19058   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19059   if( db ){
19060     if( db->pnBytesFreed ){
19061       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19062       return;
19063     }
19064     if( isLookaside(db, p) ){
19065       LookasideSlot *pBuf = (LookasideSlot*)p;
19066 #if SQLITE_DEBUG
19067       /* Trash all content in the buffer being freed */
19068       memset(p, 0xaa, db->lookaside.sz);
19069 #endif
19070       pBuf->pNext = db->lookaside.pFree;
19071       db->lookaside.pFree = pBuf;
19072       db->lookaside.nOut--;
19073       return;
19074     }
19075   }
19076   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19077   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19078   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19079   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19080   sqlite3_free(p);
19081 }
19082
19083 /*
19084 ** Change the size of an existing memory allocation
19085 */
19086 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19087   int nOld, nNew, nDiff;
19088   void *pNew;
19089   if( pOld==0 ){
19090     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19091   }
19092   if( nBytes<=0 ){
19093     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19094     return 0;
19095   }
19096   if( nBytes>=0x7fffff00 ){
19097     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19098     return 0;
19099   }
19100   nOld = sqlite3MallocSize(pOld);
19101   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19102   ** argument to xRealloc is always a value returned by a prior call to
19103   ** xRoundup. */
19104   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19105   if( nOld==nNew ){
19106     pNew = pOld;
19107   }else if( sqlite3GlobalConfig.bMemstat ){
19108     sqlite3_mutex_enter(mem0.mutex);
19109     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19110     nDiff = nNew - nOld;
19111     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
19112           mem0.alarmThreshold-nDiff ){
19113       sqlite3MallocAlarm(nDiff);
19114     }
19115     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19116     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19117     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19118     if( pNew==0 && mem0.alarmCallback ){
19119       sqlite3MallocAlarm(nBytes);
19120       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19121     }
19122     if( pNew ){
19123       nNew = sqlite3MallocSize(pNew);
19124       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19125     }
19126     sqlite3_mutex_leave(mem0.mutex);
19127   }else{
19128     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19129   }
19130   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19131   return pNew;
19132 }
19133
19134 /*
19135 ** The public interface to sqlite3Realloc.  Make sure that the memory
19136 ** subsystem is initialized prior to invoking sqliteRealloc.
19137 */
19138 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19139 #ifndef SQLITE_OMIT_AUTOINIT
19140   if( sqlite3_initialize() ) return 0;
19141 #endif
19142   return sqlite3Realloc(pOld, n);
19143 }
19144
19145
19146 /*
19147 ** Allocate and zero memory.
19148 */ 
19149 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19150   void *p = sqlite3Malloc(n);
19151   if( p ){
19152     memset(p, 0, n);
19153   }
19154   return p;
19155 }
19156
19157 /*
19158 ** Allocate and zero memory.  If the allocation fails, make
19159 ** the mallocFailed flag in the connection pointer.
19160 */
19161 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19162   void *p = sqlite3DbMallocRaw(db, n);
19163   if( p ){
19164     memset(p, 0, n);
19165   }
19166   return p;
19167 }
19168
19169 /*
19170 ** Allocate and zero memory.  If the allocation fails, make
19171 ** the mallocFailed flag in the connection pointer.
19172 **
19173 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19174 ** failure on the same database connection) then always return 0.
19175 ** Hence for a particular database connection, once malloc starts
19176 ** failing, it fails consistently until mallocFailed is reset.
19177 ** This is an important assumption.  There are many places in the
19178 ** code that do things like this:
19179 **
19180 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19181 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19182 **         if( b ) a[10] = 9;
19183 **
19184 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19185 ** that all prior mallocs (ex: "a") worked too.
19186 */
19187 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19188   void *p;
19189   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19190   assert( db==0 || db->pnBytesFreed==0 );
19191 #ifndef SQLITE_OMIT_LOOKASIDE
19192   if( db ){
19193     LookasideSlot *pBuf;
19194     if( db->mallocFailed ){
19195       return 0;
19196     }
19197     if( db->lookaside.bEnabled ){
19198       if( n>db->lookaside.sz ){
19199         db->lookaside.anStat[1]++;
19200       }else if( (pBuf = db->lookaside.pFree)==0 ){
19201         db->lookaside.anStat[2]++;
19202       }else{
19203         db->lookaside.pFree = pBuf->pNext;
19204         db->lookaside.nOut++;
19205         db->lookaside.anStat[0]++;
19206         if( db->lookaside.nOut>db->lookaside.mxOut ){
19207           db->lookaside.mxOut = db->lookaside.nOut;
19208         }
19209         return (void*)pBuf;
19210       }
19211     }
19212   }
19213 #else
19214   if( db && db->mallocFailed ){
19215     return 0;
19216   }
19217 #endif
19218   p = sqlite3Malloc(n);
19219   if( !p && db ){
19220     db->mallocFailed = 1;
19221   }
19222   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19223          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19224   return p;
19225 }
19226
19227 /*
19228 ** Resize the block of memory pointed to by p to n bytes. If the
19229 ** resize fails, set the mallocFailed flag in the connection object.
19230 */
19231 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19232   void *pNew = 0;
19233   assert( db!=0 );
19234   assert( sqlite3_mutex_held(db->mutex) );
19235   if( db->mallocFailed==0 ){
19236     if( p==0 ){
19237       return sqlite3DbMallocRaw(db, n);
19238     }
19239     if( isLookaside(db, p) ){
19240       if( n<=db->lookaside.sz ){
19241         return p;
19242       }
19243       pNew = sqlite3DbMallocRaw(db, n);
19244       if( pNew ){
19245         memcpy(pNew, p, db->lookaside.sz);
19246         sqlite3DbFree(db, p);
19247       }
19248     }else{
19249       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19250       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19251       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19252       pNew = sqlite3_realloc(p, n);
19253       if( !pNew ){
19254         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19255         db->mallocFailed = 1;
19256       }
19257       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19258             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19259     }
19260   }
19261   return pNew;
19262 }
19263
19264 /*
19265 ** Attempt to reallocate p.  If the reallocation fails, then free p
19266 ** and set the mallocFailed flag in the database connection.
19267 */
19268 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19269   void *pNew;
19270   pNew = sqlite3DbRealloc(db, p, n);
19271   if( !pNew ){
19272     sqlite3DbFree(db, p);
19273   }
19274   return pNew;
19275 }
19276
19277 /*
19278 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19279 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19280 ** is because when memory debugging is turned on, these two functions are 
19281 ** called via macros that record the current file and line number in the
19282 ** ThreadData structure.
19283 */
19284 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19285   char *zNew;
19286   size_t n;
19287   if( z==0 ){
19288     return 0;
19289   }
19290   n = sqlite3Strlen30(z) + 1;
19291   assert( (n&0x7fffffff)==n );
19292   zNew = sqlite3DbMallocRaw(db, (int)n);
19293   if( zNew ){
19294     memcpy(zNew, z, n);
19295   }
19296   return zNew;
19297 }
19298 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19299   char *zNew;
19300   if( z==0 ){
19301     return 0;
19302   }
19303   assert( (n&0x7fffffff)==n );
19304   zNew = sqlite3DbMallocRaw(db, n+1);
19305   if( zNew ){
19306     memcpy(zNew, z, n);
19307     zNew[n] = 0;
19308   }
19309   return zNew;
19310 }
19311
19312 /*
19313 ** Create a string from the zFromat argument and the va_list that follows.
19314 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19315 ** point to that string.
19316 */
19317 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19318   va_list ap;
19319   char *z;
19320
19321   va_start(ap, zFormat);
19322   z = sqlite3VMPrintf(db, zFormat, ap);
19323   va_end(ap);
19324   sqlite3DbFree(db, *pz);
19325   *pz = z;
19326 }
19327
19328
19329 /*
19330 ** This function must be called before exiting any API function (i.e. 
19331 ** returning control to the user) that has called sqlite3_malloc or
19332 ** sqlite3_realloc.
19333 **
19334 ** The returned value is normally a copy of the second argument to this
19335 ** function. However, if a malloc() failure has occurred since the previous
19336 ** invocation SQLITE_NOMEM is returned instead. 
19337 **
19338 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19339 ** then the connection error-code (the value returned by sqlite3_errcode())
19340 ** is set to SQLITE_NOMEM.
19341 */
19342 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19343   /* If the db handle is not NULL, then we must hold the connection handle
19344   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19345   ** is unsafe, as is the call to sqlite3Error().
19346   */
19347   assert( !db || sqlite3_mutex_held(db->mutex) );
19348   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19349     sqlite3Error(db, SQLITE_NOMEM, 0);
19350     db->mallocFailed = 0;
19351     rc = SQLITE_NOMEM;
19352   }
19353   return rc & (db ? db->errMask : 0xff);
19354 }
19355
19356 /************** End of malloc.c **********************************************/
19357 /************** Begin file printf.c ******************************************/
19358 /*
19359 ** The "printf" code that follows dates from the 1980's.  It is in
19360 ** the public domain.  The original comments are included here for
19361 ** completeness.  They are very out-of-date but might be useful as
19362 ** an historical reference.  Most of the "enhancements" have been backed
19363 ** out so that the functionality is now the same as standard printf().
19364 **
19365 **************************************************************************
19366 **
19367 ** This file contains code for a set of "printf"-like routines.  These
19368 ** routines format strings much like the printf() from the standard C
19369 ** library, though the implementation here has enhancements to support
19370 ** SQLlite.
19371 */
19372
19373 /*
19374 ** Conversion types fall into various categories as defined by the
19375 ** following enumeration.
19376 */
19377 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19378 #define etFLOAT       2 /* Floating point.  %f */
19379 #define etEXP         3 /* Exponentional notation. %e and %E */
19380 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19381 #define etSIZE        5 /* Return number of characters processed so far. %n */
19382 #define etSTRING      6 /* Strings. %s */
19383 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19384 #define etPERCENT     8 /* Percent symbol. %% */
19385 #define etCHARX       9 /* Characters. %c */
19386 /* The rest are extensions, not normally found in printf() */
19387 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19388 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19389                           NULL pointers replaced by SQL NULL.  %Q */
19390 #define etTOKEN      12 /* a pointer to a Token structure */
19391 #define etSRCLIST    13 /* a pointer to a SrcList */
19392 #define etPOINTER    14 /* The %p conversion */
19393 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19394 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19395
19396 #define etINVALID     0 /* Any unrecognized conversion type */
19397
19398
19399 /*
19400 ** An "etByte" is an 8-bit unsigned value.
19401 */
19402 typedef unsigned char etByte;
19403
19404 /*
19405 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19406 ** by an instance of the following structure
19407 */
19408 typedef struct et_info {   /* Information about each format field */
19409   char fmttype;            /* The format field code letter */
19410   etByte base;             /* The base for radix conversion */
19411   etByte flags;            /* One or more of FLAG_ constants below */
19412   etByte type;             /* Conversion paradigm */
19413   etByte charset;          /* Offset into aDigits[] of the digits string */
19414   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19415 } et_info;
19416
19417 /*
19418 ** Allowed values for et_info.flags
19419 */
19420 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19421 #define FLAG_INTERN  2     /* True if for internal use only */
19422 #define FLAG_STRING  4     /* Allow infinity precision */
19423
19424
19425 /*
19426 ** The following table is searched linearly, so it is good to put the
19427 ** most frequently used conversion types first.
19428 */
19429 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19430 static const char aPrefix[] = "-x0\000X0";
19431 static const et_info fmtinfo[] = {
19432   {  'd', 10, 1, etRADIX,      0,  0 },
19433   {  's',  0, 4, etSTRING,     0,  0 },
19434   {  'g',  0, 1, etGENERIC,    30, 0 },
19435   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19436   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19437   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19438   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19439   {  'c',  0, 0, etCHARX,      0,  0 },
19440   {  'o',  8, 0, etRADIX,      0,  2 },
19441   {  'u', 10, 0, etRADIX,      0,  0 },
19442   {  'x', 16, 0, etRADIX,      16, 1 },
19443   {  'X', 16, 0, etRADIX,      0,  4 },
19444 #ifndef SQLITE_OMIT_FLOATING_POINT
19445   {  'f',  0, 1, etFLOAT,      0,  0 },
19446   {  'e',  0, 1, etEXP,        30, 0 },
19447   {  'E',  0, 1, etEXP,        14, 0 },
19448   {  'G',  0, 1, etGENERIC,    14, 0 },
19449 #endif
19450   {  'i', 10, 1, etRADIX,      0,  0 },
19451   {  'n',  0, 0, etSIZE,       0,  0 },
19452   {  '%',  0, 0, etPERCENT,    0,  0 },
19453   {  'p', 16, 0, etPOINTER,    0,  1 },
19454
19455 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19456 ** use only */
19457   {  'T',  0, 2, etTOKEN,      0,  0 },
19458   {  'S',  0, 2, etSRCLIST,    0,  0 },
19459   {  'r', 10, 3, etORDINAL,    0,  0 },
19460 };
19461
19462 /*
19463 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19464 ** conversions will work.
19465 */
19466 #ifndef SQLITE_OMIT_FLOATING_POINT
19467 /*
19468 ** "*val" is a double such that 0.1 <= *val < 10.0
19469 ** Return the ascii code for the leading digit of *val, then
19470 ** multiply "*val" by 10.0 to renormalize.
19471 **
19472 ** Example:
19473 **     input:     *val = 3.14159
19474 **     output:    *val = 1.4159    function return = '3'
19475 **
19476 ** The counter *cnt is incremented each time.  After counter exceeds
19477 ** 16 (the number of significant digits in a 64-bit float) '0' is
19478 ** always returned.
19479 */
19480 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19481   int digit;
19482   LONGDOUBLE_TYPE d;
19483   if( (*cnt)<=0 ) return '0';
19484   (*cnt)--;
19485   digit = (int)*val;
19486   d = digit;
19487   digit += '0';
19488   *val = (*val - d)*10.0;
19489   return (char)digit;
19490 }
19491 #endif /* SQLITE_OMIT_FLOATING_POINT */
19492
19493 /*
19494 ** Append N space characters to the given string buffer.
19495 */
19496 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19497   static const char zSpaces[] = "                             ";
19498   while( N>=(int)sizeof(zSpaces)-1 ){
19499     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19500     N -= sizeof(zSpaces)-1;
19501   }
19502   if( N>0 ){
19503     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19504   }
19505 }
19506
19507 /*
19508 ** On machines with a small stack size, you can redefine the
19509 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19510 */
19511 #ifndef SQLITE_PRINT_BUF_SIZE
19512 # define SQLITE_PRINT_BUF_SIZE 70
19513 #endif
19514 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19515
19516 /*
19517 ** Render a string given by "fmt" into the StrAccum object.
19518 */
19519 SQLITE_PRIVATE void sqlite3VXPrintf(
19520   StrAccum *pAccum,                  /* Accumulate results here */
19521   int useExtended,                   /* Allow extended %-conversions */
19522   const char *fmt,                   /* Format string */
19523   va_list ap                         /* arguments */
19524 ){
19525   int c;                     /* Next character in the format string */
19526   char *bufpt;               /* Pointer to the conversion buffer */
19527   int precision;             /* Precision of the current field */
19528   int length;                /* Length of the field */
19529   int idx;                   /* A general purpose loop counter */
19530   int width;                 /* Width of the current field */
19531   etByte flag_leftjustify;   /* True if "-" flag is present */
19532   etByte flag_plussign;      /* True if "+" flag is present */
19533   etByte flag_blanksign;     /* True if " " flag is present */
19534   etByte flag_alternateform; /* True if "#" flag is present */
19535   etByte flag_altform2;      /* True if "!" flag is present */
19536   etByte flag_zeropad;       /* True if field width constant starts with zero */
19537   etByte flag_long;          /* True if "l" flag is present */
19538   etByte flag_longlong;      /* True if the "ll" flag is present */
19539   etByte done;               /* Loop termination flag */
19540   etByte xtype = 0;          /* Conversion paradigm */
19541   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19542   sqlite_uint64 longvalue;   /* Value for integer types */
19543   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19544   const et_info *infop;      /* Pointer to the appropriate info structure */
19545   char *zOut;                /* Rendering buffer */
19546   int nOut;                  /* Size of the rendering buffer */
19547   char *zExtra;              /* Malloced memory used by some conversion */
19548 #ifndef SQLITE_OMIT_FLOATING_POINT
19549   int  exp, e2;              /* exponent of real numbers */
19550   int nsd;                   /* Number of significant digits returned */
19551   double rounder;            /* Used for rounding floating point values */
19552   etByte flag_dp;            /* True if decimal point should be shown */
19553   etByte flag_rtz;           /* True if trailing zeros should be removed */
19554 #endif
19555   char buf[etBUFSIZE];       /* Conversion buffer */
19556
19557   bufpt = 0;
19558   for(; (c=(*fmt))!=0; ++fmt){
19559     if( c!='%' ){
19560       int amt;
19561       bufpt = (char *)fmt;
19562       amt = 1;
19563       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19564       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19565       if( c==0 ) break;
19566     }
19567     if( (c=(*++fmt))==0 ){
19568       sqlite3StrAccumAppend(pAccum, "%", 1);
19569       break;
19570     }
19571     /* Find out what flags are present */
19572     flag_leftjustify = flag_plussign = flag_blanksign = 
19573      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19574     done = 0;
19575     do{
19576       switch( c ){
19577         case '-':   flag_leftjustify = 1;     break;
19578         case '+':   flag_plussign = 1;        break;
19579         case ' ':   flag_blanksign = 1;       break;
19580         case '#':   flag_alternateform = 1;   break;
19581         case '!':   flag_altform2 = 1;        break;
19582         case '0':   flag_zeropad = 1;         break;
19583         default:    done = 1;                 break;
19584       }
19585     }while( !done && (c=(*++fmt))!=0 );
19586     /* Get the field width */
19587     width = 0;
19588     if( c=='*' ){
19589       width = va_arg(ap,int);
19590       if( width<0 ){
19591         flag_leftjustify = 1;
19592         width = -width;
19593       }
19594       c = *++fmt;
19595     }else{
19596       while( c>='0' && c<='9' ){
19597         width = width*10 + c - '0';
19598         c = *++fmt;
19599       }
19600     }
19601     /* Get the precision */
19602     if( c=='.' ){
19603       precision = 0;
19604       c = *++fmt;
19605       if( c=='*' ){
19606         precision = va_arg(ap,int);
19607         if( precision<0 ) precision = -precision;
19608         c = *++fmt;
19609       }else{
19610         while( c>='0' && c<='9' ){
19611           precision = precision*10 + c - '0';
19612           c = *++fmt;
19613         }
19614       }
19615     }else{
19616       precision = -1;
19617     }
19618     /* Get the conversion type modifier */
19619     if( c=='l' ){
19620       flag_long = 1;
19621       c = *++fmt;
19622       if( c=='l' ){
19623         flag_longlong = 1;
19624         c = *++fmt;
19625       }else{
19626         flag_longlong = 0;
19627       }
19628     }else{
19629       flag_long = flag_longlong = 0;
19630     }
19631     /* Fetch the info entry for the field */
19632     infop = &fmtinfo[0];
19633     xtype = etINVALID;
19634     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19635       if( c==fmtinfo[idx].fmttype ){
19636         infop = &fmtinfo[idx];
19637         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19638           xtype = infop->type;
19639         }else{
19640           return;
19641         }
19642         break;
19643       }
19644     }
19645     zExtra = 0;
19646
19647     /*
19648     ** At this point, variables are initialized as follows:
19649     **
19650     **   flag_alternateform          TRUE if a '#' is present.
19651     **   flag_altform2               TRUE if a '!' is present.
19652     **   flag_plussign               TRUE if a '+' is present.
19653     **   flag_leftjustify            TRUE if a '-' is present or if the
19654     **                               field width was negative.
19655     **   flag_zeropad                TRUE if the width began with 0.
19656     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19657     **                               the conversion character.
19658     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19659     **                               the conversion character.
19660     **   flag_blanksign              TRUE if a ' ' is present.
19661     **   width                       The specified field width.  This is
19662     **                               always non-negative.  Zero is the default.
19663     **   precision                   The specified precision.  The default
19664     **                               is -1.
19665     **   xtype                       The class of the conversion.
19666     **   infop                       Pointer to the appropriate info struct.
19667     */
19668     switch( xtype ){
19669       case etPOINTER:
19670         flag_longlong = sizeof(char*)==sizeof(i64);
19671         flag_long = sizeof(char*)==sizeof(long int);
19672         /* Fall through into the next case */
19673       case etORDINAL:
19674       case etRADIX:
19675         if( infop->flags & FLAG_SIGNED ){
19676           i64 v;
19677           if( flag_longlong ){
19678             v = va_arg(ap,i64);
19679           }else if( flag_long ){
19680             v = va_arg(ap,long int);
19681           }else{
19682             v = va_arg(ap,int);
19683           }
19684           if( v<0 ){
19685             if( v==SMALLEST_INT64 ){
19686               longvalue = ((u64)1)<<63;
19687             }else{
19688               longvalue = -v;
19689             }
19690             prefix = '-';
19691           }else{
19692             longvalue = v;
19693             if( flag_plussign )        prefix = '+';
19694             else if( flag_blanksign )  prefix = ' ';
19695             else                       prefix = 0;
19696           }
19697         }else{
19698           if( flag_longlong ){
19699             longvalue = va_arg(ap,u64);
19700           }else if( flag_long ){
19701             longvalue = va_arg(ap,unsigned long int);
19702           }else{
19703             longvalue = va_arg(ap,unsigned int);
19704           }
19705           prefix = 0;
19706         }
19707         if( longvalue==0 ) flag_alternateform = 0;
19708         if( flag_zeropad && precision<width-(prefix!=0) ){
19709           precision = width-(prefix!=0);
19710         }
19711         if( precision<etBUFSIZE-10 ){
19712           nOut = etBUFSIZE;
19713           zOut = buf;
19714         }else{
19715           nOut = precision + 10;
19716           zOut = zExtra = sqlite3Malloc( nOut );
19717           if( zOut==0 ){
19718             pAccum->mallocFailed = 1;
19719             return;
19720           }
19721         }
19722         bufpt = &zOut[nOut-1];
19723         if( xtype==etORDINAL ){
19724           static const char zOrd[] = "thstndrd";
19725           int x = (int)(longvalue % 10);
19726           if( x>=4 || (longvalue/10)%10==1 ){
19727             x = 0;
19728           }
19729           *(--bufpt) = zOrd[x*2+1];
19730           *(--bufpt) = zOrd[x*2];
19731         }
19732         {
19733           register const char *cset;      /* Use registers for speed */
19734           register int base;
19735           cset = &aDigits[infop->charset];
19736           base = infop->base;
19737           do{                                           /* Convert to ascii */
19738             *(--bufpt) = cset[longvalue%base];
19739             longvalue = longvalue/base;
19740           }while( longvalue>0 );
19741         }
19742         length = (int)(&zOut[nOut-1]-bufpt);
19743         for(idx=precision-length; idx>0; idx--){
19744           *(--bufpt) = '0';                             /* Zero pad */
19745         }
19746         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19747         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19748           const char *pre;
19749           char x;
19750           pre = &aPrefix[infop->prefix];
19751           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19752         }
19753         length = (int)(&zOut[nOut-1]-bufpt);
19754         break;
19755       case etFLOAT:
19756       case etEXP:
19757       case etGENERIC:
19758         realvalue = va_arg(ap,double);
19759 #ifdef SQLITE_OMIT_FLOATING_POINT
19760         length = 0;
19761 #else
19762         if( precision<0 ) precision = 6;         /* Set default precision */
19763         if( realvalue<0.0 ){
19764           realvalue = -realvalue;
19765           prefix = '-';
19766         }else{
19767           if( flag_plussign )          prefix = '+';
19768           else if( flag_blanksign )    prefix = ' ';
19769           else                         prefix = 0;
19770         }
19771         if( xtype==etGENERIC && precision>0 ) precision--;
19772 #if 0
19773         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19774         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19775 #else
19776         /* It makes more sense to use 0.5 */
19777         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19778 #endif
19779         if( xtype==etFLOAT ) realvalue += rounder;
19780         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19781         exp = 0;
19782         if( sqlite3IsNaN((double)realvalue) ){
19783           bufpt = "NaN";
19784           length = 3;
19785           break;
19786         }
19787         if( realvalue>0.0 ){
19788           LONGDOUBLE_TYPE scale = 1.0;
19789           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19790           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19791           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19792           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19793           realvalue /= scale;
19794           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19795           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19796           if( exp>350 ){
19797             if( prefix=='-' ){
19798               bufpt = "-Inf";
19799             }else if( prefix=='+' ){
19800               bufpt = "+Inf";
19801             }else{
19802               bufpt = "Inf";
19803             }
19804             length = sqlite3Strlen30(bufpt);
19805             break;
19806           }
19807         }
19808         bufpt = buf;
19809         /*
19810         ** If the field type is etGENERIC, then convert to either etEXP
19811         ** or etFLOAT, as appropriate.
19812         */
19813         if( xtype!=etFLOAT ){
19814           realvalue += rounder;
19815           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19816         }
19817         if( xtype==etGENERIC ){
19818           flag_rtz = !flag_alternateform;
19819           if( exp<-4 || exp>precision ){
19820             xtype = etEXP;
19821           }else{
19822             precision = precision - exp;
19823             xtype = etFLOAT;
19824           }
19825         }else{
19826           flag_rtz = flag_altform2;
19827         }
19828         if( xtype==etEXP ){
19829           e2 = 0;
19830         }else{
19831           e2 = exp;
19832         }
19833         if( e2+precision+width > etBUFSIZE - 15 ){
19834           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19835           if( bufpt==0 ){
19836             pAccum->mallocFailed = 1;
19837             return;
19838           }
19839         }
19840         zOut = bufpt;
19841         nsd = 16 + flag_altform2*10;
19842         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19843         /* The sign in front of the number */
19844         if( prefix ){
19845           *(bufpt++) = prefix;
19846         }
19847         /* Digits prior to the decimal point */
19848         if( e2<0 ){
19849           *(bufpt++) = '0';
19850         }else{
19851           for(; e2>=0; e2--){
19852             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19853           }
19854         }
19855         /* The decimal point */
19856         if( flag_dp ){
19857           *(bufpt++) = '.';
19858         }
19859         /* "0" digits after the decimal point but before the first
19860         ** significant digit of the number */
19861         for(e2++; e2<0; precision--, e2++){
19862           assert( precision>0 );
19863           *(bufpt++) = '0';
19864         }
19865         /* Significant digits after the decimal point */
19866         while( (precision--)>0 ){
19867           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19868         }
19869         /* Remove trailing zeros and the "." if no digits follow the "." */
19870         if( flag_rtz && flag_dp ){
19871           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19872           assert( bufpt>zOut );
19873           if( bufpt[-1]=='.' ){
19874             if( flag_altform2 ){
19875               *(bufpt++) = '0';
19876             }else{
19877               *(--bufpt) = 0;
19878             }
19879           }
19880         }
19881         /* Add the "eNNN" suffix */
19882         if( xtype==etEXP ){
19883           *(bufpt++) = aDigits[infop->charset];
19884           if( exp<0 ){
19885             *(bufpt++) = '-'; exp = -exp;
19886           }else{
19887             *(bufpt++) = '+';
19888           }
19889           if( exp>=100 ){
19890             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19891             exp %= 100;
19892           }
19893           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19894           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19895         }
19896         *bufpt = 0;
19897
19898         /* The converted number is in buf[] and zero terminated. Output it.
19899         ** Note that the number is in the usual order, not reversed as with
19900         ** integer conversions. */
19901         length = (int)(bufpt-zOut);
19902         bufpt = zOut;
19903
19904         /* Special case:  Add leading zeros if the flag_zeropad flag is
19905         ** set and we are not left justified */
19906         if( flag_zeropad && !flag_leftjustify && length < width){
19907           int i;
19908           int nPad = width - length;
19909           for(i=width; i>=nPad; i--){
19910             bufpt[i] = bufpt[i-nPad];
19911           }
19912           i = prefix!=0;
19913           while( nPad-- ) bufpt[i++] = '0';
19914           length = width;
19915         }
19916 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19917         break;
19918       case etSIZE:
19919         *(va_arg(ap,int*)) = pAccum->nChar;
19920         length = width = 0;
19921         break;
19922       case etPERCENT:
19923         buf[0] = '%';
19924         bufpt = buf;
19925         length = 1;
19926         break;
19927       case etCHARX:
19928         c = va_arg(ap,int);
19929         buf[0] = (char)c;
19930         if( precision>=0 ){
19931           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19932           length = precision;
19933         }else{
19934           length =1;
19935         }
19936         bufpt = buf;
19937         break;
19938       case etSTRING:
19939       case etDYNSTRING:
19940         bufpt = va_arg(ap,char*);
19941         if( bufpt==0 ){
19942           bufpt = "";
19943         }else if( xtype==etDYNSTRING ){
19944           zExtra = bufpt;
19945         }
19946         if( precision>=0 ){
19947           for(length=0; length<precision && bufpt[length]; length++){}
19948         }else{
19949           length = sqlite3Strlen30(bufpt);
19950         }
19951         break;
19952       case etSQLESCAPE:
19953       case etSQLESCAPE2:
19954       case etSQLESCAPE3: {
19955         int i, j, k, n, isnull;
19956         int needQuote;
19957         char ch;
19958         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19959         char *escarg = va_arg(ap,char*);
19960         isnull = escarg==0;
19961         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19962         k = precision;
19963         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19964           if( ch==q )  n++;
19965         }
19966         needQuote = !isnull && xtype==etSQLESCAPE2;
19967         n += i + 1 + needQuote*2;
19968         if( n>etBUFSIZE ){
19969           bufpt = zExtra = sqlite3Malloc( n );
19970           if( bufpt==0 ){
19971             pAccum->mallocFailed = 1;
19972             return;
19973           }
19974         }else{
19975           bufpt = buf;
19976         }
19977         j = 0;
19978         if( needQuote ) bufpt[j++] = q;
19979         k = i;
19980         for(i=0; i<k; i++){
19981           bufpt[j++] = ch = escarg[i];
19982           if( ch==q ) bufpt[j++] = ch;
19983         }
19984         if( needQuote ) bufpt[j++] = q;
19985         bufpt[j] = 0;
19986         length = j;
19987         /* The precision in %q and %Q means how many input characters to
19988         ** consume, not the length of the output...
19989         ** if( precision>=0 && precision<length ) length = precision; */
19990         break;
19991       }
19992       case etTOKEN: {
19993         Token *pToken = va_arg(ap, Token*);
19994         if( pToken ){
19995           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19996         }
19997         length = width = 0;
19998         break;
19999       }
20000       case etSRCLIST: {
20001         SrcList *pSrc = va_arg(ap, SrcList*);
20002         int k = va_arg(ap, int);
20003         struct SrcList_item *pItem = &pSrc->a[k];
20004         assert( k>=0 && k<pSrc->nSrc );
20005         if( pItem->zDatabase ){
20006           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20007           sqlite3StrAccumAppend(pAccum, ".", 1);
20008         }
20009         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20010         length = width = 0;
20011         break;
20012       }
20013       default: {
20014         assert( xtype==etINVALID );
20015         return;
20016       }
20017     }/* End switch over the format type */
20018     /*
20019     ** The text of the conversion is pointed to by "bufpt" and is
20020     ** "length" characters long.  The field width is "width".  Do
20021     ** the output.
20022     */
20023     if( !flag_leftjustify ){
20024       register int nspace;
20025       nspace = width-length;
20026       if( nspace>0 ){
20027         sqlite3AppendSpace(pAccum, nspace);
20028       }
20029     }
20030     if( length>0 ){
20031       sqlite3StrAccumAppend(pAccum, bufpt, length);
20032     }
20033     if( flag_leftjustify ){
20034       register int nspace;
20035       nspace = width-length;
20036       if( nspace>0 ){
20037         sqlite3AppendSpace(pAccum, nspace);
20038       }
20039     }
20040     sqlite3_free(zExtra);
20041   }/* End for loop over the format string */
20042 } /* End of function */
20043
20044 /*
20045 ** Append N bytes of text from z to the StrAccum object.
20046 */
20047 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20048   assert( z!=0 || N==0 );
20049   if( p->tooBig | p->mallocFailed ){
20050     testcase(p->tooBig);
20051     testcase(p->mallocFailed);
20052     return;
20053   }
20054   assert( p->zText!=0 || p->nChar==0 );
20055   if( N<0 ){
20056     N = sqlite3Strlen30(z);
20057   }
20058   if( N==0 || NEVER(z==0) ){
20059     return;
20060   }
20061   if( p->nChar+N >= p->nAlloc ){
20062     char *zNew;
20063     if( !p->useMalloc ){
20064       p->tooBig = 1;
20065       N = p->nAlloc - p->nChar - 1;
20066       if( N<=0 ){
20067         return;
20068       }
20069     }else{
20070       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20071       i64 szNew = p->nChar;
20072       szNew += N + 1;
20073       if( szNew > p->mxAlloc ){
20074         sqlite3StrAccumReset(p);
20075         p->tooBig = 1;
20076         return;
20077       }else{
20078         p->nAlloc = (int)szNew;
20079       }
20080       if( p->useMalloc==1 ){
20081         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20082       }else{
20083         zNew = sqlite3_realloc(zOld, p->nAlloc);
20084       }
20085       if( zNew ){
20086         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20087         p->zText = zNew;
20088       }else{
20089         p->mallocFailed = 1;
20090         sqlite3StrAccumReset(p);
20091         return;
20092       }
20093     }
20094   }
20095   assert( p->zText );
20096   memcpy(&p->zText[p->nChar], z, N);
20097   p->nChar += N;
20098 }
20099
20100 /*
20101 ** Finish off a string by making sure it is zero-terminated.
20102 ** Return a pointer to the resulting string.  Return a NULL
20103 ** pointer if any kind of error was encountered.
20104 */
20105 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20106   if( p->zText ){
20107     p->zText[p->nChar] = 0;
20108     if( p->useMalloc && p->zText==p->zBase ){
20109       if( p->useMalloc==1 ){
20110         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20111       }else{
20112         p->zText = sqlite3_malloc(p->nChar+1);
20113       }
20114       if( p->zText ){
20115         memcpy(p->zText, p->zBase, p->nChar+1);
20116       }else{
20117         p->mallocFailed = 1;
20118       }
20119     }
20120   }
20121   return p->zText;
20122 }
20123
20124 /*
20125 ** Reset an StrAccum string.  Reclaim all malloced memory.
20126 */
20127 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20128   if( p->zText!=p->zBase ){
20129     if( p->useMalloc==1 ){
20130       sqlite3DbFree(p->db, p->zText);
20131     }else{
20132       sqlite3_free(p->zText);
20133     }
20134   }
20135   p->zText = 0;
20136 }
20137
20138 /*
20139 ** Initialize a string accumulator
20140 */
20141 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20142   p->zText = p->zBase = zBase;
20143   p->db = 0;
20144   p->nChar = 0;
20145   p->nAlloc = n;
20146   p->mxAlloc = mx;
20147   p->useMalloc = 1;
20148   p->tooBig = 0;
20149   p->mallocFailed = 0;
20150 }
20151
20152 /*
20153 ** Print into memory obtained from sqliteMalloc().  Use the internal
20154 ** %-conversion extensions.
20155 */
20156 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20157   char *z;
20158   char zBase[SQLITE_PRINT_BUF_SIZE];
20159   StrAccum acc;
20160   assert( db!=0 );
20161   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20162                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20163   acc.db = db;
20164   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20165   z = sqlite3StrAccumFinish(&acc);
20166   if( acc.mallocFailed ){
20167     db->mallocFailed = 1;
20168   }
20169   return z;
20170 }
20171
20172 /*
20173 ** Print into memory obtained from sqliteMalloc().  Use the internal
20174 ** %-conversion extensions.
20175 */
20176 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20177   va_list ap;
20178   char *z;
20179   va_start(ap, zFormat);
20180   z = sqlite3VMPrintf(db, zFormat, ap);
20181   va_end(ap);
20182   return z;
20183 }
20184
20185 /*
20186 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20187 ** the string and before returnning.  This routine is intended to be used
20188 ** to modify an existing string.  For example:
20189 **
20190 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20191 **
20192 */
20193 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20194   va_list ap;
20195   char *z;
20196   va_start(ap, zFormat);
20197   z = sqlite3VMPrintf(db, zFormat, ap);
20198   va_end(ap);
20199   sqlite3DbFree(db, zStr);
20200   return z;
20201 }
20202
20203 /*
20204 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20205 ** %-conversion extensions.
20206 */
20207 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20208   char *z;
20209   char zBase[SQLITE_PRINT_BUF_SIZE];
20210   StrAccum acc;
20211 #ifndef SQLITE_OMIT_AUTOINIT
20212   if( sqlite3_initialize() ) return 0;
20213 #endif
20214   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20215   acc.useMalloc = 2;
20216   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20217   z = sqlite3StrAccumFinish(&acc);
20218   return z;
20219 }
20220
20221 /*
20222 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20223 ** %-conversion extensions.
20224 */
20225 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20226   va_list ap;
20227   char *z;
20228 #ifndef SQLITE_OMIT_AUTOINIT
20229   if( sqlite3_initialize() ) return 0;
20230 #endif
20231   va_start(ap, zFormat);
20232   z = sqlite3_vmprintf(zFormat, ap);
20233   va_end(ap);
20234   return z;
20235 }
20236
20237 /*
20238 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20239 ** current locale settings.  This is important for SQLite because we
20240 ** are not able to use a "," as the decimal point in place of "." as
20241 ** specified by some locales.
20242 **
20243 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20244 ** from the snprintf() standard.  Unfortunately, it is too late to change
20245 ** this without breaking compatibility, so we just have to live with the
20246 ** mistake.
20247 **
20248 ** sqlite3_vsnprintf() is the varargs version.
20249 */
20250 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20251   StrAccum acc;
20252   if( n<=0 ) return zBuf;
20253   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20254   acc.useMalloc = 0;
20255   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20256   return sqlite3StrAccumFinish(&acc);
20257 }
20258 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20259   char *z;
20260   va_list ap;
20261   va_start(ap,zFormat);
20262   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20263   va_end(ap);
20264   return z;
20265 }
20266
20267 /*
20268 ** This is the routine that actually formats the sqlite3_log() message.
20269 ** We house it in a separate routine from sqlite3_log() to avoid using
20270 ** stack space on small-stack systems when logging is disabled.
20271 **
20272 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20273 ** allocate memory because it might be called while the memory allocator
20274 ** mutex is held.
20275 */
20276 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20277   StrAccum acc;                          /* String accumulator */
20278   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20279
20280   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20281   acc.useMalloc = 0;
20282   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20283   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20284                            sqlite3StrAccumFinish(&acc));
20285 }
20286
20287 /*
20288 ** Format and write a message to the log if logging is enabled.
20289 */
20290 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20291   va_list ap;                             /* Vararg list */
20292   if( sqlite3GlobalConfig.xLog ){
20293     va_start(ap, zFormat);
20294     renderLogMsg(iErrCode, zFormat, ap);
20295     va_end(ap);
20296   }
20297 }
20298
20299 #if defined(SQLITE_DEBUG)
20300 /*
20301 ** A version of printf() that understands %lld.  Used for debugging.
20302 ** The printf() built into some versions of windows does not understand %lld
20303 ** and segfaults if you give it a long long int.
20304 */
20305 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20306   va_list ap;
20307   StrAccum acc;
20308   char zBuf[500];
20309   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20310   acc.useMalloc = 0;
20311   va_start(ap,zFormat);
20312   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20313   va_end(ap);
20314   sqlite3StrAccumFinish(&acc);
20315   fprintf(stdout,"%s", zBuf);
20316   fflush(stdout);
20317 }
20318 #endif
20319
20320 #ifndef SQLITE_OMIT_TRACE
20321 /*
20322 ** variable-argument wrapper around sqlite3VXPrintf().
20323 */
20324 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20325   va_list ap;
20326   va_start(ap,zFormat);
20327   sqlite3VXPrintf(p, 1, zFormat, ap);
20328   va_end(ap);
20329 }
20330 #endif
20331
20332 /************** End of printf.c **********************************************/
20333 /************** Begin file random.c ******************************************/
20334 /*
20335 ** 2001 September 15
20336 **
20337 ** The author disclaims copyright to this source code.  In place of
20338 ** a legal notice, here is a blessing:
20339 **
20340 **    May you do good and not evil.
20341 **    May you find forgiveness for yourself and forgive others.
20342 **    May you share freely, never taking more than you give.
20343 **
20344 *************************************************************************
20345 ** This file contains code to implement a pseudo-random number
20346 ** generator (PRNG) for SQLite.
20347 **
20348 ** Random numbers are used by some of the database backends in order
20349 ** to generate random integer keys for tables or random filenames.
20350 */
20351
20352
20353 /* All threads share a single random number generator.
20354 ** This structure is the current state of the generator.
20355 */
20356 static SQLITE_WSD struct sqlite3PrngType {
20357   unsigned char isInit;          /* True if initialized */
20358   unsigned char i, j;            /* State variables */
20359   unsigned char s[256];          /* State variables */
20360 } sqlite3Prng;
20361
20362 /*
20363 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20364 ** must be held while executing this routine.
20365 **
20366 ** Why not just use a library random generator like lrand48() for this?
20367 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20368 ** good source of random numbers.  The lrand48() library function may
20369 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20370 ** subtle problems on some systems that could cause problems.  It is hard
20371 ** to know.  To minimize the risk of problems due to bad lrand48()
20372 ** implementations, SQLite uses this random number generator based
20373 ** on RC4, which we know works very well.
20374 **
20375 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20376 ** randomness any more.  But we will leave this code in all the same.
20377 */
20378 static u8 randomByte(void){
20379   unsigned char t;
20380
20381
20382   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20383   ** state vector.  If writable static data is unsupported on the target,
20384   ** we have to locate the state vector at run-time.  In the more common
20385   ** case where writable static data is supported, wsdPrng can refer directly
20386   ** to the "sqlite3Prng" state vector declared above.
20387   */
20388 #ifdef SQLITE_OMIT_WSD
20389   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20390 # define wsdPrng p[0]
20391 #else
20392 # define wsdPrng sqlite3Prng
20393 #endif
20394
20395
20396   /* Initialize the state of the random number generator once,
20397   ** the first time this routine is called.  The seed value does
20398   ** not need to contain a lot of randomness since we are not
20399   ** trying to do secure encryption or anything like that...
20400   **
20401   ** Nothing in this file or anywhere else in SQLite does any kind of
20402   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20403   ** number generator) not as an encryption device.
20404   */
20405   if( !wsdPrng.isInit ){
20406     int i;
20407     char k[256];
20408     wsdPrng.j = 0;
20409     wsdPrng.i = 0;
20410     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20411     for(i=0; i<256; i++){
20412       wsdPrng.s[i] = (u8)i;
20413     }
20414     for(i=0; i<256; i++){
20415       wsdPrng.j += wsdPrng.s[i] + k[i];
20416       t = wsdPrng.s[wsdPrng.j];
20417       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20418       wsdPrng.s[i] = t;
20419     }
20420     wsdPrng.isInit = 1;
20421   }
20422
20423   /* Generate and return single random byte
20424   */
20425   wsdPrng.i++;
20426   t = wsdPrng.s[wsdPrng.i];
20427   wsdPrng.j += t;
20428   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20429   wsdPrng.s[wsdPrng.j] = t;
20430   t += wsdPrng.s[wsdPrng.i];
20431   return wsdPrng.s[t];
20432 }
20433
20434 /*
20435 ** Return N random bytes.
20436 */
20437 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20438   unsigned char *zBuf = pBuf;
20439 #if SQLITE_THREADSAFE
20440   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20441 #endif
20442   sqlite3_mutex_enter(mutex);
20443   while( N-- ){
20444     *(zBuf++) = randomByte();
20445   }
20446   sqlite3_mutex_leave(mutex);
20447 }
20448
20449 #ifndef SQLITE_OMIT_BUILTIN_TEST
20450 /*
20451 ** For testing purposes, we sometimes want to preserve the state of
20452 ** PRNG and restore the PRNG to its saved state at a later time, or
20453 ** to reset the PRNG to its initial state.  These routines accomplish
20454 ** those tasks.
20455 **
20456 ** The sqlite3_test_control() interface calls these routines to
20457 ** control the PRNG.
20458 */
20459 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20460 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20461   memcpy(
20462     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20463     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20464     sizeof(sqlite3Prng)
20465   );
20466 }
20467 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20468   memcpy(
20469     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20470     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20471     sizeof(sqlite3Prng)
20472   );
20473 }
20474 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20475   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20476 }
20477 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20478
20479 /************** End of random.c **********************************************/
20480 /************** Begin file utf.c *********************************************/
20481 /*
20482 ** 2004 April 13
20483 **
20484 ** The author disclaims copyright to this source code.  In place of
20485 ** a legal notice, here is a blessing:
20486 **
20487 **    May you do good and not evil.
20488 **    May you find forgiveness for yourself and forgive others.
20489 **    May you share freely, never taking more than you give.
20490 **
20491 *************************************************************************
20492 ** This file contains routines used to translate between UTF-8, 
20493 ** UTF-16, UTF-16BE, and UTF-16LE.
20494 **
20495 ** Notes on UTF-8:
20496 **
20497 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20498 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20499 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20500 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20501 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20502 **
20503 **
20504 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20505 **
20506 **      Word-0               Word-1          Value
20507 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20508 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20509 **
20510 **
20511 ** BOM or Byte Order Mark:
20512 **     0xff 0xfe   little-endian utf-16 follows
20513 **     0xfe 0xff   big-endian utf-16 follows
20514 **
20515 */
20516 /* #include <assert.h> */
20517
20518 #ifndef SQLITE_AMALGAMATION
20519 /*
20520 ** The following constant value is used by the SQLITE_BIGENDIAN and
20521 ** SQLITE_LITTLEENDIAN macros.
20522 */
20523 SQLITE_PRIVATE const int sqlite3one = 1;
20524 #endif /* SQLITE_AMALGAMATION */
20525
20526 /*
20527 ** This lookup table is used to help decode the first byte of
20528 ** a multi-byte UTF8 character.
20529 */
20530 static const unsigned char sqlite3Utf8Trans1[] = {
20531   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20532   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20533   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20534   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20535   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20536   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20537   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20538   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20539 };
20540
20541
20542 #define WRITE_UTF8(zOut, c) {                          \
20543   if( c<0x00080 ){                                     \
20544     *zOut++ = (u8)(c&0xFF);                            \
20545   }                                                    \
20546   else if( c<0x00800 ){                                \
20547     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20548     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20549   }                                                    \
20550   else if( c<0x10000 ){                                \
20551     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20552     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20553     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20554   }else{                                               \
20555     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20556     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20557     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20558     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20559   }                                                    \
20560 }
20561
20562 #define WRITE_UTF16LE(zOut, c) {                                    \
20563   if( c<=0xFFFF ){                                                  \
20564     *zOut++ = (u8)(c&0x00FF);                                       \
20565     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20566   }else{                                                            \
20567     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20568     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20569     *zOut++ = (u8)(c&0x00FF);                                       \
20570     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20571   }                                                                 \
20572 }
20573
20574 #define WRITE_UTF16BE(zOut, c) {                                    \
20575   if( c<=0xFFFF ){                                                  \
20576     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20577     *zOut++ = (u8)(c&0x00FF);                                       \
20578   }else{                                                            \
20579     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20580     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20581     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20582     *zOut++ = (u8)(c&0x00FF);                                       \
20583   }                                                                 \
20584 }
20585
20586 #define READ_UTF16LE(zIn, TERM, c){                                   \
20587   c = (*zIn++);                                                       \
20588   c += ((*zIn++)<<8);                                                 \
20589   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20590     int c2 = (*zIn++);                                                \
20591     c2 += ((*zIn++)<<8);                                              \
20592     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20593   }                                                                   \
20594 }
20595
20596 #define READ_UTF16BE(zIn, TERM, c){                                   \
20597   c = ((*zIn++)<<8);                                                  \
20598   c += (*zIn++);                                                      \
20599   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20600     int c2 = ((*zIn++)<<8);                                           \
20601     c2 += (*zIn++);                                                   \
20602     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20603   }                                                                   \
20604 }
20605
20606 /*
20607 ** Translate a single UTF-8 character.  Return the unicode value.
20608 **
20609 ** During translation, assume that the byte that zTerm points
20610 ** is a 0x00.
20611 **
20612 ** Write a pointer to the next unread byte back into *pzNext.
20613 **
20614 ** Notes On Invalid UTF-8:
20615 **
20616 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20617 **     be encoded as a multi-byte character.  Any multi-byte character that
20618 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20619 **
20620 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20621 **     If a multi-byte character attempts to encode a value between
20622 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20623 **
20624 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20625 **     byte of a character are interpreted as single-byte characters
20626 **     and rendered as themselves even though they are technically
20627 **     invalid characters.
20628 **
20629 **  *  This routine accepts an infinite number of different UTF8 encodings
20630 **     for unicode values 0x80 and greater.  It do not change over-length
20631 **     encodings to 0xfffd as some systems recommend.
20632 */
20633 #define READ_UTF8(zIn, zTerm, c)                           \
20634   c = *(zIn++);                                            \
20635   if( c>=0xc0 ){                                           \
20636     c = sqlite3Utf8Trans1[c-0xc0];                         \
20637     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20638       c = (c<<6) + (0x3f & *(zIn++));                      \
20639     }                                                      \
20640     if( c<0x80                                             \
20641         || (c&0xFFFFF800)==0xD800                          \
20642         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20643   }
20644 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20645   const unsigned char **pz    /* Pointer to string from which to read char */
20646 ){
20647   unsigned int c;
20648
20649   /* Same as READ_UTF8() above but without the zTerm parameter.
20650   ** For this routine, we assume the UTF8 string is always zero-terminated.
20651   */
20652   c = *((*pz)++);
20653   if( c>=0xc0 ){
20654     c = sqlite3Utf8Trans1[c-0xc0];
20655     while( (*(*pz) & 0xc0)==0x80 ){
20656       c = (c<<6) + (0x3f & *((*pz)++));
20657     }
20658     if( c<0x80
20659         || (c&0xFFFFF800)==0xD800
20660         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20661   }
20662   return c;
20663 }
20664
20665
20666
20667
20668 /*
20669 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20670 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20671 */ 
20672 /* #define TRANSLATE_TRACE 1 */
20673
20674 #ifndef SQLITE_OMIT_UTF16
20675 /*
20676 ** This routine transforms the internal text encoding used by pMem to
20677 ** desiredEnc. It is an error if the string is already of the desired
20678 ** encoding, or if *pMem does not contain a string value.
20679 */
20680 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20681   int len;                    /* Maximum length of output string in bytes */
20682   unsigned char *zOut;                  /* Output buffer */
20683   unsigned char *zIn;                   /* Input iterator */
20684   unsigned char *zTerm;                 /* End of input */
20685   unsigned char *z;                     /* Output iterator */
20686   unsigned int c;
20687
20688   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20689   assert( pMem->flags&MEM_Str );
20690   assert( pMem->enc!=desiredEnc );
20691   assert( pMem->enc!=0 );
20692   assert( pMem->n>=0 );
20693
20694 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20695   {
20696     char zBuf[100];
20697     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20698     fprintf(stderr, "INPUT:  %s\n", zBuf);
20699   }
20700 #endif
20701
20702   /* If the translation is between UTF-16 little and big endian, then 
20703   ** all that is required is to swap the byte order. This case is handled
20704   ** differently from the others.
20705   */
20706   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20707     u8 temp;
20708     int rc;
20709     rc = sqlite3VdbeMemMakeWriteable(pMem);
20710     if( rc!=SQLITE_OK ){
20711       assert( rc==SQLITE_NOMEM );
20712       return SQLITE_NOMEM;
20713     }
20714     zIn = (u8*)pMem->z;
20715     zTerm = &zIn[pMem->n&~1];
20716     while( zIn<zTerm ){
20717       temp = *zIn;
20718       *zIn = *(zIn+1);
20719       zIn++;
20720       *zIn++ = temp;
20721     }
20722     pMem->enc = desiredEnc;
20723     goto translate_out;
20724   }
20725
20726   /* Set len to the maximum number of bytes required in the output buffer. */
20727   if( desiredEnc==SQLITE_UTF8 ){
20728     /* When converting from UTF-16, the maximum growth results from
20729     ** translating a 2-byte character to a 4-byte UTF-8 character.
20730     ** A single byte is required for the output string
20731     ** nul-terminator.
20732     */
20733     pMem->n &= ~1;
20734     len = pMem->n * 2 + 1;
20735   }else{
20736     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20737     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20738     ** character. Two bytes are required in the output buffer for the
20739     ** nul-terminator.
20740     */
20741     len = pMem->n * 2 + 2;
20742   }
20743
20744   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20745   ** byte past the end.
20746   **
20747   ** Variable zOut is set to point at the output buffer, space obtained
20748   ** from sqlite3_malloc().
20749   */
20750   zIn = (u8*)pMem->z;
20751   zTerm = &zIn[pMem->n];
20752   zOut = sqlite3DbMallocRaw(pMem->db, len);
20753   if( !zOut ){
20754     return SQLITE_NOMEM;
20755   }
20756   z = zOut;
20757
20758   if( pMem->enc==SQLITE_UTF8 ){
20759     if( desiredEnc==SQLITE_UTF16LE ){
20760       /* UTF-8 -> UTF-16 Little-endian */
20761       while( zIn<zTerm ){
20762         READ_UTF8(zIn, zTerm, c);
20763         WRITE_UTF16LE(z, c);
20764       }
20765     }else{
20766       assert( desiredEnc==SQLITE_UTF16BE );
20767       /* UTF-8 -> UTF-16 Big-endian */
20768       while( zIn<zTerm ){
20769         READ_UTF8(zIn, zTerm, c);
20770         WRITE_UTF16BE(z, c);
20771       }
20772     }
20773     pMem->n = (int)(z - zOut);
20774     *z++ = 0;
20775   }else{
20776     assert( desiredEnc==SQLITE_UTF8 );
20777     if( pMem->enc==SQLITE_UTF16LE ){
20778       /* UTF-16 Little-endian -> UTF-8 */
20779       while( zIn<zTerm ){
20780         READ_UTF16LE(zIn, zIn<zTerm, c); 
20781         WRITE_UTF8(z, c);
20782       }
20783     }else{
20784       /* UTF-16 Big-endian -> UTF-8 */
20785       while( zIn<zTerm ){
20786         READ_UTF16BE(zIn, zIn<zTerm, c); 
20787         WRITE_UTF8(z, c);
20788       }
20789     }
20790     pMem->n = (int)(z - zOut);
20791   }
20792   *z = 0;
20793   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20794
20795   sqlite3VdbeMemRelease(pMem);
20796   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20797   pMem->enc = desiredEnc;
20798   pMem->flags |= (MEM_Term|MEM_Dyn);
20799   pMem->z = (char*)zOut;
20800   pMem->zMalloc = pMem->z;
20801
20802 translate_out:
20803 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20804   {
20805     char zBuf[100];
20806     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20807     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20808   }
20809 #endif
20810   return SQLITE_OK;
20811 }
20812
20813 /*
20814 ** This routine checks for a byte-order mark at the beginning of the 
20815 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20816 ** the encoding of the Mem adjusted. This routine does not do any
20817 ** byte-swapping, it just sets Mem.enc appropriately.
20818 **
20819 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20820 ** changed by this function.
20821 */
20822 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20823   int rc = SQLITE_OK;
20824   u8 bom = 0;
20825
20826   assert( pMem->n>=0 );
20827   if( pMem->n>1 ){
20828     u8 b1 = *(u8 *)pMem->z;
20829     u8 b2 = *(((u8 *)pMem->z) + 1);
20830     if( b1==0xFE && b2==0xFF ){
20831       bom = SQLITE_UTF16BE;
20832     }
20833     if( b1==0xFF && b2==0xFE ){
20834       bom = SQLITE_UTF16LE;
20835     }
20836   }
20837   
20838   if( bom ){
20839     rc = sqlite3VdbeMemMakeWriteable(pMem);
20840     if( rc==SQLITE_OK ){
20841       pMem->n -= 2;
20842       memmove(pMem->z, &pMem->z[2], pMem->n);
20843       pMem->z[pMem->n] = '\0';
20844       pMem->z[pMem->n+1] = '\0';
20845       pMem->flags |= MEM_Term;
20846       pMem->enc = bom;
20847     }
20848   }
20849   return rc;
20850 }
20851 #endif /* SQLITE_OMIT_UTF16 */
20852
20853 /*
20854 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20855 ** return the number of unicode characters in pZ up to (but not including)
20856 ** the first 0x00 byte. If nByte is not less than zero, return the
20857 ** number of unicode characters in the first nByte of pZ (or up to 
20858 ** the first 0x00, whichever comes first).
20859 */
20860 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20861   int r = 0;
20862   const u8 *z = (const u8*)zIn;
20863   const u8 *zTerm;
20864   if( nByte>=0 ){
20865     zTerm = &z[nByte];
20866   }else{
20867     zTerm = (const u8*)(-1);
20868   }
20869   assert( z<=zTerm );
20870   while( *z!=0 && z<zTerm ){
20871     SQLITE_SKIP_UTF8(z);
20872     r++;
20873   }
20874   return r;
20875 }
20876
20877 /* This test function is not currently used by the automated test-suite. 
20878 ** Hence it is only available in debug builds.
20879 */
20880 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20881 /*
20882 ** Translate UTF-8 to UTF-8.
20883 **
20884 ** This has the effect of making sure that the string is well-formed
20885 ** UTF-8.  Miscoded characters are removed.
20886 **
20887 ** The translation is done in-place and aborted if the output
20888 ** overruns the input.
20889 */
20890 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20891   unsigned char *zOut = zIn;
20892   unsigned char *zStart = zIn;
20893   u32 c;
20894
20895   while( zIn[0] && zOut<=zIn ){
20896     c = sqlite3Utf8Read((const u8**)&zIn);
20897     if( c!=0xfffd ){
20898       WRITE_UTF8(zOut, c);
20899     }
20900   }
20901   *zOut = 0;
20902   return (int)(zOut - zStart);
20903 }
20904 #endif
20905
20906 #ifndef SQLITE_OMIT_UTF16
20907 /*
20908 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20909 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20910 ** be freed by the calling function.
20911 **
20912 ** NULL is returned if there is an allocation error.
20913 */
20914 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20915   Mem m;
20916   memset(&m, 0, sizeof(m));
20917   m.db = db;
20918   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20919   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20920   if( db->mallocFailed ){
20921     sqlite3VdbeMemRelease(&m);
20922     m.z = 0;
20923   }
20924   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20925   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20926   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20927   assert( m.z || db->mallocFailed );
20928   return m.z;
20929 }
20930
20931 /*
20932 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20933 ** enc. A pointer to the new string is returned, and the value of *pnOut
20934 ** is set to the length of the returned string in bytes. The call should
20935 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20936 ** no longer required.
20937 ** 
20938 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20939 ** flag set.
20940 */
20941 #ifdef SQLITE_ENABLE_STAT3
20942 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20943   Mem m;
20944   memset(&m, 0, sizeof(m));
20945   m.db = db;
20946   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20947   if( sqlite3VdbeMemTranslate(&m, enc) ){
20948     assert( db->mallocFailed );
20949     return 0;
20950   }
20951   assert( m.z==m.zMalloc );
20952   *pnOut = m.n;
20953   return m.z;
20954 }
20955 #endif
20956
20957 /*
20958 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20959 ** Return the number of bytes in the first nChar unicode characters
20960 ** in pZ.  nChar must be non-negative.
20961 */
20962 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20963   int c;
20964   unsigned char const *z = zIn;
20965   int n = 0;
20966   
20967   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20968     while( n<nChar ){
20969       READ_UTF16BE(z, 1, c);
20970       n++;
20971     }
20972   }else{
20973     while( n<nChar ){
20974       READ_UTF16LE(z, 1, c);
20975       n++;
20976     }
20977   }
20978   return (int)(z-(unsigned char const *)zIn);
20979 }
20980
20981 #if defined(SQLITE_TEST)
20982 /*
20983 ** This routine is called from the TCL test function "translate_selftest".
20984 ** It checks that the primitives for serializing and deserializing
20985 ** characters in each encoding are inverses of each other.
20986 */
20987 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20988   unsigned int i, t;
20989   unsigned char zBuf[20];
20990   unsigned char *z;
20991   int n;
20992   unsigned int c;
20993
20994   for(i=0; i<0x00110000; i++){
20995     z = zBuf;
20996     WRITE_UTF8(z, i);
20997     n = (int)(z-zBuf);
20998     assert( n>0 && n<=4 );
20999     z[0] = 0;
21000     z = zBuf;
21001     c = sqlite3Utf8Read((const u8**)&z);
21002     t = i;
21003     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21004     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21005     assert( c==t );
21006     assert( (z-zBuf)==n );
21007   }
21008   for(i=0; i<0x00110000; i++){
21009     if( i>=0xD800 && i<0xE000 ) continue;
21010     z = zBuf;
21011     WRITE_UTF16LE(z, i);
21012     n = (int)(z-zBuf);
21013     assert( n>0 && n<=4 );
21014     z[0] = 0;
21015     z = zBuf;
21016     READ_UTF16LE(z, 1, c);
21017     assert( c==i );
21018     assert( (z-zBuf)==n );
21019   }
21020   for(i=0; i<0x00110000; i++){
21021     if( i>=0xD800 && i<0xE000 ) continue;
21022     z = zBuf;
21023     WRITE_UTF16BE(z, i);
21024     n = (int)(z-zBuf);
21025     assert( n>0 && n<=4 );
21026     z[0] = 0;
21027     z = zBuf;
21028     READ_UTF16BE(z, 1, c);
21029     assert( c==i );
21030     assert( (z-zBuf)==n );
21031   }
21032 }
21033 #endif /* SQLITE_TEST */
21034 #endif /* SQLITE_OMIT_UTF16 */
21035
21036 /************** End of utf.c *************************************************/
21037 /************** Begin file util.c ********************************************/
21038 /*
21039 ** 2001 September 15
21040 **
21041 ** The author disclaims copyright to this source code.  In place of
21042 ** a legal notice, here is a blessing:
21043 **
21044 **    May you do good and not evil.
21045 **    May you find forgiveness for yourself and forgive others.
21046 **    May you share freely, never taking more than you give.
21047 **
21048 *************************************************************************
21049 ** Utility functions used throughout sqlite.
21050 **
21051 ** This file contains functions for allocating memory, comparing
21052 ** strings, and stuff like that.
21053 **
21054 */
21055 /* #include <stdarg.h> */
21056 #ifdef SQLITE_HAVE_ISNAN
21057 # include <math.h>
21058 #endif
21059
21060 /*
21061 ** Routine needed to support the testcase() macro.
21062 */
21063 #ifdef SQLITE_COVERAGE_TEST
21064 SQLITE_PRIVATE void sqlite3Coverage(int x){
21065   static unsigned dummy = 0;
21066   dummy += (unsigned)x;
21067 }
21068 #endif
21069
21070 #ifndef SQLITE_OMIT_FLOATING_POINT
21071 /*
21072 ** Return true if the floating point value is Not a Number (NaN).
21073 **
21074 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21075 ** Otherwise, we have our own implementation that works on most systems.
21076 */
21077 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21078   int rc;   /* The value return */
21079 #if !defined(SQLITE_HAVE_ISNAN)
21080   /*
21081   ** Systems that support the isnan() library function should probably
21082   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21083   ** found that many systems do not have a working isnan() function so
21084   ** this implementation is provided as an alternative.
21085   **
21086   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21087   ** On the other hand, the use of -ffast-math comes with the following
21088   ** warning:
21089   **
21090   **      This option [-ffast-math] should never be turned on by any
21091   **      -O option since it can result in incorrect output for programs
21092   **      which depend on an exact implementation of IEEE or ISO 
21093   **      rules/specifications for math functions.
21094   **
21095   ** Under MSVC, this NaN test may fail if compiled with a floating-
21096   ** point precision mode other than /fp:precise.  From the MSDN 
21097   ** documentation:
21098   **
21099   **      The compiler [with /fp:precise] will properly handle comparisons 
21100   **      involving NaN. For example, x != x evaluates to true if x is NaN 
21101   **      ...
21102   */
21103 #ifdef __FAST_MATH__
21104 # error SQLite will not work correctly with the -ffast-math option of GCC.
21105 #endif
21106   volatile double y = x;
21107   volatile double z = y;
21108   rc = (y!=z);
21109 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21110   rc = isnan(x);
21111 #endif /* SQLITE_HAVE_ISNAN */
21112   testcase( rc );
21113   return rc;
21114 }
21115 #endif /* SQLITE_OMIT_FLOATING_POINT */
21116
21117 /*
21118 ** Compute a string length that is limited to what can be stored in
21119 ** lower 30 bits of a 32-bit signed integer.
21120 **
21121 ** The value returned will never be negative.  Nor will it ever be greater
21122 ** than the actual length of the string.  For very long strings (greater
21123 ** than 1GiB) the value returned might be less than the true string length.
21124 */
21125 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21126   const char *z2 = z;
21127   if( z==0 ) return 0;
21128   while( *z2 ){ z2++; }
21129   return 0x3fffffff & (int)(z2 - z);
21130 }
21131
21132 /*
21133 ** Set the most recent error code and error string for the sqlite
21134 ** handle "db". The error code is set to "err_code".
21135 **
21136 ** If it is not NULL, string zFormat specifies the format of the
21137 ** error string in the style of the printf functions: The following
21138 ** format characters are allowed:
21139 **
21140 **      %s      Insert a string
21141 **      %z      A string that should be freed after use
21142 **      %d      Insert an integer
21143 **      %T      Insert a token
21144 **      %S      Insert the first element of a SrcList
21145 **
21146 ** zFormat and any string tokens that follow it are assumed to be
21147 ** encoded in UTF-8.
21148 **
21149 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21150 ** should be called with err_code set to SQLITE_OK and zFormat set
21151 ** to NULL.
21152 */
21153 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21154   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21155     db->errCode = err_code;
21156     if( zFormat ){
21157       char *z;
21158       va_list ap;
21159       va_start(ap, zFormat);
21160       z = sqlite3VMPrintf(db, zFormat, ap);
21161       va_end(ap);
21162       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21163     }else{
21164       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21165     }
21166   }
21167 }
21168
21169 /*
21170 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21171 ** The following formatting characters are allowed:
21172 **
21173 **      %s      Insert a string
21174 **      %z      A string that should be freed after use
21175 **      %d      Insert an integer
21176 **      %T      Insert a token
21177 **      %S      Insert the first element of a SrcList
21178 **
21179 ** This function should be used to report any error that occurs whilst
21180 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21181 ** last thing the sqlite3_prepare() function does is copy the error
21182 ** stored by this function into the database handle using sqlite3Error().
21183 ** Function sqlite3Error() should be used during statement execution
21184 ** (sqlite3_step() etc.).
21185 */
21186 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21187   char *zMsg;
21188   va_list ap;
21189   sqlite3 *db = pParse->db;
21190   va_start(ap, zFormat);
21191   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21192   va_end(ap);
21193   if( db->suppressErr ){
21194     sqlite3DbFree(db, zMsg);
21195   }else{
21196     pParse->nErr++;
21197     sqlite3DbFree(db, pParse->zErrMsg);
21198     pParse->zErrMsg = zMsg;
21199     pParse->rc = SQLITE_ERROR;
21200   }
21201 }
21202
21203 /*
21204 ** Convert an SQL-style quoted string into a normal string by removing
21205 ** the quote characters.  The conversion is done in-place.  If the
21206 ** input does not begin with a quote character, then this routine
21207 ** is a no-op.
21208 **
21209 ** The input string must be zero-terminated.  A new zero-terminator
21210 ** is added to the dequoted string.
21211 **
21212 ** The return value is -1 if no dequoting occurs or the length of the
21213 ** dequoted string, exclusive of the zero terminator, if dequoting does
21214 ** occur.
21215 **
21216 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21217 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21218 ** "a-b-c".
21219 */
21220 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21221   char quote;
21222   int i, j;
21223   if( z==0 ) return -1;
21224   quote = z[0];
21225   switch( quote ){
21226     case '\'':  break;
21227     case '"':   break;
21228     case '`':   break;                /* For MySQL compatibility */
21229     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21230     default:    return -1;
21231   }
21232   for(i=1, j=0; ALWAYS(z[i]); i++){
21233     if( z[i]==quote ){
21234       if( z[i+1]==quote ){
21235         z[j++] = quote;
21236         i++;
21237       }else{
21238         break;
21239       }
21240     }else{
21241       z[j++] = z[i];
21242     }
21243   }
21244   z[j] = 0;
21245   return j;
21246 }
21247
21248 /* Convenient short-hand */
21249 #define UpperToLower sqlite3UpperToLower
21250
21251 /*
21252 ** Some systems have stricmp().  Others have strcasecmp().  Because
21253 ** there is no consistency, we will define our own.
21254 **
21255 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21256 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21257 ** the contents of two buffers containing UTF-8 strings in a
21258 ** case-independent fashion, using the same definition of "case
21259 ** independence" that SQLite uses internally when comparing identifiers.
21260 */
21261 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21262   register unsigned char *a, *b;
21263   a = (unsigned char *)zLeft;
21264   b = (unsigned char *)zRight;
21265   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21266   return UpperToLower[*a] - UpperToLower[*b];
21267 }
21268 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21269   register unsigned char *a, *b;
21270   a = (unsigned char *)zLeft;
21271   b = (unsigned char *)zRight;
21272   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21273   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21274 }
21275
21276 /*
21277 ** The string z[] is an text representation of a real number.
21278 ** Convert this string to a double and write it into *pResult.
21279 **
21280 ** The string z[] is length bytes in length (bytes, not characters) and
21281 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21282 **
21283 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21284 ** if the string is empty or contains extraneous text.  Valid numbers
21285 ** are in one of these formats:
21286 **
21287 **    [+-]digits[E[+-]digits]
21288 **    [+-]digits.[digits][E[+-]digits]
21289 **    [+-].digits[E[+-]digits]
21290 **
21291 ** Leading and trailing whitespace is ignored for the purpose of determining
21292 ** validity.
21293 **
21294 ** If some prefix of the input string is a valid number, this routine
21295 ** returns FALSE but it still converts the prefix and writes the result
21296 ** into *pResult.
21297 */
21298 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21299 #ifndef SQLITE_OMIT_FLOATING_POINT
21300   int incr = (enc==SQLITE_UTF8?1:2);
21301   const char *zEnd = z + length;
21302   /* sign * significand * (10 ^ (esign * exponent)) */
21303   int sign = 1;    /* sign of significand */
21304   i64 s = 0;       /* significand */
21305   int d = 0;       /* adjust exponent for shifting decimal point */
21306   int esign = 1;   /* sign of exponent */
21307   int e = 0;       /* exponent */
21308   int eValid = 1;  /* True exponent is either not used or is well-formed */
21309   double result;
21310   int nDigits = 0;
21311
21312   *pResult = 0.0;   /* Default return value, in case of an error */
21313
21314   if( enc==SQLITE_UTF16BE ) z++;
21315
21316   /* skip leading spaces */
21317   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21318   if( z>=zEnd ) return 0;
21319
21320   /* get sign of significand */
21321   if( *z=='-' ){
21322     sign = -1;
21323     z+=incr;
21324   }else if( *z=='+' ){
21325     z+=incr;
21326   }
21327
21328   /* skip leading zeroes */
21329   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21330
21331   /* copy max significant digits to significand */
21332   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21333     s = s*10 + (*z - '0');
21334     z+=incr, nDigits++;
21335   }
21336
21337   /* skip non-significant significand digits
21338   ** (increase exponent by d to shift decimal left) */
21339   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21340   if( z>=zEnd ) goto do_atof_calc;
21341
21342   /* if decimal point is present */
21343   if( *z=='.' ){
21344     z+=incr;
21345     /* copy digits from after decimal to significand
21346     ** (decrease exponent by d to shift decimal right) */
21347     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21348       s = s*10 + (*z - '0');
21349       z+=incr, nDigits++, d--;
21350     }
21351     /* skip non-significant digits */
21352     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21353   }
21354   if( z>=zEnd ) goto do_atof_calc;
21355
21356   /* if exponent is present */
21357   if( *z=='e' || *z=='E' ){
21358     z+=incr;
21359     eValid = 0;
21360     if( z>=zEnd ) goto do_atof_calc;
21361     /* get sign of exponent */
21362     if( *z=='-' ){
21363       esign = -1;
21364       z+=incr;
21365     }else if( *z=='+' ){
21366       z+=incr;
21367     }
21368     /* copy digits to exponent */
21369     while( z<zEnd && sqlite3Isdigit(*z) ){
21370       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21371       z+=incr;
21372       eValid = 1;
21373     }
21374   }
21375
21376   /* skip trailing spaces */
21377   if( nDigits && eValid ){
21378     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21379   }
21380
21381 do_atof_calc:
21382   /* adjust exponent by d, and update sign */
21383   e = (e*esign) + d;
21384   if( e<0 ) {
21385     esign = -1;
21386     e *= -1;
21387   } else {
21388     esign = 1;
21389   }
21390
21391   /* if 0 significand */
21392   if( !s ) {
21393     /* In the IEEE 754 standard, zero is signed.
21394     ** Add the sign if we've seen at least one digit */
21395     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21396   } else {
21397     /* attempt to reduce exponent */
21398     if( esign>0 ){
21399       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21400     }else{
21401       while( !(s%10) && e>0 ) e--,s/=10;
21402     }
21403
21404     /* adjust the sign of significand */
21405     s = sign<0 ? -s : s;
21406
21407     /* if exponent, scale significand as appropriate
21408     ** and store in result. */
21409     if( e ){
21410       LONGDOUBLE_TYPE scale = 1.0;
21411       /* attempt to handle extremely small/large numbers better */
21412       if( e>307 && e<342 ){
21413         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21414         if( esign<0 ){
21415           result = s / scale;
21416           result /= 1.0e+308;
21417         }else{
21418           result = s * scale;
21419           result *= 1.0e+308;
21420         }
21421       }else if( e>=342 ){
21422         if( esign<0 ){
21423           result = 0.0*s;
21424         }else{
21425           result = 1e308*1e308*s;  /* Infinity */
21426         }
21427       }else{
21428         /* 1.0e+22 is the largest power of 10 than can be 
21429         ** represented exactly. */
21430         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21431         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21432         if( esign<0 ){
21433           result = s / scale;
21434         }else{
21435           result = s * scale;
21436         }
21437       }
21438     } else {
21439       result = (double)s;
21440     }
21441   }
21442
21443   /* store the result */
21444   *pResult = result;
21445
21446   /* return true if number and no extra non-whitespace chracters after */
21447   return z>=zEnd && nDigits>0 && eValid;
21448 #else
21449   return !sqlite3Atoi64(z, pResult, length, enc);
21450 #endif /* SQLITE_OMIT_FLOATING_POINT */
21451 }
21452
21453 /*
21454 ** Compare the 19-character string zNum against the text representation
21455 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21456 ** if zNum is less than, equal to, or greater than the string.
21457 ** Note that zNum must contain exactly 19 characters.
21458 **
21459 ** Unlike memcmp() this routine is guaranteed to return the difference
21460 ** in the values of the last digit if the only difference is in the
21461 ** last digit.  So, for example,
21462 **
21463 **      compare2pow63("9223372036854775800", 1)
21464 **
21465 ** will return -8.
21466 */
21467 static int compare2pow63(const char *zNum, int incr){
21468   int c = 0;
21469   int i;
21470                     /* 012345678901234567 */
21471   const char *pow63 = "922337203685477580";
21472   for(i=0; c==0 && i<18; i++){
21473     c = (zNum[i*incr]-pow63[i])*10;
21474   }
21475   if( c==0 ){
21476     c = zNum[18*incr] - '8';
21477     testcase( c==(-1) );
21478     testcase( c==0 );
21479     testcase( c==(+1) );
21480   }
21481   return c;
21482 }
21483
21484
21485 /*
21486 ** Convert zNum to a 64-bit signed integer.
21487 **
21488 ** If the zNum value is representable as a 64-bit twos-complement 
21489 ** integer, then write that value into *pNum and return 0.
21490 **
21491 ** If zNum is exactly 9223372036854665808, return 2.  This special
21492 ** case is broken out because while 9223372036854665808 cannot be a 
21493 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21494 **
21495 ** If zNum is too big for a 64-bit integer and is not
21496 ** 9223372036854665808 then return 1.
21497 **
21498 ** length is the number of bytes in the string (bytes, not characters).
21499 ** The string is not necessarily zero-terminated.  The encoding is
21500 ** given by enc.
21501 */
21502 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21503   int incr = (enc==SQLITE_UTF8?1:2);
21504   u64 u = 0;
21505   int neg = 0; /* assume positive */
21506   int i;
21507   int c = 0;
21508   const char *zStart;
21509   const char *zEnd = zNum + length;
21510   if( enc==SQLITE_UTF16BE ) zNum++;
21511   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21512   if( zNum<zEnd ){
21513     if( *zNum=='-' ){
21514       neg = 1;
21515       zNum+=incr;
21516     }else if( *zNum=='+' ){
21517       zNum+=incr;
21518     }
21519   }
21520   zStart = zNum;
21521   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21522   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21523     u = u*10 + c - '0';
21524   }
21525   if( u>LARGEST_INT64 ){
21526     *pNum = SMALLEST_INT64;
21527   }else if( neg ){
21528     *pNum = -(i64)u;
21529   }else{
21530     *pNum = (i64)u;
21531   }
21532   testcase( i==18 );
21533   testcase( i==19 );
21534   testcase( i==20 );
21535   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21536     /* zNum is empty or contains non-numeric text or is longer
21537     ** than 19 digits (thus guaranteeing that it is too large) */
21538     return 1;
21539   }else if( i<19*incr ){
21540     /* Less than 19 digits, so we know that it fits in 64 bits */
21541     assert( u<=LARGEST_INT64 );
21542     return 0;
21543   }else{
21544     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21545     c = compare2pow63(zNum, incr);
21546     if( c<0 ){
21547       /* zNum is less than 9223372036854775808 so it fits */
21548       assert( u<=LARGEST_INT64 );
21549       return 0;
21550     }else if( c>0 ){
21551       /* zNum is greater than 9223372036854775808 so it overflows */
21552       return 1;
21553     }else{
21554       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21555       ** special case 2 overflow if positive */
21556       assert( u-1==LARGEST_INT64 );
21557       assert( (*pNum)==SMALLEST_INT64 );
21558       return neg ? 0 : 2;
21559     }
21560   }
21561 }
21562
21563 /*
21564 ** If zNum represents an integer that will fit in 32-bits, then set
21565 ** *pValue to that integer and return true.  Otherwise return false.
21566 **
21567 ** Any non-numeric characters that following zNum are ignored.
21568 ** This is different from sqlite3Atoi64() which requires the
21569 ** input number to be zero-terminated.
21570 */
21571 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21572   sqlite_int64 v = 0;
21573   int i, c;
21574   int neg = 0;
21575   if( zNum[0]=='-' ){
21576     neg = 1;
21577     zNum++;
21578   }else if( zNum[0]=='+' ){
21579     zNum++;
21580   }
21581   while( zNum[0]=='0' ) zNum++;
21582   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21583     v = v*10 + c;
21584   }
21585
21586   /* The longest decimal representation of a 32 bit integer is 10 digits:
21587   **
21588   **             1234567890
21589   **     2^31 -> 2147483648
21590   */
21591   testcase( i==10 );
21592   if( i>10 ){
21593     return 0;
21594   }
21595   testcase( v-neg==2147483647 );
21596   if( v-neg>2147483647 ){
21597     return 0;
21598   }
21599   if( neg ){
21600     v = -v;
21601   }
21602   *pValue = (int)v;
21603   return 1;
21604 }
21605
21606 /*
21607 ** Return a 32-bit integer value extracted from a string.  If the
21608 ** string is not an integer, just return 0.
21609 */
21610 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21611   int x = 0;
21612   if( z ) sqlite3GetInt32(z, &x);
21613   return x;
21614 }
21615
21616 /*
21617 ** The variable-length integer encoding is as follows:
21618 **
21619 ** KEY:
21620 **         A = 0xxxxxxx    7 bits of data and one flag bit
21621 **         B = 1xxxxxxx    7 bits of data and one flag bit
21622 **         C = xxxxxxxx    8 bits of data
21623 **
21624 **  7 bits - A
21625 ** 14 bits - BA
21626 ** 21 bits - BBA
21627 ** 28 bits - BBBA
21628 ** 35 bits - BBBBA
21629 ** 42 bits - BBBBBA
21630 ** 49 bits - BBBBBBA
21631 ** 56 bits - BBBBBBBA
21632 ** 64 bits - BBBBBBBBC
21633 */
21634
21635 /*
21636 ** Write a 64-bit variable-length integer to memory starting at p[0].
21637 ** The length of data write will be between 1 and 9 bytes.  The number
21638 ** of bytes written is returned.
21639 **
21640 ** A variable-length integer consists of the lower 7 bits of each byte
21641 ** for all bytes that have the 8th bit set and one byte with the 8th
21642 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21643 ** 8 bits and is the last byte.
21644 */
21645 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21646   int i, j, n;
21647   u8 buf[10];
21648   if( v & (((u64)0xff000000)<<32) ){
21649     p[8] = (u8)v;
21650     v >>= 8;
21651     for(i=7; i>=0; i--){
21652       p[i] = (u8)((v & 0x7f) | 0x80);
21653       v >>= 7;
21654     }
21655     return 9;
21656   }    
21657   n = 0;
21658   do{
21659     buf[n++] = (u8)((v & 0x7f) | 0x80);
21660     v >>= 7;
21661   }while( v!=0 );
21662   buf[0] &= 0x7f;
21663   assert( n<=9 );
21664   for(i=0, j=n-1; j>=0; j--, i++){
21665     p[i] = buf[j];
21666   }
21667   return n;
21668 }
21669
21670 /*
21671 ** This routine is a faster version of sqlite3PutVarint() that only
21672 ** works for 32-bit positive integers and which is optimized for
21673 ** the common case of small integers.  A MACRO version, putVarint32,
21674 ** is provided which inlines the single-byte case.  All code should use
21675 ** the MACRO version as this function assumes the single-byte case has
21676 ** already been handled.
21677 */
21678 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21679 #ifndef putVarint32
21680   if( (v & ~0x7f)==0 ){
21681     p[0] = v;
21682     return 1;
21683   }
21684 #endif
21685   if( (v & ~0x3fff)==0 ){
21686     p[0] = (u8)((v>>7) | 0x80);
21687     p[1] = (u8)(v & 0x7f);
21688     return 2;
21689   }
21690   return sqlite3PutVarint(p, v);
21691 }
21692
21693 /*
21694 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21695 ** are defined here rather than simply putting the constant expressions
21696 ** inline in order to work around bugs in the RVT compiler.
21697 **
21698 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21699 **
21700 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21701 */
21702 #define SLOT_2_0     0x001fc07f
21703 #define SLOT_4_2_0   0xf01fc07f
21704
21705
21706 /*
21707 ** Read a 64-bit variable-length integer from memory starting at p[0].
21708 ** Return the number of bytes read.  The value is stored in *v.
21709 */
21710 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21711   u32 a,b,s;
21712
21713   a = *p;
21714   /* a: p0 (unmasked) */
21715   if (!(a&0x80))
21716   {
21717     *v = a;
21718     return 1;
21719   }
21720
21721   p++;
21722   b = *p;
21723   /* b: p1 (unmasked) */
21724   if (!(b&0x80))
21725   {
21726     a &= 0x7f;
21727     a = a<<7;
21728     a |= b;
21729     *v = a;
21730     return 2;
21731   }
21732
21733   /* Verify that constants are precomputed correctly */
21734   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21735   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21736
21737   p++;
21738   a = a<<14;
21739   a |= *p;
21740   /* a: p0<<14 | p2 (unmasked) */
21741   if (!(a&0x80))
21742   {
21743     a &= SLOT_2_0;
21744     b &= 0x7f;
21745     b = b<<7;
21746     a |= b;
21747     *v = a;
21748     return 3;
21749   }
21750
21751   /* CSE1 from below */
21752   a &= SLOT_2_0;
21753   p++;
21754   b = b<<14;
21755   b |= *p;
21756   /* b: p1<<14 | p3 (unmasked) */
21757   if (!(b&0x80))
21758   {
21759     b &= SLOT_2_0;
21760     /* moved CSE1 up */
21761     /* a &= (0x7f<<14)|(0x7f); */
21762     a = a<<7;
21763     a |= b;
21764     *v = a;
21765     return 4;
21766   }
21767
21768   /* a: p0<<14 | p2 (masked) */
21769   /* b: p1<<14 | p3 (unmasked) */
21770   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21771   /* moved CSE1 up */
21772   /* a &= (0x7f<<14)|(0x7f); */
21773   b &= SLOT_2_0;
21774   s = a;
21775   /* s: p0<<14 | p2 (masked) */
21776
21777   p++;
21778   a = a<<14;
21779   a |= *p;
21780   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21781   if (!(a&0x80))
21782   {
21783     /* we can skip these cause they were (effectively) done above in calc'ing s */
21784     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21785     /* b &= (0x7f<<14)|(0x7f); */
21786     b = b<<7;
21787     a |= b;
21788     s = s>>18;
21789     *v = ((u64)s)<<32 | a;
21790     return 5;
21791   }
21792
21793   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21794   s = s<<7;
21795   s |= b;
21796   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21797
21798   p++;
21799   b = b<<14;
21800   b |= *p;
21801   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21802   if (!(b&0x80))
21803   {
21804     /* we can skip this cause it was (effectively) done above in calc'ing s */
21805     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21806     a &= SLOT_2_0;
21807     a = a<<7;
21808     a |= b;
21809     s = s>>18;
21810     *v = ((u64)s)<<32 | a;
21811     return 6;
21812   }
21813
21814   p++;
21815   a = a<<14;
21816   a |= *p;
21817   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21818   if (!(a&0x80))
21819   {
21820     a &= SLOT_4_2_0;
21821     b &= SLOT_2_0;
21822     b = b<<7;
21823     a |= b;
21824     s = s>>11;
21825     *v = ((u64)s)<<32 | a;
21826     return 7;
21827   }
21828
21829   /* CSE2 from below */
21830   a &= SLOT_2_0;
21831   p++;
21832   b = b<<14;
21833   b |= *p;
21834   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21835   if (!(b&0x80))
21836   {
21837     b &= SLOT_4_2_0;
21838     /* moved CSE2 up */
21839     /* a &= (0x7f<<14)|(0x7f); */
21840     a = a<<7;
21841     a |= b;
21842     s = s>>4;
21843     *v = ((u64)s)<<32 | a;
21844     return 8;
21845   }
21846
21847   p++;
21848   a = a<<15;
21849   a |= *p;
21850   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21851
21852   /* moved CSE2 up */
21853   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21854   b &= SLOT_2_0;
21855   b = b<<8;
21856   a |= b;
21857
21858   s = s<<4;
21859   b = p[-4];
21860   b &= 0x7f;
21861   b = b>>3;
21862   s |= b;
21863
21864   *v = ((u64)s)<<32 | a;
21865
21866   return 9;
21867 }
21868
21869 /*
21870 ** Read a 32-bit variable-length integer from memory starting at p[0].
21871 ** Return the number of bytes read.  The value is stored in *v.
21872 **
21873 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21874 ** integer, then set *v to 0xffffffff.
21875 **
21876 ** A MACRO version, getVarint32, is provided which inlines the 
21877 ** single-byte case.  All code should use the MACRO version as 
21878 ** this function assumes the single-byte case has already been handled.
21879 */
21880 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21881   u32 a,b;
21882
21883   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21884   ** by the getVarin32() macro */
21885   a = *p;
21886   /* a: p0 (unmasked) */
21887 #ifndef getVarint32
21888   if (!(a&0x80))
21889   {
21890     /* Values between 0 and 127 */
21891     *v = a;
21892     return 1;
21893   }
21894 #endif
21895
21896   /* The 2-byte case */
21897   p++;
21898   b = *p;
21899   /* b: p1 (unmasked) */
21900   if (!(b&0x80))
21901   {
21902     /* Values between 128 and 16383 */
21903     a &= 0x7f;
21904     a = a<<7;
21905     *v = a | b;
21906     return 2;
21907   }
21908
21909   /* The 3-byte case */
21910   p++;
21911   a = a<<14;
21912   a |= *p;
21913   /* a: p0<<14 | p2 (unmasked) */
21914   if (!(a&0x80))
21915   {
21916     /* Values between 16384 and 2097151 */
21917     a &= (0x7f<<14)|(0x7f);
21918     b &= 0x7f;
21919     b = b<<7;
21920     *v = a | b;
21921     return 3;
21922   }
21923
21924   /* A 32-bit varint is used to store size information in btrees.
21925   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21926   ** A 3-byte varint is sufficient, for example, to record the size
21927   ** of a 1048569-byte BLOB or string.
21928   **
21929   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21930   ** rare larger cases can be handled by the slower 64-bit varint
21931   ** routine.
21932   */
21933 #if 1
21934   {
21935     u64 v64;
21936     u8 n;
21937
21938     p -= 2;
21939     n = sqlite3GetVarint(p, &v64);
21940     assert( n>3 && n<=9 );
21941     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21942       *v = 0xffffffff;
21943     }else{
21944       *v = (u32)v64;
21945     }
21946     return n;
21947   }
21948
21949 #else
21950   /* For following code (kept for historical record only) shows an
21951   ** unrolling for the 3- and 4-byte varint cases.  This code is
21952   ** slightly faster, but it is also larger and much harder to test.
21953   */
21954   p++;
21955   b = b<<14;
21956   b |= *p;
21957   /* b: p1<<14 | p3 (unmasked) */
21958   if (!(b&0x80))
21959   {
21960     /* Values between 2097152 and 268435455 */
21961     b &= (0x7f<<14)|(0x7f);
21962     a &= (0x7f<<14)|(0x7f);
21963     a = a<<7;
21964     *v = a | b;
21965     return 4;
21966   }
21967
21968   p++;
21969   a = a<<14;
21970   a |= *p;
21971   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21972   if (!(a&0x80))
21973   {
21974     /* Values  between 268435456 and 34359738367 */
21975     a &= SLOT_4_2_0;
21976     b &= SLOT_4_2_0;
21977     b = b<<7;
21978     *v = a | b;
21979     return 5;
21980   }
21981
21982   /* We can only reach this point when reading a corrupt database
21983   ** file.  In that case we are not in any hurry.  Use the (relatively
21984   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21985   ** value. */
21986   {
21987     u64 v64;
21988     u8 n;
21989
21990     p -= 4;
21991     n = sqlite3GetVarint(p, &v64);
21992     assert( n>5 && n<=9 );
21993     *v = (u32)v64;
21994     return n;
21995   }
21996 #endif
21997 }
21998
21999 /*
22000 ** Return the number of bytes that will be needed to store the given
22001 ** 64-bit integer.
22002 */
22003 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22004   int i = 0;
22005   do{
22006     i++;
22007     v >>= 7;
22008   }while( v!=0 && ALWAYS(i<9) );
22009   return i;
22010 }
22011
22012
22013 /*
22014 ** Read or write a four-byte big-endian integer value.
22015 */
22016 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22017   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22018 }
22019 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22020   p[0] = (u8)(v>>24);
22021   p[1] = (u8)(v>>16);
22022   p[2] = (u8)(v>>8);
22023   p[3] = (u8)v;
22024 }
22025
22026
22027
22028 /*
22029 ** Translate a single byte of Hex into an integer.
22030 ** This routine only works if h really is a valid hexadecimal
22031 ** character:  0..9a..fA..F
22032 */
22033 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22034   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22035 #ifdef SQLITE_ASCII
22036   h += 9*(1&(h>>6));
22037 #endif
22038 #ifdef SQLITE_EBCDIC
22039   h += 9*(1&~(h>>4));
22040 #endif
22041   return (u8)(h & 0xf);
22042 }
22043
22044 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22045 /*
22046 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22047 ** value.  Return a pointer to its binary value.  Space to hold the
22048 ** binary value has been obtained from malloc and must be freed by
22049 ** the calling routine.
22050 */
22051 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22052   char *zBlob;
22053   int i;
22054
22055   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22056   n--;
22057   if( zBlob ){
22058     for(i=0; i<n; i+=2){
22059       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22060     }
22061     zBlob[i/2] = 0;
22062   }
22063   return zBlob;
22064 }
22065 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22066
22067 /*
22068 ** Log an error that is an API call on a connection pointer that should
22069 ** not have been used.  The "type" of connection pointer is given as the
22070 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22071 */
22072 static void logBadConnection(const char *zType){
22073   sqlite3_log(SQLITE_MISUSE, 
22074      "API call with %s database connection pointer",
22075      zType
22076   );
22077 }
22078
22079 /*
22080 ** Check to make sure we have a valid db pointer.  This test is not
22081 ** foolproof but it does provide some measure of protection against
22082 ** misuse of the interface such as passing in db pointers that are
22083 ** NULL or which have been previously closed.  If this routine returns
22084 ** 1 it means that the db pointer is valid and 0 if it should not be
22085 ** dereferenced for any reason.  The calling function should invoke
22086 ** SQLITE_MISUSE immediately.
22087 **
22088 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22089 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22090 ** open properly and is not fit for general use but which can be
22091 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22092 */
22093 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22094   u32 magic;
22095   if( db==0 ){
22096     logBadConnection("NULL");
22097     return 0;
22098   }
22099   magic = db->magic;
22100   if( magic!=SQLITE_MAGIC_OPEN ){
22101     if( sqlite3SafetyCheckSickOrOk(db) ){
22102       testcase( sqlite3GlobalConfig.xLog!=0 );
22103       logBadConnection("unopened");
22104     }
22105     return 0;
22106   }else{
22107     return 1;
22108   }
22109 }
22110 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22111   u32 magic;
22112   magic = db->magic;
22113   if( magic!=SQLITE_MAGIC_SICK &&
22114       magic!=SQLITE_MAGIC_OPEN &&
22115       magic!=SQLITE_MAGIC_BUSY ){
22116     testcase( sqlite3GlobalConfig.xLog!=0 );
22117     logBadConnection("invalid");
22118     return 0;
22119   }else{
22120     return 1;
22121   }
22122 }
22123
22124 /*
22125 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22126 ** the other 64-bit signed integer at *pA and store the result in *pA.
22127 ** Return 0 on success.  Or if the operation would have resulted in an
22128 ** overflow, leave *pA unchanged and return 1.
22129 */
22130 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22131   i64 iA = *pA;
22132   testcase( iA==0 ); testcase( iA==1 );
22133   testcase( iB==-1 ); testcase( iB==0 );
22134   if( iB>=0 ){
22135     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22136     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22137     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22138     *pA += iB;
22139   }else{
22140     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22141     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22142     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22143     *pA += iB;
22144   }
22145   return 0; 
22146 }
22147 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22148   testcase( iB==SMALLEST_INT64+1 );
22149   if( iB==SMALLEST_INT64 ){
22150     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22151     if( (*pA)>=0 ) return 1;
22152     *pA -= iB;
22153     return 0;
22154   }else{
22155     return sqlite3AddInt64(pA, -iB);
22156   }
22157 }
22158 #define TWOPOWER32 (((i64)1)<<32)
22159 #define TWOPOWER31 (((i64)1)<<31)
22160 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22161   i64 iA = *pA;
22162   i64 iA1, iA0, iB1, iB0, r;
22163
22164   iA1 = iA/TWOPOWER32;
22165   iA0 = iA % TWOPOWER32;
22166   iB1 = iB/TWOPOWER32;
22167   iB0 = iB % TWOPOWER32;
22168   if( iA1*iB1 != 0 ) return 1;
22169   assert( iA1*iB0==0 || iA0*iB1==0 );
22170   r = iA1*iB0 + iA0*iB1;
22171   testcase( r==(-TWOPOWER31)-1 );
22172   testcase( r==(-TWOPOWER31) );
22173   testcase( r==TWOPOWER31 );
22174   testcase( r==TWOPOWER31-1 );
22175   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22176   r *= TWOPOWER32;
22177   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22178   *pA = r;
22179   return 0;
22180 }
22181
22182 /*
22183 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22184 ** if the integer has a value of -2147483648, return +2147483647
22185 */
22186 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22187   if( x>=0 ) return x;
22188   if( x==(int)0x80000000 ) return 0x7fffffff;
22189   return -x;
22190 }
22191
22192 #ifdef SQLITE_ENABLE_8_3_NAMES
22193 /*
22194 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22195 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22196 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22197 ** three characters, then shorten the suffix on z[] to be the last three
22198 ** characters of the original suffix.
22199 **
22200 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22201 ** do the suffix shortening regardless of URI parameter.
22202 **
22203 ** Examples:
22204 **
22205 **     test.db-journal    =>   test.nal
22206 **     test.db-wal        =>   test.wal
22207 **     test.db-shm        =>   test.shm
22208 **     test.db-mj7f3319fa =>   test.9fa
22209 */
22210 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22211 #if SQLITE_ENABLE_8_3_NAMES<2
22212   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22213 #endif
22214   {
22215     int i, sz;
22216     sz = sqlite3Strlen30(z);
22217     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22218     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22219   }
22220 }
22221 #endif
22222
22223 /************** End of util.c ************************************************/
22224 /************** Begin file hash.c ********************************************/
22225 /*
22226 ** 2001 September 22
22227 **
22228 ** The author disclaims copyright to this source code.  In place of
22229 ** a legal notice, here is a blessing:
22230 **
22231 **    May you do good and not evil.
22232 **    May you find forgiveness for yourself and forgive others.
22233 **    May you share freely, never taking more than you give.
22234 **
22235 *************************************************************************
22236 ** This is the implementation of generic hash-tables
22237 ** used in SQLite.
22238 */
22239 /* #include <assert.h> */
22240
22241 /* Turn bulk memory into a hash table object by initializing the
22242 ** fields of the Hash structure.
22243 **
22244 ** "pNew" is a pointer to the hash table that is to be initialized.
22245 */
22246 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22247   assert( pNew!=0 );
22248   pNew->first = 0;
22249   pNew->count = 0;
22250   pNew->htsize = 0;
22251   pNew->ht = 0;
22252 }
22253
22254 /* Remove all entries from a hash table.  Reclaim all memory.
22255 ** Call this routine to delete a hash table or to reset a hash table
22256 ** to the empty state.
22257 */
22258 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22259   HashElem *elem;         /* For looping over all elements of the table */
22260
22261   assert( pH!=0 );
22262   elem = pH->first;
22263   pH->first = 0;
22264   sqlite3_free(pH->ht);
22265   pH->ht = 0;
22266   pH->htsize = 0;
22267   while( elem ){
22268     HashElem *next_elem = elem->next;
22269     sqlite3_free(elem);
22270     elem = next_elem;
22271   }
22272   pH->count = 0;
22273 }
22274
22275 /*
22276 ** The hashing function.
22277 */
22278 static unsigned int strHash(const char *z, int nKey){
22279   int h = 0;
22280   assert( nKey>=0 );
22281   while( nKey > 0  ){
22282     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22283     nKey--;
22284   }
22285   return h;
22286 }
22287
22288
22289 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22290 ** insert pNew into the pEntry hash bucket.
22291 */
22292 static void insertElement(
22293   Hash *pH,              /* The complete hash table */
22294   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22295   HashElem *pNew         /* The element to be inserted */
22296 ){
22297   HashElem *pHead;       /* First element already in pEntry */
22298   if( pEntry ){
22299     pHead = pEntry->count ? pEntry->chain : 0;
22300     pEntry->count++;
22301     pEntry->chain = pNew;
22302   }else{
22303     pHead = 0;
22304   }
22305   if( pHead ){
22306     pNew->next = pHead;
22307     pNew->prev = pHead->prev;
22308     if( pHead->prev ){ pHead->prev->next = pNew; }
22309     else             { pH->first = pNew; }
22310     pHead->prev = pNew;
22311   }else{
22312     pNew->next = pH->first;
22313     if( pH->first ){ pH->first->prev = pNew; }
22314     pNew->prev = 0;
22315     pH->first = pNew;
22316   }
22317 }
22318
22319
22320 /* Resize the hash table so that it cantains "new_size" buckets.
22321 **
22322 ** The hash table might fail to resize if sqlite3_malloc() fails or
22323 ** if the new size is the same as the prior size.
22324 ** Return TRUE if the resize occurs and false if not.
22325 */
22326 static int rehash(Hash *pH, unsigned int new_size){
22327   struct _ht *new_ht;            /* The new hash table */
22328   HashElem *elem, *next_elem;    /* For looping over existing elements */
22329
22330 #if SQLITE_MALLOC_SOFT_LIMIT>0
22331   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22332     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22333   }
22334   if( new_size==pH->htsize ) return 0;
22335 #endif
22336
22337   /* The inability to allocates space for a larger hash table is
22338   ** a performance hit but it is not a fatal error.  So mark the
22339   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
22340   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22341   ** only zeroes the requested number of bytes whereas this module will
22342   ** use the actual amount of space allocated for the hash table (which
22343   ** may be larger than the requested amount).
22344   */
22345   sqlite3BeginBenignMalloc();
22346   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22347   sqlite3EndBenignMalloc();
22348
22349   if( new_ht==0 ) return 0;
22350   sqlite3_free(pH->ht);
22351   pH->ht = new_ht;
22352   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22353   memset(new_ht, 0, new_size*sizeof(struct _ht));
22354   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22355     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22356     next_elem = elem->next;
22357     insertElement(pH, &new_ht[h], elem);
22358   }
22359   return 1;
22360 }
22361
22362 /* This function (for internal use only) locates an element in an
22363 ** hash table that matches the given key.  The hash for this key has
22364 ** already been computed and is passed as the 4th parameter.
22365 */
22366 static HashElem *findElementGivenHash(
22367   const Hash *pH,     /* The pH to be searched */
22368   const char *pKey,   /* The key we are searching for */
22369   int nKey,           /* Bytes in key (not counting zero terminator) */
22370   unsigned int h      /* The hash for this key. */
22371 ){
22372   HashElem *elem;                /* Used to loop thru the element list */
22373   int count;                     /* Number of elements left to test */
22374
22375   if( pH->ht ){
22376     struct _ht *pEntry = &pH->ht[h];
22377     elem = pEntry->chain;
22378     count = pEntry->count;
22379   }else{
22380     elem = pH->first;
22381     count = pH->count;
22382   }
22383   while( count-- && ALWAYS(elem) ){
22384     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22385       return elem;
22386     }
22387     elem = elem->next;
22388   }
22389   return 0;
22390 }
22391
22392 /* Remove a single entry from the hash table given a pointer to that
22393 ** element and a hash on the element's key.
22394 */
22395 static void removeElementGivenHash(
22396   Hash *pH,         /* The pH containing "elem" */
22397   HashElem* elem,   /* The element to be removed from the pH */
22398   unsigned int h    /* Hash value for the element */
22399 ){
22400   struct _ht *pEntry;
22401   if( elem->prev ){
22402     elem->prev->next = elem->next; 
22403   }else{
22404     pH->first = elem->next;
22405   }
22406   if( elem->next ){
22407     elem->next->prev = elem->prev;
22408   }
22409   if( pH->ht ){
22410     pEntry = &pH->ht[h];
22411     if( pEntry->chain==elem ){
22412       pEntry->chain = elem->next;
22413     }
22414     pEntry->count--;
22415     assert( pEntry->count>=0 );
22416   }
22417   sqlite3_free( elem );
22418   pH->count--;
22419   if( pH->count==0 ){
22420     assert( pH->first==0 );
22421     assert( pH->count==0 );
22422     sqlite3HashClear(pH);
22423   }
22424 }
22425
22426 /* Attempt to locate an element of the hash table pH with a key
22427 ** that matches pKey,nKey.  Return the data for this element if it is
22428 ** found, or NULL if there is no match.
22429 */
22430 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22431   HashElem *elem;    /* The element that matches key */
22432   unsigned int h;    /* A hash on key */
22433
22434   assert( pH!=0 );
22435   assert( pKey!=0 );
22436   assert( nKey>=0 );
22437   if( pH->ht ){
22438     h = strHash(pKey, nKey) % pH->htsize;
22439   }else{
22440     h = 0;
22441   }
22442   elem = findElementGivenHash(pH, pKey, nKey, h);
22443   return elem ? elem->data : 0;
22444 }
22445
22446 /* Insert an element into the hash table pH.  The key is pKey,nKey
22447 ** and the data is "data".
22448 **
22449 ** If no element exists with a matching key, then a new
22450 ** element is created and NULL is returned.
22451 **
22452 ** If another element already exists with the same key, then the
22453 ** new data replaces the old data and the old data is returned.
22454 ** The key is not copied in this instance.  If a malloc fails, then
22455 ** the new data is returned and the hash table is unchanged.
22456 **
22457 ** If the "data" parameter to this function is NULL, then the
22458 ** element corresponding to "key" is removed from the hash table.
22459 */
22460 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22461   unsigned int h;       /* the hash of the key modulo hash table size */
22462   HashElem *elem;       /* Used to loop thru the element list */
22463   HashElem *new_elem;   /* New element added to the pH */
22464
22465   assert( pH!=0 );
22466   assert( pKey!=0 );
22467   assert( nKey>=0 );
22468   if( pH->htsize ){
22469     h = strHash(pKey, nKey) % pH->htsize;
22470   }else{
22471     h = 0;
22472   }
22473   elem = findElementGivenHash(pH,pKey,nKey,h);
22474   if( elem ){
22475     void *old_data = elem->data;
22476     if( data==0 ){
22477       removeElementGivenHash(pH,elem,h);
22478     }else{
22479       elem->data = data;
22480       elem->pKey = pKey;
22481       assert(nKey==elem->nKey);
22482     }
22483     return old_data;
22484   }
22485   if( data==0 ) return 0;
22486   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22487   if( new_elem==0 ) return data;
22488   new_elem->pKey = pKey;
22489   new_elem->nKey = nKey;
22490   new_elem->data = data;
22491   pH->count++;
22492   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22493     if( rehash(pH, pH->count*2) ){
22494       assert( pH->htsize>0 );
22495       h = strHash(pKey, nKey) % pH->htsize;
22496     }
22497   }
22498   if( pH->ht ){
22499     insertElement(pH, &pH->ht[h], new_elem);
22500   }else{
22501     insertElement(pH, 0, new_elem);
22502   }
22503   return 0;
22504 }
22505
22506 /************** End of hash.c ************************************************/
22507 /************** Begin file opcodes.c *****************************************/
22508 /* Automatically generated.  Do not edit */
22509 /* See the mkopcodec.awk script for details. */
22510 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22511 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22512  static const char *const azName[] = { "?",
22513      /*   1 */ "Goto",
22514      /*   2 */ "Gosub",
22515      /*   3 */ "Return",
22516      /*   4 */ "Yield",
22517      /*   5 */ "HaltIfNull",
22518      /*   6 */ "Halt",
22519      /*   7 */ "Integer",
22520      /*   8 */ "Int64",
22521      /*   9 */ "String",
22522      /*  10 */ "Null",
22523      /*  11 */ "Blob",
22524      /*  12 */ "Variable",
22525      /*  13 */ "Move",
22526      /*  14 */ "Copy",
22527      /*  15 */ "SCopy",
22528      /*  16 */ "ResultRow",
22529      /*  17 */ "CollSeq",
22530      /*  18 */ "Function",
22531      /*  19 */ "Not",
22532      /*  20 */ "AddImm",
22533      /*  21 */ "MustBeInt",
22534      /*  22 */ "RealAffinity",
22535      /*  23 */ "Permutation",
22536      /*  24 */ "Compare",
22537      /*  25 */ "Jump",
22538      /*  26 */ "Once",
22539      /*  27 */ "If",
22540      /*  28 */ "IfNot",
22541      /*  29 */ "Column",
22542      /*  30 */ "Affinity",
22543      /*  31 */ "MakeRecord",
22544      /*  32 */ "Count",
22545      /*  33 */ "Savepoint",
22546      /*  34 */ "AutoCommit",
22547      /*  35 */ "Transaction",
22548      /*  36 */ "ReadCookie",
22549      /*  37 */ "SetCookie",
22550      /*  38 */ "VerifyCookie",
22551      /*  39 */ "OpenRead",
22552      /*  40 */ "OpenWrite",
22553      /*  41 */ "OpenAutoindex",
22554      /*  42 */ "OpenEphemeral",
22555      /*  43 */ "SorterOpen",
22556      /*  44 */ "OpenPseudo",
22557      /*  45 */ "Close",
22558      /*  46 */ "SeekLt",
22559      /*  47 */ "SeekLe",
22560      /*  48 */ "SeekGe",
22561      /*  49 */ "SeekGt",
22562      /*  50 */ "Seek",
22563      /*  51 */ "NotFound",
22564      /*  52 */ "Found",
22565      /*  53 */ "IsUnique",
22566      /*  54 */ "NotExists",
22567      /*  55 */ "Sequence",
22568      /*  56 */ "NewRowid",
22569      /*  57 */ "Insert",
22570      /*  58 */ "InsertInt",
22571      /*  59 */ "Delete",
22572      /*  60 */ "ResetCount",
22573      /*  61 */ "SorterCompare",
22574      /*  62 */ "SorterData",
22575      /*  63 */ "RowKey",
22576      /*  64 */ "RowData",
22577      /*  65 */ "Rowid",
22578      /*  66 */ "NullRow",
22579      /*  67 */ "Last",
22580      /*  68 */ "Or",
22581      /*  69 */ "And",
22582      /*  70 */ "SorterSort",
22583      /*  71 */ "Sort",
22584      /*  72 */ "Rewind",
22585      /*  73 */ "IsNull",
22586      /*  74 */ "NotNull",
22587      /*  75 */ "Ne",
22588      /*  76 */ "Eq",
22589      /*  77 */ "Gt",
22590      /*  78 */ "Le",
22591      /*  79 */ "Lt",
22592      /*  80 */ "Ge",
22593      /*  81 */ "SorterNext",
22594      /*  82 */ "BitAnd",
22595      /*  83 */ "BitOr",
22596      /*  84 */ "ShiftLeft",
22597      /*  85 */ "ShiftRight",
22598      /*  86 */ "Add",
22599      /*  87 */ "Subtract",
22600      /*  88 */ "Multiply",
22601      /*  89 */ "Divide",
22602      /*  90 */ "Remainder",
22603      /*  91 */ "Concat",
22604      /*  92 */ "Prev",
22605      /*  93 */ "BitNot",
22606      /*  94 */ "String8",
22607      /*  95 */ "Next",
22608      /*  96 */ "SorterInsert",
22609      /*  97 */ "IdxInsert",
22610      /*  98 */ "IdxDelete",
22611      /*  99 */ "IdxRowid",
22612      /* 100 */ "IdxLT",
22613      /* 101 */ "IdxGE",
22614      /* 102 */ "Destroy",
22615      /* 103 */ "Clear",
22616      /* 104 */ "CreateIndex",
22617      /* 105 */ "CreateTable",
22618      /* 106 */ "ParseSchema",
22619      /* 107 */ "LoadAnalysis",
22620      /* 108 */ "DropTable",
22621      /* 109 */ "DropIndex",
22622      /* 110 */ "DropTrigger",
22623      /* 111 */ "IntegrityCk",
22624      /* 112 */ "RowSetAdd",
22625      /* 113 */ "RowSetRead",
22626      /* 114 */ "RowSetTest",
22627      /* 115 */ "Program",
22628      /* 116 */ "Param",
22629      /* 117 */ "FkCounter",
22630      /* 118 */ "FkIfZero",
22631      /* 119 */ "MemMax",
22632      /* 120 */ "IfPos",
22633      /* 121 */ "IfNeg",
22634      /* 122 */ "IfZero",
22635      /* 123 */ "AggStep",
22636      /* 124 */ "AggFinal",
22637      /* 125 */ "Checkpoint",
22638      /* 126 */ "JournalMode",
22639      /* 127 */ "Vacuum",
22640      /* 128 */ "IncrVacuum",
22641      /* 129 */ "Expire",
22642      /* 130 */ "Real",
22643      /* 131 */ "TableLock",
22644      /* 132 */ "VBegin",
22645      /* 133 */ "VCreate",
22646      /* 134 */ "VDestroy",
22647      /* 135 */ "VOpen",
22648      /* 136 */ "VFilter",
22649      /* 137 */ "VColumn",
22650      /* 138 */ "VNext",
22651      /* 139 */ "VRename",
22652      /* 140 */ "VUpdate",
22653      /* 141 */ "ToText",
22654      /* 142 */ "ToBlob",
22655      /* 143 */ "ToNumeric",
22656      /* 144 */ "ToInt",
22657      /* 145 */ "ToReal",
22658      /* 146 */ "Pagecount",
22659      /* 147 */ "MaxPgcnt",
22660      /* 148 */ "Trace",
22661      /* 149 */ "Noop",
22662      /* 150 */ "Explain",
22663   };
22664   return azName[i];
22665 }
22666 #endif
22667
22668 /************** End of opcodes.c *********************************************/
22669 /************** Begin file os_unix.c *****************************************/
22670 /*
22671 ** 2004 May 22
22672 **
22673 ** The author disclaims copyright to this source code.  In place of
22674 ** a legal notice, here is a blessing:
22675 **
22676 **    May you do good and not evil.
22677 **    May you find forgiveness for yourself and forgive others.
22678 **    May you share freely, never taking more than you give.
22679 **
22680 ******************************************************************************
22681 **
22682 ** This file contains the VFS implementation for unix-like operating systems
22683 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22684 **
22685 ** There are actually several different VFS implementations in this file.
22686 ** The differences are in the way that file locking is done.  The default
22687 ** implementation uses Posix Advisory Locks.  Alternative implementations
22688 ** use flock(), dot-files, various proprietary locking schemas, or simply
22689 ** skip locking all together.
22690 **
22691 ** This source file is organized into divisions where the logic for various
22692 ** subfunctions is contained within the appropriate division.  PLEASE
22693 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22694 ** in the correct division and should be clearly labeled.
22695 **
22696 ** The layout of divisions is as follows:
22697 **
22698 **   *  General-purpose declarations and utility functions.
22699 **   *  Unique file ID logic used by VxWorks.
22700 **   *  Various locking primitive implementations (all except proxy locking):
22701 **      + for Posix Advisory Locks
22702 **      + for no-op locks
22703 **      + for dot-file locks
22704 **      + for flock() locking
22705 **      + for named semaphore locks (VxWorks only)
22706 **      + for AFP filesystem locks (MacOSX only)
22707 **   *  sqlite3_file methods not associated with locking.
22708 **   *  Definitions of sqlite3_io_methods objects for all locking
22709 **      methods plus "finder" functions for each locking method.
22710 **   *  sqlite3_vfs method implementations.
22711 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22712 **   *  Definitions of sqlite3_vfs objects for all locking methods
22713 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22714 */
22715 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22716
22717 /* Use posix_fallocate() if it is available
22718 */
22719 #if !defined(HAVE_POSIX_FALLOCATE) \
22720       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22721 # define HAVE_POSIX_FALLOCATE 1
22722 #endif
22723
22724 #ifdef __UCLIBC__
22725   #undef HAVE_POSIX_FALLOCATE
22726 #endif
22727
22728 /*
22729 ** There are various methods for file locking used for concurrency
22730 ** control:
22731 **
22732 **   1. POSIX locking (the default),
22733 **   2. No locking,
22734 **   3. Dot-file locking,
22735 **   4. flock() locking,
22736 **   5. AFP locking (OSX only),
22737 **   6. Named POSIX semaphores (VXWorks only),
22738 **   7. proxy locking. (OSX only)
22739 **
22740 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22741 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22742 ** selection of the appropriate locking style based on the filesystem
22743 ** where the database is located.  
22744 */
22745 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22746 #  if defined(__APPLE__)
22747 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22748 #  else
22749 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22750 #  endif
22751 #endif
22752
22753 /*
22754 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22755 ** vxworks, or 0 otherwise.
22756 */
22757 #ifndef OS_VXWORKS
22758 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22759 #    define OS_VXWORKS 1
22760 #  else
22761 #    define OS_VXWORKS 0
22762 #  endif
22763 #endif
22764
22765 /*
22766 ** These #defines should enable >2GB file support on Posix if the
22767 ** underlying operating system supports it.  If the OS lacks
22768 ** large file support, these should be no-ops.
22769 **
22770 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22771 ** on the compiler command line.  This is necessary if you are compiling
22772 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22773 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22774 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22775 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22776 ** portability you should omit LFS.
22777 **
22778 ** The previous paragraph was written in 2005.  (This paragraph is written
22779 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22780 ** you should probably leave LFS enabled.  But some embedded platforms might
22781 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22782 */
22783 #ifndef SQLITE_DISABLE_LFS
22784 # define _LARGE_FILE       1
22785 # ifndef _FILE_OFFSET_BITS
22786 #   define _FILE_OFFSET_BITS 64
22787 # endif
22788 # define _LARGEFILE_SOURCE 1
22789 #endif
22790
22791 /*
22792 ** standard include files.
22793 */
22794 #include <sys/types.h>
22795 #include <sys/stat.h>
22796 #include <fcntl.h>
22797 #include <unistd.h>
22798 /* #include <time.h> */
22799 #include <sys/time.h>
22800 #include <errno.h>
22801 #ifndef SQLITE_OMIT_WAL
22802 #include <sys/mman.h>
22803 #endif
22804
22805
22806 #if SQLITE_ENABLE_LOCKING_STYLE
22807 # include <sys/ioctl.h>
22808 # if OS_VXWORKS
22809 #  include <semaphore.h>
22810 #  include <limits.h>
22811 # else
22812 #  include <sys/file.h>
22813 #  include <sys/param.h>
22814 # endif
22815 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22816
22817 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22818 # include <sys/mount.h>
22819 #endif
22820
22821 #ifdef HAVE_UTIME
22822 # include <utime.h>
22823 #endif
22824
22825 /*
22826 ** Allowed values of unixFile.fsFlags
22827 */
22828 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22829
22830 /*
22831 ** If we are to be thread-safe, include the pthreads header and define
22832 ** the SQLITE_UNIX_THREADS macro.
22833 */
22834 #if SQLITE_THREADSAFE
22835 /* # include <pthread.h> */
22836 # define SQLITE_UNIX_THREADS 1
22837 #endif
22838
22839 /*
22840 ** Default permissions when creating a new file
22841 */
22842 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22843 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22844 #endif
22845
22846 /*
22847 ** Default permissions when creating auto proxy dir
22848 */
22849 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22850 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22851 #endif
22852
22853 /*
22854 ** Maximum supported path-length.
22855 */
22856 #define MAX_PATHNAME 512
22857
22858 /*
22859 ** Only set the lastErrno if the error code is a real error and not 
22860 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22861 */
22862 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22863
22864 /* Forward references */
22865 typedef struct unixShm unixShm;               /* Connection shared memory */
22866 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22867 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22868 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22869
22870 /*
22871 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22872 ** cannot be closed immediately. In these cases, instances of the following
22873 ** structure are used to store the file descriptor while waiting for an
22874 ** opportunity to either close or reuse it.
22875 */
22876 struct UnixUnusedFd {
22877   int fd;                   /* File descriptor to close */
22878   int flags;                /* Flags this file descriptor was opened with */
22879   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22880 };
22881
22882 /*
22883 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22884 ** VFS implementations.
22885 */
22886 typedef struct unixFile unixFile;
22887 struct unixFile {
22888   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22889   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
22890   unixInodeInfo *pInode;              /* Info about locks on this inode */
22891   int h;                              /* The file descriptor */
22892   unsigned char eFileLock;            /* The type of lock held on this fd */
22893   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
22894   int lastErrno;                      /* The unix errno from last I/O error */
22895   void *lockingContext;               /* Locking style specific state */
22896   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22897   const char *zPath;                  /* Name of the file */
22898   unixShm *pShm;                      /* Shared memory segment information */
22899   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22900 #ifdef __QNXNTO__
22901   int sectorSize;                     /* Device sector size */
22902   int deviceCharacteristics;          /* Precomputed device characteristics */
22903 #endif
22904 #if SQLITE_ENABLE_LOCKING_STYLE
22905   int openFlags;                      /* The flags specified at open() */
22906 #endif
22907 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22908   unsigned fsFlags;                   /* cached details from statfs() */
22909 #endif
22910 #if OS_VXWORKS
22911   struct vxworksFileId *pId;          /* Unique file ID */
22912 #endif
22913 #ifdef SQLITE_DEBUG
22914   /* The next group of variables are used to track whether or not the
22915   ** transaction counter in bytes 24-27 of database files are updated
22916   ** whenever any part of the database changes.  An assertion fault will
22917   ** occur if a file is updated without also updating the transaction
22918   ** counter.  This test is made to avoid new problems similar to the
22919   ** one described by ticket #3584. 
22920   */
22921   unsigned char transCntrChng;   /* True if the transaction counter changed */
22922   unsigned char dbUpdate;        /* True if any part of database file changed */
22923   unsigned char inNormalWrite;   /* True if in a normal write operation */
22924 #endif
22925 #ifdef SQLITE_TEST
22926   /* In test mode, increase the size of this structure a bit so that 
22927   ** it is larger than the struct CrashFile defined in test6.c.
22928   */
22929   char aPadding[32];
22930 #endif
22931 };
22932
22933 /*
22934 ** Allowed values for the unixFile.ctrlFlags bitmask:
22935 */
22936 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
22937 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
22938 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
22939 #ifndef SQLITE_DISABLE_DIRSYNC
22940 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
22941 #else
22942 # define UNIXFILE_DIRSYNC    0x00
22943 #endif
22944 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
22945 #define UNIXFILE_DELETE      0x20     /* Delete on close */
22946 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
22947 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
22948
22949 /*
22950 ** Include code that is common to all os_*.c files
22951 */
22952 /************** Include os_common.h in the middle of os_unix.c ***************/
22953 /************** Begin file os_common.h ***************************************/
22954 /*
22955 ** 2004 May 22
22956 **
22957 ** The author disclaims copyright to this source code.  In place of
22958 ** a legal notice, here is a blessing:
22959 **
22960 **    May you do good and not evil.
22961 **    May you find forgiveness for yourself and forgive others.
22962 **    May you share freely, never taking more than you give.
22963 **
22964 ******************************************************************************
22965 **
22966 ** This file contains macros and a little bit of code that is common to
22967 ** all of the platform-specific files (os_*.c) and is #included into those
22968 ** files.
22969 **
22970 ** This file should be #included by the os_*.c files only.  It is not a
22971 ** general purpose header file.
22972 */
22973 #ifndef _OS_COMMON_H_
22974 #define _OS_COMMON_H_
22975
22976 /*
22977 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22978 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22979 ** switch.  The following code should catch this problem at compile-time.
22980 */
22981 #ifdef MEMORY_DEBUG
22982 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22983 #endif
22984
22985 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22986 # ifndef SQLITE_DEBUG_OS_TRACE
22987 #   define SQLITE_DEBUG_OS_TRACE 0
22988 # endif
22989   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22990 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22991 #else
22992 # define OSTRACE(X)
22993 #endif
22994
22995 /*
22996 ** Macros for performance tracing.  Normally turned off.  Only works
22997 ** on i486 hardware.
22998 */
22999 #ifdef SQLITE_PERFORMANCE_TRACE
23000
23001 /* 
23002 ** hwtime.h contains inline assembler code for implementing 
23003 ** high-performance timing routines.
23004 */
23005 /************** Include hwtime.h in the middle of os_common.h ****************/
23006 /************** Begin file hwtime.h ******************************************/
23007 /*
23008 ** 2008 May 27
23009 **
23010 ** The author disclaims copyright to this source code.  In place of
23011 ** a legal notice, here is a blessing:
23012 **
23013 **    May you do good and not evil.
23014 **    May you find forgiveness for yourself and forgive others.
23015 **    May you share freely, never taking more than you give.
23016 **
23017 ******************************************************************************
23018 **
23019 ** This file contains inline asm code for retrieving "high-performance"
23020 ** counters for x86 class CPUs.
23021 */
23022 #ifndef _HWTIME_H_
23023 #define _HWTIME_H_
23024
23025 /*
23026 ** The following routine only works on pentium-class (or newer) processors.
23027 ** It uses the RDTSC opcode to read the cycle count value out of the
23028 ** processor and returns that value.  This can be used for high-res
23029 ** profiling.
23030 */
23031 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23032       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23033
23034   #if defined(__GNUC__)
23035
23036   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23037      unsigned int lo, hi;
23038      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23039      return (sqlite_uint64)hi << 32 | lo;
23040   }
23041
23042   #elif defined(_MSC_VER)
23043
23044   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23045      __asm {
23046         rdtsc
23047         ret       ; return value at EDX:EAX
23048      }
23049   }
23050
23051   #endif
23052
23053 #elif (defined(__GNUC__) && defined(__x86_64__))
23054
23055   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23056       unsigned long val;
23057       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23058       return val;
23059   }
23060  
23061 #elif (defined(__GNUC__) && defined(__ppc__))
23062
23063   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23064       unsigned long long retval;
23065       unsigned long junk;
23066       __asm__ __volatile__ ("\n\
23067           1:      mftbu   %1\n\
23068                   mftb    %L0\n\
23069                   mftbu   %0\n\
23070                   cmpw    %0,%1\n\
23071                   bne     1b"
23072                   : "=r" (retval), "=r" (junk));
23073       return retval;
23074   }
23075
23076 #else
23077
23078   #error Need implementation of sqlite3Hwtime() for your platform.
23079
23080   /*
23081   ** To compile without implementing sqlite3Hwtime() for your platform,
23082   ** you can remove the above #error and use the following
23083   ** stub function.  You will lose timing support for many
23084   ** of the debugging and testing utilities, but it should at
23085   ** least compile and run.
23086   */
23087 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23088
23089 #endif
23090
23091 #endif /* !defined(_HWTIME_H_) */
23092
23093 /************** End of hwtime.h **********************************************/
23094 /************** Continuing where we left off in os_common.h ******************/
23095
23096 static sqlite_uint64 g_start;
23097 static sqlite_uint64 g_elapsed;
23098 #define TIMER_START       g_start=sqlite3Hwtime()
23099 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23100 #define TIMER_ELAPSED     g_elapsed
23101 #else
23102 #define TIMER_START
23103 #define TIMER_END
23104 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23105 #endif
23106
23107 /*
23108 ** If we compile with the SQLITE_TEST macro set, then the following block
23109 ** of code will give us the ability to simulate a disk I/O error.  This
23110 ** is used for testing the I/O recovery logic.
23111 */
23112 #ifdef SQLITE_TEST
23113 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23114 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23115 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23116 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23117 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23118 SQLITE_API int sqlite3_diskfull_pending = 0;
23119 SQLITE_API int sqlite3_diskfull = 0;
23120 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23121 #define SimulateIOError(CODE)  \
23122   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23123        || sqlite3_io_error_pending-- == 1 )  \
23124               { local_ioerr(); CODE; }
23125 static void local_ioerr(){
23126   IOTRACE(("IOERR\n"));
23127   sqlite3_io_error_hit++;
23128   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23129 }
23130 #define SimulateDiskfullError(CODE) \
23131    if( sqlite3_diskfull_pending ){ \
23132      if( sqlite3_diskfull_pending == 1 ){ \
23133        local_ioerr(); \
23134        sqlite3_diskfull = 1; \
23135        sqlite3_io_error_hit = 1; \
23136        CODE; \
23137      }else{ \
23138        sqlite3_diskfull_pending--; \
23139      } \
23140    }
23141 #else
23142 #define SimulateIOErrorBenign(X)
23143 #define SimulateIOError(A)
23144 #define SimulateDiskfullError(A)
23145 #endif
23146
23147 /*
23148 ** When testing, keep a count of the number of open files.
23149 */
23150 #ifdef SQLITE_TEST
23151 SQLITE_API int sqlite3_open_file_count = 0;
23152 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23153 #else
23154 #define OpenCounter(X)
23155 #endif
23156
23157 #endif /* !defined(_OS_COMMON_H_) */
23158
23159 /************** End of os_common.h *******************************************/
23160 /************** Continuing where we left off in os_unix.c ********************/
23161
23162 /*
23163 ** Define various macros that are missing from some systems.
23164 */
23165 #ifndef O_LARGEFILE
23166 # define O_LARGEFILE 0
23167 #endif
23168 #ifdef SQLITE_DISABLE_LFS
23169 # undef O_LARGEFILE
23170 # define O_LARGEFILE 0
23171 #endif
23172 #ifndef O_NOFOLLOW
23173 # define O_NOFOLLOW 0
23174 #endif
23175 #ifndef O_BINARY
23176 # define O_BINARY 0
23177 #endif
23178
23179 /*
23180 ** The threadid macro resolves to the thread-id or to 0.  Used for
23181 ** testing and debugging only.
23182 */
23183 #if SQLITE_THREADSAFE
23184 #define threadid pthread_self()
23185 #else
23186 #define threadid 0
23187 #endif
23188
23189 /*
23190 ** Different Unix systems declare open() in different ways.  Same use
23191 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23192 ** The difference is important when using a pointer to the function.
23193 **
23194 ** The safest way to deal with the problem is to always use this wrapper
23195 ** which always has the same well-defined interface.
23196 */
23197 static int posixOpen(const char *zFile, int flags, int mode){
23198   return open(zFile, flags, mode);
23199 }
23200
23201 /*
23202 ** On some systems, calls to fchown() will trigger a message in a security
23203 ** log if they come from non-root processes.  So avoid calling fchown() if
23204 ** we are not running as root.
23205 */
23206 static int posixFchown(int fd, uid_t uid, gid_t gid){
23207   return geteuid() ? 0 : fchown(fd,uid,gid);
23208 }
23209
23210 /* Forward reference */
23211 static int openDirectory(const char*, int*);
23212
23213 /*
23214 ** Many system calls are accessed through pointer-to-functions so that
23215 ** they may be overridden at runtime to facilitate fault injection during
23216 ** testing and sandboxing.  The following array holds the names and pointers
23217 ** to all overrideable system calls.
23218 */
23219 static struct unix_syscall {
23220   const char *zName;            /* Name of the sytem call */
23221   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23222   sqlite3_syscall_ptr pDefault; /* Default value */
23223 } aSyscall[] = {
23224   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23225 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23226
23227   { "close",        (sqlite3_syscall_ptr)close,      0  },
23228 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23229
23230   { "access",       (sqlite3_syscall_ptr)access,     0  },
23231 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23232
23233   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23234 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23235
23236   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23237 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23238
23239 /*
23240 ** The DJGPP compiler environment looks mostly like Unix, but it
23241 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23242 ** that always succeeds.  This means that locking does not occur under
23243 ** DJGPP.  But it is DOS - what did you expect?
23244 */
23245 #ifdef __DJGPP__
23246   { "fstat",        0,                 0  },
23247 #define osFstat(a,b,c)    0
23248 #else     
23249   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23250 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23251 #endif
23252
23253   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23254 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23255
23256   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23257 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23258
23259   { "read",         (sqlite3_syscall_ptr)read,       0  },
23260 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23261
23262 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23263   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23264 #else
23265   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23266 #endif
23267 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23268
23269 #if defined(USE_PREAD64)
23270   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23271 #else
23272   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23273 #endif
23274 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23275
23276   { "write",        (sqlite3_syscall_ptr)write,      0  },
23277 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23278
23279 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23280   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23281 #else
23282   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23283 #endif
23284 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23285                     aSyscall[12].pCurrent)
23286
23287 #if defined(USE_PREAD64)
23288   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23289 #else
23290   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23291 #endif
23292 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23293                     aSyscall[13].pCurrent)
23294
23295 #if SQLITE_ENABLE_LOCKING_STYLE
23296   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23297 #else
23298   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
23299 #endif
23300 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23301
23302 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23303   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23304 #else
23305   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23306 #endif
23307 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23308
23309   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23310 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23311
23312   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23313 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23314
23315   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23316 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23317
23318   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23319 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23320
23321   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23322 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23323
23324   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
23325 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
23326
23327 }; /* End of the overrideable system calls */
23328
23329 /*
23330 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23331 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23332 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23333 ** system call named zName.
23334 */
23335 static int unixSetSystemCall(
23336   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23337   const char *zName,            /* Name of system call to override */
23338   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23339 ){
23340   unsigned int i;
23341   int rc = SQLITE_NOTFOUND;
23342
23343   UNUSED_PARAMETER(pNotUsed);
23344   if( zName==0 ){
23345     /* If no zName is given, restore all system calls to their default
23346     ** settings and return NULL
23347     */
23348     rc = SQLITE_OK;
23349     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23350       if( aSyscall[i].pDefault ){
23351         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23352       }
23353     }
23354   }else{
23355     /* If zName is specified, operate on only the one system call
23356     ** specified.
23357     */
23358     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23359       if( strcmp(zName, aSyscall[i].zName)==0 ){
23360         if( aSyscall[i].pDefault==0 ){
23361           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23362         }
23363         rc = SQLITE_OK;
23364         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23365         aSyscall[i].pCurrent = pNewFunc;
23366         break;
23367       }
23368     }
23369   }
23370   return rc;
23371 }
23372
23373 /*
23374 ** Return the value of a system call.  Return NULL if zName is not a
23375 ** recognized system call name.  NULL is also returned if the system call
23376 ** is currently undefined.
23377 */
23378 static sqlite3_syscall_ptr unixGetSystemCall(
23379   sqlite3_vfs *pNotUsed,
23380   const char *zName
23381 ){
23382   unsigned int i;
23383
23384   UNUSED_PARAMETER(pNotUsed);
23385   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23386     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23387   }
23388   return 0;
23389 }
23390
23391 /*
23392 ** Return the name of the first system call after zName.  If zName==NULL
23393 ** then return the name of the first system call.  Return NULL if zName
23394 ** is the last system call or if zName is not the name of a valid
23395 ** system call.
23396 */
23397 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23398   int i = -1;
23399
23400   UNUSED_PARAMETER(p);
23401   if( zName ){
23402     for(i=0; i<ArraySize(aSyscall)-1; i++){
23403       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23404     }
23405   }
23406   for(i++; i<ArraySize(aSyscall); i++){
23407     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23408   }
23409   return 0;
23410 }
23411
23412 /*
23413 ** Invoke open().  Do so multiple times, until it either succeeds or
23414 ** fails for some reason other than EINTR.
23415 **
23416 ** If the file creation mode "m" is 0 then set it to the default for
23417 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23418 ** 0644) as modified by the system umask.  If m is not 0, then
23419 ** make the file creation mode be exactly m ignoring the umask.
23420 **
23421 ** The m parameter will be non-zero only when creating -wal, -journal,
23422 ** and -shm files.  We want those files to have *exactly* the same
23423 ** permissions as their original database, unadulterated by the umask.
23424 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23425 ** transaction crashes and leaves behind hot journals, then any
23426 ** process that is able to write to the database will also be able to
23427 ** recover the hot journals.
23428 */
23429 static int robust_open(const char *z, int f, mode_t m){
23430   int fd;
23431   mode_t m2;
23432   mode_t origM = 0;
23433   if( m==0 ){
23434     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
23435   }else{
23436     m2 = m;
23437     origM = osUmask(0);
23438   }
23439   do{
23440 #if defined(O_CLOEXEC)
23441     fd = osOpen(z,f|O_CLOEXEC,m2);
23442 #else
23443     fd = osOpen(z,f,m2);
23444 #endif
23445   }while( fd<0 && errno==EINTR );
23446   if( m ){
23447     osUmask(origM);
23448   }
23449 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23450   if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23451 #endif
23452   return fd;
23453 }
23454
23455 /*
23456 ** Helper functions to obtain and relinquish the global mutex. The
23457 ** global mutex is used to protect the unixInodeInfo and
23458 ** vxworksFileId objects used by this file, all of which may be 
23459 ** shared by multiple threads.
23460 **
23461 ** Function unixMutexHeld() is used to assert() that the global mutex 
23462 ** is held when required. This function is only used as part of assert() 
23463 ** statements. e.g.
23464 **
23465 **   unixEnterMutex()
23466 **     assert( unixMutexHeld() );
23467 **   unixEnterLeave()
23468 */
23469 static void unixEnterMutex(void){
23470   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23471 }
23472 static void unixLeaveMutex(void){
23473   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23474 }
23475 #ifdef SQLITE_DEBUG
23476 static int unixMutexHeld(void) {
23477   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23478 }
23479 #endif
23480
23481
23482 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23483 /*
23484 ** Helper function for printing out trace information from debugging
23485 ** binaries. This returns the string represetation of the supplied
23486 ** integer lock-type.
23487 */
23488 static const char *azFileLock(int eFileLock){
23489   switch( eFileLock ){
23490     case NO_LOCK: return "NONE";
23491     case SHARED_LOCK: return "SHARED";
23492     case RESERVED_LOCK: return "RESERVED";
23493     case PENDING_LOCK: return "PENDING";
23494     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23495   }
23496   return "ERROR";
23497 }
23498 #endif
23499
23500 #ifdef SQLITE_LOCK_TRACE
23501 /*
23502 ** Print out information about all locking operations.
23503 **
23504 ** This routine is used for troubleshooting locks on multithreaded
23505 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23506 ** command-line option on the compiler.  This code is normally
23507 ** turned off.
23508 */
23509 static int lockTrace(int fd, int op, struct flock *p){
23510   char *zOpName, *zType;
23511   int s;
23512   int savedErrno;
23513   if( op==F_GETLK ){
23514     zOpName = "GETLK";
23515   }else if( op==F_SETLK ){
23516     zOpName = "SETLK";
23517   }else{
23518     s = osFcntl(fd, op, p);
23519     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23520     return s;
23521   }
23522   if( p->l_type==F_RDLCK ){
23523     zType = "RDLCK";
23524   }else if( p->l_type==F_WRLCK ){
23525     zType = "WRLCK";
23526   }else if( p->l_type==F_UNLCK ){
23527     zType = "UNLCK";
23528   }else{
23529     assert( 0 );
23530   }
23531   assert( p->l_whence==SEEK_SET );
23532   s = osFcntl(fd, op, p);
23533   savedErrno = errno;
23534   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23535      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23536      (int)p->l_pid, s);
23537   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23538     struct flock l2;
23539     l2 = *p;
23540     osFcntl(fd, F_GETLK, &l2);
23541     if( l2.l_type==F_RDLCK ){
23542       zType = "RDLCK";
23543     }else if( l2.l_type==F_WRLCK ){
23544       zType = "WRLCK";
23545     }else if( l2.l_type==F_UNLCK ){
23546       zType = "UNLCK";
23547     }else{
23548       assert( 0 );
23549     }
23550     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23551        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23552   }
23553   errno = savedErrno;
23554   return s;
23555 }
23556 #undef osFcntl
23557 #define osFcntl lockTrace
23558 #endif /* SQLITE_LOCK_TRACE */
23559
23560 /*
23561 ** Retry ftruncate() calls that fail due to EINTR
23562 */
23563 static int robust_ftruncate(int h, sqlite3_int64 sz){
23564   int rc;
23565   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23566   return rc;
23567 }
23568
23569 /*
23570 ** This routine translates a standard POSIX errno code into something
23571 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23572 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23573 ** and a variety of "please close the file descriptor NOW" errors into 
23574 ** SQLITE_IOERR
23575 ** 
23576 ** Errors during initialization of locks, or file system support for locks,
23577 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23578 */
23579 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23580   switch (posixError) {
23581 #if 0
23582   /* At one point this code was not commented out. In theory, this branch
23583   ** should never be hit, as this function should only be called after
23584   ** a locking-related function (i.e. fcntl()) has returned non-zero with
23585   ** the value of errno as the first argument. Since a system call has failed,
23586   ** errno should be non-zero.
23587   **
23588   ** Despite this, if errno really is zero, we still don't want to return
23589   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23590   ** propagated back to the caller. Commenting this branch out means errno==0
23591   ** will be handled by the "default:" case below.
23592   */
23593   case 0: 
23594     return SQLITE_OK;
23595 #endif
23596
23597   case EAGAIN:
23598   case ETIMEDOUT:
23599   case EBUSY:
23600   case EINTR:
23601   case ENOLCK:  
23602     /* random NFS retry error, unless during file system support 
23603      * introspection, in which it actually means what it says */
23604     return SQLITE_BUSY;
23605     
23606   case EACCES: 
23607     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23608     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23609         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23610         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23611         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23612       return SQLITE_BUSY;
23613     }
23614     /* else fall through */
23615   case EPERM: 
23616     return SQLITE_PERM;
23617     
23618   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23619   ** this module never makes such a call. And the code in SQLite itself 
23620   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23621   ** this case is also commented out. If the system does set errno to EDEADLK,
23622   ** the default SQLITE_IOERR_XXX code will be returned. */
23623 #if 0
23624   case EDEADLK:
23625     return SQLITE_IOERR_BLOCKED;
23626 #endif
23627     
23628 #if EOPNOTSUPP!=ENOTSUP
23629   case EOPNOTSUPP: 
23630     /* something went terribly awry, unless during file system support 
23631      * introspection, in which it actually means what it says */
23632 #endif
23633 #ifdef ENOTSUP
23634   case ENOTSUP: 
23635     /* invalid fd, unless during file system support introspection, in which 
23636      * it actually means what it says */
23637 #endif
23638   case EIO:
23639   case EBADF:
23640   case EINVAL:
23641   case ENOTCONN:
23642   case ENODEV:
23643   case ENXIO:
23644   case ENOENT:
23645 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23646   case ESTALE:
23647 #endif
23648   case ENOSYS:
23649     /* these should force the client to close the file and reconnect */
23650     
23651   default: 
23652     return sqliteIOErr;
23653   }
23654 }
23655
23656
23657
23658 /******************************************************************************
23659 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23660 **
23661 ** On most versions of unix, we can get a unique ID for a file by concatenating
23662 ** the device number and the inode number.  But this does not work on VxWorks.
23663 ** On VxWorks, a unique file id must be based on the canonical filename.
23664 **
23665 ** A pointer to an instance of the following structure can be used as a
23666 ** unique file ID in VxWorks.  Each instance of this structure contains
23667 ** a copy of the canonical filename.  There is also a reference count.  
23668 ** The structure is reclaimed when the number of pointers to it drops to
23669 ** zero.
23670 **
23671 ** There are never very many files open at one time and lookups are not
23672 ** a performance-critical path, so it is sufficient to put these
23673 ** structures on a linked list.
23674 */
23675 struct vxworksFileId {
23676   struct vxworksFileId *pNext;  /* Next in a list of them all */
23677   int nRef;                     /* Number of references to this one */
23678   int nName;                    /* Length of the zCanonicalName[] string */
23679   char *zCanonicalName;         /* Canonical filename */
23680 };
23681
23682 #if OS_VXWORKS
23683 /* 
23684 ** All unique filenames are held on a linked list headed by this
23685 ** variable:
23686 */
23687 static struct vxworksFileId *vxworksFileList = 0;
23688
23689 /*
23690 ** Simplify a filename into its canonical form
23691 ** by making the following changes:
23692 **
23693 **  * removing any trailing and duplicate /
23694 **  * convert /./ into just /
23695 **  * convert /A/../ where A is any simple name into just /
23696 **
23697 ** Changes are made in-place.  Return the new name length.
23698 **
23699 ** The original filename is in z[0..n-1].  Return the number of
23700 ** characters in the simplified name.
23701 */
23702 static int vxworksSimplifyName(char *z, int n){
23703   int i, j;
23704   while( n>1 && z[n-1]=='/' ){ n--; }
23705   for(i=j=0; i<n; i++){
23706     if( z[i]=='/' ){
23707       if( z[i+1]=='/' ) continue;
23708       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23709         i += 1;
23710         continue;
23711       }
23712       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23713         while( j>0 && z[j-1]!='/' ){ j--; }
23714         if( j>0 ){ j--; }
23715         i += 2;
23716         continue;
23717       }
23718     }
23719     z[j++] = z[i];
23720   }
23721   z[j] = 0;
23722   return j;
23723 }
23724
23725 /*
23726 ** Find a unique file ID for the given absolute pathname.  Return
23727 ** a pointer to the vxworksFileId object.  This pointer is the unique
23728 ** file ID.
23729 **
23730 ** The nRef field of the vxworksFileId object is incremented before
23731 ** the object is returned.  A new vxworksFileId object is created
23732 ** and added to the global list if necessary.
23733 **
23734 ** If a memory allocation error occurs, return NULL.
23735 */
23736 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23737   struct vxworksFileId *pNew;         /* search key and new file ID */
23738   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23739   int n;                              /* Length of zAbsoluteName string */
23740
23741   assert( zAbsoluteName[0]=='/' );
23742   n = (int)strlen(zAbsoluteName);
23743   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23744   if( pNew==0 ) return 0;
23745   pNew->zCanonicalName = (char*)&pNew[1];
23746   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23747   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23748
23749   /* Search for an existing entry that matching the canonical name.
23750   ** If found, increment the reference count and return a pointer to
23751   ** the existing file ID.
23752   */
23753   unixEnterMutex();
23754   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23755     if( pCandidate->nName==n 
23756      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23757     ){
23758        sqlite3_free(pNew);
23759        pCandidate->nRef++;
23760        unixLeaveMutex();
23761        return pCandidate;
23762     }
23763   }
23764
23765   /* No match was found.  We will make a new file ID */
23766   pNew->nRef = 1;
23767   pNew->nName = n;
23768   pNew->pNext = vxworksFileList;
23769   vxworksFileList = pNew;
23770   unixLeaveMutex();
23771   return pNew;
23772 }
23773
23774 /*
23775 ** Decrement the reference count on a vxworksFileId object.  Free
23776 ** the object when the reference count reaches zero.
23777 */
23778 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23779   unixEnterMutex();
23780   assert( pId->nRef>0 );
23781   pId->nRef--;
23782   if( pId->nRef==0 ){
23783     struct vxworksFileId **pp;
23784     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23785     assert( *pp==pId );
23786     *pp = pId->pNext;
23787     sqlite3_free(pId);
23788   }
23789   unixLeaveMutex();
23790 }
23791 #endif /* OS_VXWORKS */
23792 /*************** End of Unique File ID Utility Used By VxWorks ****************
23793 ******************************************************************************/
23794
23795
23796 /******************************************************************************
23797 *************************** Posix Advisory Locking ****************************
23798 **
23799 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23800 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23801 ** sets or clears a lock, that operation overrides any prior locks set
23802 ** by the same process.  It does not explicitly say so, but this implies
23803 ** that it overrides locks set by the same process using a different
23804 ** file descriptor.  Consider this test case:
23805 **
23806 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23807 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23808 **
23809 ** Suppose ./file1 and ./file2 are really the same file (because
23810 ** one is a hard or symbolic link to the other) then if you set
23811 ** an exclusive lock on fd1, then try to get an exclusive lock
23812 ** on fd2, it works.  I would have expected the second lock to
23813 ** fail since there was already a lock on the file due to fd1.
23814 ** But not so.  Since both locks came from the same process, the
23815 ** second overrides the first, even though they were on different
23816 ** file descriptors opened on different file names.
23817 **
23818 ** This means that we cannot use POSIX locks to synchronize file access
23819 ** among competing threads of the same process.  POSIX locks will work fine
23820 ** to synchronize access for threads in separate processes, but not
23821 ** threads within the same process.
23822 **
23823 ** To work around the problem, SQLite has to manage file locks internally
23824 ** on its own.  Whenever a new database is opened, we have to find the
23825 ** specific inode of the database file (the inode is determined by the
23826 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23827 ** and check for locks already existing on that inode.  When locks are
23828 ** created or removed, we have to look at our own internal record of the
23829 ** locks to see if another thread has previously set a lock on that same
23830 ** inode.
23831 **
23832 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23833 ** For VxWorks, we have to use the alternative unique ID system based on
23834 ** canonical filename and implemented in the previous division.)
23835 **
23836 ** The sqlite3_file structure for POSIX is no longer just an integer file
23837 ** descriptor.  It is now a structure that holds the integer file
23838 ** descriptor and a pointer to a structure that describes the internal
23839 ** locks on the corresponding inode.  There is one locking structure
23840 ** per inode, so if the same inode is opened twice, both unixFile structures
23841 ** point to the same locking structure.  The locking structure keeps
23842 ** a reference count (so we will know when to delete it) and a "cnt"
23843 ** field that tells us its internal lock status.  cnt==0 means the
23844 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23845 ** cnt>0 means there are cnt shared locks on the file.
23846 **
23847 ** Any attempt to lock or unlock a file first checks the locking
23848 ** structure.  The fcntl() system call is only invoked to set a 
23849 ** POSIX lock if the internal lock structure transitions between
23850 ** a locked and an unlocked state.
23851 **
23852 ** But wait:  there are yet more problems with POSIX advisory locks.
23853 **
23854 ** If you close a file descriptor that points to a file that has locks,
23855 ** all locks on that file that are owned by the current process are
23856 ** released.  To work around this problem, each unixInodeInfo object
23857 ** maintains a count of the number of pending locks on tha inode.
23858 ** When an attempt is made to close an unixFile, if there are
23859 ** other unixFile open on the same inode that are holding locks, the call
23860 ** to close() the file descriptor is deferred until all of the locks clear.
23861 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23862 ** be closed and that list is walked (and cleared) when the last lock
23863 ** clears.
23864 **
23865 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23866 **
23867 ** Many older versions of linux use the LinuxThreads library which is
23868 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23869 ** A cannot be modified or overridden by a different thread B.
23870 ** Only thread A can modify the lock.  Locking behavior is correct
23871 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23872 ** on linux - with NPTL a lock created by thread A can override locks
23873 ** in thread B.  But there is no way to know at compile-time which
23874 ** threading library is being used.  So there is no way to know at
23875 ** compile-time whether or not thread A can override locks on thread B.
23876 ** One has to do a run-time check to discover the behavior of the
23877 ** current process.
23878 **
23879 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23880 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23881 ** LinuxThreads provided that (1) there is no more than one connection 
23882 ** per database file in the same process and (2) database connections
23883 ** do not move across threads.
23884 */
23885
23886 /*
23887 ** An instance of the following structure serves as the key used
23888 ** to locate a particular unixInodeInfo object.
23889 */
23890 struct unixFileId {
23891   dev_t dev;                  /* Device number */
23892 #if OS_VXWORKS
23893   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23894 #else
23895   ino_t ino;                  /* Inode number */
23896 #endif
23897 };
23898
23899 /*
23900 ** An instance of the following structure is allocated for each open
23901 ** inode.  Or, on LinuxThreads, there is one of these structures for
23902 ** each inode opened by each thread.
23903 **
23904 ** A single inode can have multiple file descriptors, so each unixFile
23905 ** structure contains a pointer to an instance of this object and this
23906 ** object keeps a count of the number of unixFile pointing to it.
23907 */
23908 struct unixInodeInfo {
23909   struct unixFileId fileId;       /* The lookup key */
23910   int nShared;                    /* Number of SHARED locks held */
23911   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23912   unsigned char bProcessLock;     /* An exclusive process lock is held */
23913   int nRef;                       /* Number of pointers to this structure */
23914   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23915   int nLock;                      /* Number of outstanding file locks */
23916   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23917   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23918   unixInodeInfo *pPrev;           /*    .... doubly linked */
23919 #if SQLITE_ENABLE_LOCKING_STYLE
23920   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23921 #endif
23922 #if OS_VXWORKS
23923   sem_t *pSem;                    /* Named POSIX semaphore */
23924   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23925 #endif
23926 };
23927
23928 /*
23929 ** A lists of all unixInodeInfo objects.
23930 */
23931 static unixInodeInfo *inodeList = 0;
23932
23933 /*
23934 **
23935 ** This function - unixLogError_x(), is only ever called via the macro
23936 ** unixLogError().
23937 **
23938 ** It is invoked after an error occurs in an OS function and errno has been
23939 ** set. It logs a message using sqlite3_log() containing the current value of
23940 ** errno and, if possible, the human-readable equivalent from strerror() or
23941 ** strerror_r().
23942 **
23943 ** The first argument passed to the macro should be the error code that
23944 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
23945 ** The two subsequent arguments should be the name of the OS function that
23946 ** failed (e.g. "unlink", "open") and the associated file-system path,
23947 ** if any.
23948 */
23949 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
23950 static int unixLogErrorAtLine(
23951   int errcode,                    /* SQLite error code */
23952   const char *zFunc,              /* Name of OS function that failed */
23953   const char *zPath,              /* File path associated with error */
23954   int iLine                       /* Source line number where error occurred */
23955 ){
23956   char *zErr;                     /* Message from strerror() or equivalent */
23957   int iErrno = errno;             /* Saved syscall error number */
23958
23959   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
23960   ** the strerror() function to obtain the human-readable error message
23961   ** equivalent to errno. Otherwise, use strerror_r().
23962   */ 
23963 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
23964   char aErr[80];
23965   memset(aErr, 0, sizeof(aErr));
23966   zErr = aErr;
23967
23968   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
23969   ** assume that the system provides the GNU version of strerror_r() that
23970   ** returns a pointer to a buffer containing the error message. That pointer 
23971   ** may point to aErr[], or it may point to some static storage somewhere. 
23972   ** Otherwise, assume that the system provides the POSIX version of 
23973   ** strerror_r(), which always writes an error message into aErr[].
23974   **
23975   ** If the code incorrectly assumes that it is the POSIX version that is
23976   ** available, the error message will often be an empty string. Not a
23977   ** huge problem. Incorrectly concluding that the GNU version is available 
23978   ** could lead to a segfault though.
23979   */
23980 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
23981   zErr = 
23982 # endif
23983   strerror_r(iErrno, aErr, sizeof(aErr)-1);
23984
23985 #elif SQLITE_THREADSAFE
23986   /* This is a threadsafe build, but strerror_r() is not available. */
23987   zErr = "";
23988 #else
23989   /* Non-threadsafe build, use strerror(). */
23990   zErr = strerror(iErrno);
23991 #endif
23992
23993   assert( errcode!=SQLITE_OK );
23994   if( zPath==0 ) zPath = "";
23995   sqlite3_log(errcode,
23996       "os_unix.c:%d: (%d) %s(%s) - %s",
23997       iLine, iErrno, zFunc, zPath, zErr
23998   );
23999
24000   return errcode;
24001 }
24002
24003 /*
24004 ** Close a file descriptor.
24005 **
24006 ** We assume that close() almost always works, since it is only in a
24007 ** very sick application or on a very sick platform that it might fail.
24008 ** If it does fail, simply leak the file descriptor, but do log the
24009 ** error.
24010 **
24011 ** Note that it is not safe to retry close() after EINTR since the
24012 ** file descriptor might have already been reused by another thread.
24013 ** So we don't even try to recover from an EINTR.  Just log the error
24014 ** and move on.
24015 */
24016 static void robust_close(unixFile *pFile, int h, int lineno){
24017   if( osClose(h) ){
24018     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24019                        pFile ? pFile->zPath : 0, lineno);
24020   }
24021 }
24022
24023 /*
24024 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24025 */ 
24026 static void closePendingFds(unixFile *pFile){
24027   unixInodeInfo *pInode = pFile->pInode;
24028   UnixUnusedFd *p;
24029   UnixUnusedFd *pNext;
24030   for(p=pInode->pUnused; p; p=pNext){
24031     pNext = p->pNext;
24032     robust_close(pFile, p->fd, __LINE__);
24033     sqlite3_free(p);
24034   }
24035   pInode->pUnused = 0;
24036 }
24037
24038 /*
24039 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24040 **
24041 ** The mutex entered using the unixEnterMutex() function must be held
24042 ** when this function is called.
24043 */
24044 static void releaseInodeInfo(unixFile *pFile){
24045   unixInodeInfo *pInode = pFile->pInode;
24046   assert( unixMutexHeld() );
24047   if( ALWAYS(pInode) ){
24048     pInode->nRef--;
24049     if( pInode->nRef==0 ){
24050       assert( pInode->pShmNode==0 );
24051       closePendingFds(pFile);
24052       if( pInode->pPrev ){
24053         assert( pInode->pPrev->pNext==pInode );
24054         pInode->pPrev->pNext = pInode->pNext;
24055       }else{
24056         assert( inodeList==pInode );
24057         inodeList = pInode->pNext;
24058       }
24059       if( pInode->pNext ){
24060         assert( pInode->pNext->pPrev==pInode );
24061         pInode->pNext->pPrev = pInode->pPrev;
24062       }
24063       sqlite3_free(pInode);
24064     }
24065   }
24066 }
24067
24068 /*
24069 ** Given a file descriptor, locate the unixInodeInfo object that
24070 ** describes that file descriptor.  Create a new one if necessary.  The
24071 ** return value might be uninitialized if an error occurs.
24072 **
24073 ** The mutex entered using the unixEnterMutex() function must be held
24074 ** when this function is called.
24075 **
24076 ** Return an appropriate error code.
24077 */
24078 static int findInodeInfo(
24079   unixFile *pFile,               /* Unix file with file desc used in the key */
24080   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24081 ){
24082   int rc;                        /* System call return code */
24083   int fd;                        /* The file descriptor for pFile */
24084   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24085   struct stat statbuf;           /* Low-level file information */
24086   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24087
24088   assert( unixMutexHeld() );
24089
24090   /* Get low-level information about the file that we can used to
24091   ** create a unique name for the file.
24092   */
24093   fd = pFile->h;
24094   rc = osFstat(fd, &statbuf);
24095   if( rc!=0 ){
24096     pFile->lastErrno = errno;
24097 #ifdef EOVERFLOW
24098     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24099 #endif
24100     return SQLITE_IOERR;
24101   }
24102
24103 #ifdef __APPLE__
24104   /* On OS X on an msdos filesystem, the inode number is reported
24105   ** incorrectly for zero-size files.  See ticket #3260.  To work
24106   ** around this problem (we consider it a bug in OS X, not SQLite)
24107   ** we always increase the file size to 1 by writing a single byte
24108   ** prior to accessing the inode number.  The one byte written is
24109   ** an ASCII 'S' character which also happens to be the first byte
24110   ** in the header of every SQLite database.  In this way, if there
24111   ** is a race condition such that another thread has already populated
24112   ** the first page of the database, no damage is done.
24113   */
24114   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24115     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24116     if( rc!=1 ){
24117       pFile->lastErrno = errno;
24118       return SQLITE_IOERR;
24119     }
24120     rc = osFstat(fd, &statbuf);
24121     if( rc!=0 ){
24122       pFile->lastErrno = errno;
24123       return SQLITE_IOERR;
24124     }
24125   }
24126 #endif
24127
24128   memset(&fileId, 0, sizeof(fileId));
24129   fileId.dev = statbuf.st_dev;
24130 #if OS_VXWORKS
24131   fileId.pId = pFile->pId;
24132 #else
24133   fileId.ino = statbuf.st_ino;
24134 #endif
24135   pInode = inodeList;
24136   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24137     pInode = pInode->pNext;
24138   }
24139   if( pInode==0 ){
24140     pInode = sqlite3_malloc( sizeof(*pInode) );
24141     if( pInode==0 ){
24142       return SQLITE_NOMEM;
24143     }
24144     memset(pInode, 0, sizeof(*pInode));
24145     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24146     pInode->nRef = 1;
24147     pInode->pNext = inodeList;
24148     pInode->pPrev = 0;
24149     if( inodeList ) inodeList->pPrev = pInode;
24150     inodeList = pInode;
24151   }else{
24152     pInode->nRef++;
24153   }
24154   *ppInode = pInode;
24155   return SQLITE_OK;
24156 }
24157
24158
24159 /*
24160 ** This routine checks if there is a RESERVED lock held on the specified
24161 ** file by this or any other process. If such a lock is held, set *pResOut
24162 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24163 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24164 */
24165 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24166   int rc = SQLITE_OK;
24167   int reserved = 0;
24168   unixFile *pFile = (unixFile*)id;
24169
24170   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24171
24172   assert( pFile );
24173   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24174
24175   /* Check if a thread in this process holds such a lock */
24176   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24177     reserved = 1;
24178   }
24179
24180   /* Otherwise see if some other process holds it.
24181   */
24182 #ifndef __DJGPP__
24183   if( !reserved && !pFile->pInode->bProcessLock ){
24184     struct flock lock;
24185     lock.l_whence = SEEK_SET;
24186     lock.l_start = RESERVED_BYTE;
24187     lock.l_len = 1;
24188     lock.l_type = F_WRLCK;
24189     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24190       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24191       pFile->lastErrno = errno;
24192     } else if( lock.l_type!=F_UNLCK ){
24193       reserved = 1;
24194     }
24195   }
24196 #endif
24197   
24198   unixLeaveMutex();
24199   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24200
24201   *pResOut = reserved;
24202   return rc;
24203 }
24204
24205 /*
24206 ** Attempt to set a system-lock on the file pFile.  The lock is 
24207 ** described by pLock.
24208 **
24209 ** If the pFile was opened read/write from unix-excl, then the only lock
24210 ** ever obtained is an exclusive lock, and it is obtained exactly once
24211 ** the first time any lock is attempted.  All subsequent system locking
24212 ** operations become no-ops.  Locking operations still happen internally,
24213 ** in order to coordinate access between separate database connections
24214 ** within this process, but all of that is handled in memory and the
24215 ** operating system does not participate.
24216 **
24217 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24218 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24219 ** and is read-only.
24220 **
24221 ** Zero is returned if the call completes successfully, or -1 if a call
24222 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24223 */
24224 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24225   int rc;
24226   unixInodeInfo *pInode = pFile->pInode;
24227   assert( unixMutexHeld() );
24228   assert( pInode!=0 );
24229   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24230    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24231   ){
24232     if( pInode->bProcessLock==0 ){
24233       struct flock lock;
24234       assert( pInode->nLock==0 );
24235       lock.l_whence = SEEK_SET;
24236       lock.l_start = SHARED_FIRST;
24237       lock.l_len = SHARED_SIZE;
24238       lock.l_type = F_WRLCK;
24239       rc = osFcntl(pFile->h, F_SETLK, &lock);
24240       if( rc<0 ) return rc;
24241       pInode->bProcessLock = 1;
24242       pInode->nLock++;
24243     }else{
24244       rc = 0;
24245     }
24246   }else{
24247     rc = osFcntl(pFile->h, F_SETLK, pLock);
24248   }
24249   return rc;
24250 }
24251
24252 /*
24253 ** Lock the file with the lock specified by parameter eFileLock - one
24254 ** of the following:
24255 **
24256 **     (1) SHARED_LOCK
24257 **     (2) RESERVED_LOCK
24258 **     (3) PENDING_LOCK
24259 **     (4) EXCLUSIVE_LOCK
24260 **
24261 ** Sometimes when requesting one lock state, additional lock states
24262 ** are inserted in between.  The locking might fail on one of the later
24263 ** transitions leaving the lock state different from what it started but
24264 ** still short of its goal.  The following chart shows the allowed
24265 ** transitions and the inserted intermediate states:
24266 **
24267 **    UNLOCKED -> SHARED
24268 **    SHARED -> RESERVED
24269 **    SHARED -> (PENDING) -> EXCLUSIVE
24270 **    RESERVED -> (PENDING) -> EXCLUSIVE
24271 **    PENDING -> EXCLUSIVE
24272 **
24273 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24274 ** routine to lower a locking level.
24275 */
24276 static int unixLock(sqlite3_file *id, int eFileLock){
24277   /* The following describes the implementation of the various locks and
24278   ** lock transitions in terms of the POSIX advisory shared and exclusive
24279   ** lock primitives (called read-locks and write-locks below, to avoid
24280   ** confusion with SQLite lock names). The algorithms are complicated
24281   ** slightly in order to be compatible with windows systems simultaneously
24282   ** accessing the same database file, in case that is ever required.
24283   **
24284   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24285   ** byte', each single bytes at well known offsets, and the 'shared byte
24286   ** range', a range of 510 bytes at a well known offset.
24287   **
24288   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24289   ** byte'.  If this is successful, a random byte from the 'shared byte
24290   ** range' is read-locked and the lock on the 'pending byte' released.
24291   **
24292   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24293   ** A RESERVED lock is implemented by grabbing a write-lock on the
24294   ** 'reserved byte'. 
24295   **
24296   ** A process may only obtain a PENDING lock after it has obtained a
24297   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24298   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24299   ** obtained, but existing SHARED locks are allowed to persist. A process
24300   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24301   ** This property is used by the algorithm for rolling back a journal file
24302   ** after a crash.
24303   **
24304   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24305   ** implemented by obtaining a write-lock on the entire 'shared byte
24306   ** range'. Since all other locks require a read-lock on one of the bytes
24307   ** within this range, this ensures that no other locks are held on the
24308   ** database. 
24309   **
24310   ** The reason a single byte cannot be used instead of the 'shared byte
24311   ** range' is that some versions of windows do not support read-locks. By
24312   ** locking a random byte from a range, concurrent SHARED locks may exist
24313   ** even if the locking primitive used is always a write-lock.
24314   */
24315   int rc = SQLITE_OK;
24316   unixFile *pFile = (unixFile*)id;
24317   unixInodeInfo *pInode;
24318   struct flock lock;
24319   int tErrno = 0;
24320
24321   assert( pFile );
24322   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24323       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24324       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24325
24326   /* If there is already a lock of this type or more restrictive on the
24327   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24328   ** unixEnterMutex() hasn't been called yet.
24329   */
24330   if( pFile->eFileLock>=eFileLock ){
24331     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24332             azFileLock(eFileLock)));
24333     return SQLITE_OK;
24334   }
24335
24336   /* Make sure the locking sequence is correct.
24337   **  (1) We never move from unlocked to anything higher than shared lock.
24338   **  (2) SQLite never explicitly requests a pendig lock.
24339   **  (3) A shared lock is always held when a reserve lock is requested.
24340   */
24341   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24342   assert( eFileLock!=PENDING_LOCK );
24343   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24344
24345   /* This mutex is needed because pFile->pInode is shared across threads
24346   */
24347   unixEnterMutex();
24348   pInode = pFile->pInode;
24349
24350   /* If some thread using this PID has a lock via a different unixFile*
24351   ** handle that precludes the requested lock, return BUSY.
24352   */
24353   if( (pFile->eFileLock!=pInode->eFileLock && 
24354           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24355   ){
24356     rc = SQLITE_BUSY;
24357     goto end_lock;
24358   }
24359
24360   /* If a SHARED lock is requested, and some thread using this PID already
24361   ** has a SHARED or RESERVED lock, then increment reference counts and
24362   ** return SQLITE_OK.
24363   */
24364   if( eFileLock==SHARED_LOCK && 
24365       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24366     assert( eFileLock==SHARED_LOCK );
24367     assert( pFile->eFileLock==0 );
24368     assert( pInode->nShared>0 );
24369     pFile->eFileLock = SHARED_LOCK;
24370     pInode->nShared++;
24371     pInode->nLock++;
24372     goto end_lock;
24373   }
24374
24375
24376   /* A PENDING lock is needed before acquiring a SHARED lock and before
24377   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24378   ** be released.
24379   */
24380   lock.l_len = 1L;
24381   lock.l_whence = SEEK_SET;
24382   if( eFileLock==SHARED_LOCK 
24383       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24384   ){
24385     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24386     lock.l_start = PENDING_BYTE;
24387     if( unixFileLock(pFile, &lock) ){
24388       tErrno = errno;
24389       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24390       if( rc!=SQLITE_BUSY ){
24391         pFile->lastErrno = tErrno;
24392       }
24393       goto end_lock;
24394     }
24395   }
24396
24397
24398   /* If control gets to this point, then actually go ahead and make
24399   ** operating system calls for the specified lock.
24400   */
24401   if( eFileLock==SHARED_LOCK ){
24402     assert( pInode->nShared==0 );
24403     assert( pInode->eFileLock==0 );
24404     assert( rc==SQLITE_OK );
24405
24406     /* Now get the read-lock */
24407     lock.l_start = SHARED_FIRST;
24408     lock.l_len = SHARED_SIZE;
24409     if( unixFileLock(pFile, &lock) ){
24410       tErrno = errno;
24411       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24412     }
24413
24414     /* Drop the temporary PENDING lock */
24415     lock.l_start = PENDING_BYTE;
24416     lock.l_len = 1L;
24417     lock.l_type = F_UNLCK;
24418     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24419       /* This could happen with a network mount */
24420       tErrno = errno;
24421       rc = SQLITE_IOERR_UNLOCK; 
24422     }
24423
24424     if( rc ){
24425       if( rc!=SQLITE_BUSY ){
24426         pFile->lastErrno = tErrno;
24427       }
24428       goto end_lock;
24429     }else{
24430       pFile->eFileLock = SHARED_LOCK;
24431       pInode->nLock++;
24432       pInode->nShared = 1;
24433     }
24434   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24435     /* We are trying for an exclusive lock but another thread in this
24436     ** same process is still holding a shared lock. */
24437     rc = SQLITE_BUSY;
24438   }else{
24439     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24440     ** assumed that there is a SHARED or greater lock on the file
24441     ** already.
24442     */
24443     assert( 0!=pFile->eFileLock );
24444     lock.l_type = F_WRLCK;
24445
24446     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24447     if( eFileLock==RESERVED_LOCK ){
24448       lock.l_start = RESERVED_BYTE;
24449       lock.l_len = 1L;
24450     }else{
24451       lock.l_start = SHARED_FIRST;
24452       lock.l_len = SHARED_SIZE;
24453     }
24454
24455     if( unixFileLock(pFile, &lock) ){
24456       tErrno = errno;
24457       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24458       if( rc!=SQLITE_BUSY ){
24459         pFile->lastErrno = tErrno;
24460       }
24461     }
24462   }
24463   
24464
24465 #ifdef SQLITE_DEBUG
24466   /* Set up the transaction-counter change checking flags when
24467   ** transitioning from a SHARED to a RESERVED lock.  The change
24468   ** from SHARED to RESERVED marks the beginning of a normal
24469   ** write operation (not a hot journal rollback).
24470   */
24471   if( rc==SQLITE_OK
24472    && pFile->eFileLock<=SHARED_LOCK
24473    && eFileLock==RESERVED_LOCK
24474   ){
24475     pFile->transCntrChng = 0;
24476     pFile->dbUpdate = 0;
24477     pFile->inNormalWrite = 1;
24478   }
24479 #endif
24480
24481
24482   if( rc==SQLITE_OK ){
24483     pFile->eFileLock = eFileLock;
24484     pInode->eFileLock = eFileLock;
24485   }else if( eFileLock==EXCLUSIVE_LOCK ){
24486     pFile->eFileLock = PENDING_LOCK;
24487     pInode->eFileLock = PENDING_LOCK;
24488   }
24489
24490 end_lock:
24491   unixLeaveMutex();
24492   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24493       rc==SQLITE_OK ? "ok" : "failed"));
24494   return rc;
24495 }
24496
24497 /*
24498 ** Add the file descriptor used by file handle pFile to the corresponding
24499 ** pUnused list.
24500 */
24501 static void setPendingFd(unixFile *pFile){
24502   unixInodeInfo *pInode = pFile->pInode;
24503   UnixUnusedFd *p = pFile->pUnused;
24504   p->pNext = pInode->pUnused;
24505   pInode->pUnused = p;
24506   pFile->h = -1;
24507   pFile->pUnused = 0;
24508 }
24509
24510 /*
24511 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24512 ** must be either NO_LOCK or SHARED_LOCK.
24513 **
24514 ** If the locking level of the file descriptor is already at or below
24515 ** the requested locking level, this routine is a no-op.
24516 ** 
24517 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24518 ** the byte range is divided into 2 parts and the first part is unlocked then
24519 ** set to a read lock, then the other part is simply unlocked.  This works 
24520 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24521 ** remove the write lock on a region when a read lock is set.
24522 */
24523 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24524   unixFile *pFile = (unixFile*)id;
24525   unixInodeInfo *pInode;
24526   struct flock lock;
24527   int rc = SQLITE_OK;
24528
24529   assert( pFile );
24530   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24531       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24532       getpid()));
24533
24534   assert( eFileLock<=SHARED_LOCK );
24535   if( pFile->eFileLock<=eFileLock ){
24536     return SQLITE_OK;
24537   }
24538   unixEnterMutex();
24539   pInode = pFile->pInode;
24540   assert( pInode->nShared!=0 );
24541   if( pFile->eFileLock>SHARED_LOCK ){
24542     assert( pInode->eFileLock==pFile->eFileLock );
24543
24544 #ifdef SQLITE_DEBUG
24545     /* When reducing a lock such that other processes can start
24546     ** reading the database file again, make sure that the
24547     ** transaction counter was updated if any part of the database
24548     ** file changed.  If the transaction counter is not updated,
24549     ** other connections to the same file might not realize that
24550     ** the file has changed and hence might not know to flush their
24551     ** cache.  The use of a stale cache can lead to database corruption.
24552     */
24553     pFile->inNormalWrite = 0;
24554 #endif
24555
24556     /* downgrading to a shared lock on NFS involves clearing the write lock
24557     ** before establishing the readlock - to avoid a race condition we downgrade
24558     ** the lock in 2 blocks, so that part of the range will be covered by a 
24559     ** write lock until the rest is covered by a read lock:
24560     **  1:   [WWWWW]
24561     **  2:   [....W]
24562     **  3:   [RRRRW]
24563     **  4:   [RRRR.]
24564     */
24565     if( eFileLock==SHARED_LOCK ){
24566
24567 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24568       (void)handleNFSUnlock;
24569       assert( handleNFSUnlock==0 );
24570 #endif
24571 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24572       if( handleNFSUnlock ){
24573         int tErrno;               /* Error code from system call errors */
24574         off_t divSize = SHARED_SIZE - 1;
24575         
24576         lock.l_type = F_UNLCK;
24577         lock.l_whence = SEEK_SET;
24578         lock.l_start = SHARED_FIRST;
24579         lock.l_len = divSize;
24580         if( unixFileLock(pFile, &lock)==(-1) ){
24581           tErrno = errno;
24582           rc = SQLITE_IOERR_UNLOCK;
24583           if( IS_LOCK_ERROR(rc) ){
24584             pFile->lastErrno = tErrno;
24585           }
24586           goto end_unlock;
24587         }
24588         lock.l_type = F_RDLCK;
24589         lock.l_whence = SEEK_SET;
24590         lock.l_start = SHARED_FIRST;
24591         lock.l_len = divSize;
24592         if( unixFileLock(pFile, &lock)==(-1) ){
24593           tErrno = errno;
24594           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24595           if( IS_LOCK_ERROR(rc) ){
24596             pFile->lastErrno = tErrno;
24597           }
24598           goto end_unlock;
24599         }
24600         lock.l_type = F_UNLCK;
24601         lock.l_whence = SEEK_SET;
24602         lock.l_start = SHARED_FIRST+divSize;
24603         lock.l_len = SHARED_SIZE-divSize;
24604         if( unixFileLock(pFile, &lock)==(-1) ){
24605           tErrno = errno;
24606           rc = SQLITE_IOERR_UNLOCK;
24607           if( IS_LOCK_ERROR(rc) ){
24608             pFile->lastErrno = tErrno;
24609           }
24610           goto end_unlock;
24611         }
24612       }else
24613 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24614       {
24615         lock.l_type = F_RDLCK;
24616         lock.l_whence = SEEK_SET;
24617         lock.l_start = SHARED_FIRST;
24618         lock.l_len = SHARED_SIZE;
24619         if( unixFileLock(pFile, &lock) ){
24620           /* In theory, the call to unixFileLock() cannot fail because another
24621           ** process is holding an incompatible lock. If it does, this 
24622           ** indicates that the other process is not following the locking
24623           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24624           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
24625           ** an assert to fail). */ 
24626           rc = SQLITE_IOERR_RDLOCK;
24627           pFile->lastErrno = errno;
24628           goto end_unlock;
24629         }
24630       }
24631     }
24632     lock.l_type = F_UNLCK;
24633     lock.l_whence = SEEK_SET;
24634     lock.l_start = PENDING_BYTE;
24635     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24636     if( unixFileLock(pFile, &lock)==0 ){
24637       pInode->eFileLock = SHARED_LOCK;
24638     }else{
24639       rc = SQLITE_IOERR_UNLOCK;
24640       pFile->lastErrno = errno;
24641       goto end_unlock;
24642     }
24643   }
24644   if( eFileLock==NO_LOCK ){
24645     /* Decrement the shared lock counter.  Release the lock using an
24646     ** OS call only when all threads in this same process have released
24647     ** the lock.
24648     */
24649     pInode->nShared--;
24650     if( pInode->nShared==0 ){
24651       lock.l_type = F_UNLCK;
24652       lock.l_whence = SEEK_SET;
24653       lock.l_start = lock.l_len = 0L;
24654       if( unixFileLock(pFile, &lock)==0 ){
24655         pInode->eFileLock = NO_LOCK;
24656       }else{
24657         rc = SQLITE_IOERR_UNLOCK;
24658         pFile->lastErrno = errno;
24659         pInode->eFileLock = NO_LOCK;
24660         pFile->eFileLock = NO_LOCK;
24661       }
24662     }
24663
24664     /* Decrement the count of locks against this same file.  When the
24665     ** count reaches zero, close any other file descriptors whose close
24666     ** was deferred because of outstanding locks.
24667     */
24668     pInode->nLock--;
24669     assert( pInode->nLock>=0 );
24670     if( pInode->nLock==0 ){
24671       closePendingFds(pFile);
24672     }
24673   }
24674
24675 end_unlock:
24676   unixLeaveMutex();
24677   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24678   return rc;
24679 }
24680
24681 /*
24682 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24683 ** must be either NO_LOCK or SHARED_LOCK.
24684 **
24685 ** If the locking level of the file descriptor is already at or below
24686 ** the requested locking level, this routine is a no-op.
24687 */
24688 static int unixUnlock(sqlite3_file *id, int eFileLock){
24689   return posixUnlock(id, eFileLock, 0);
24690 }
24691
24692 /*
24693 ** This function performs the parts of the "close file" operation 
24694 ** common to all locking schemes. It closes the directory and file
24695 ** handles, if they are valid, and sets all fields of the unixFile
24696 ** structure to 0.
24697 **
24698 ** It is *not* necessary to hold the mutex when this routine is called,
24699 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24700 ** vxworksReleaseFileId() routine.
24701 */
24702 static int closeUnixFile(sqlite3_file *id){
24703   unixFile *pFile = (unixFile*)id;
24704   if( pFile->h>=0 ){
24705     robust_close(pFile, pFile->h, __LINE__);
24706     pFile->h = -1;
24707   }
24708 #if OS_VXWORKS
24709   if( pFile->pId ){
24710     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24711       osUnlink(pFile->pId->zCanonicalName);
24712     }
24713     vxworksReleaseFileId(pFile->pId);
24714     pFile->pId = 0;
24715   }
24716 #endif
24717   OSTRACE(("CLOSE   %-3d\n", pFile->h));
24718   OpenCounter(-1);
24719   sqlite3_free(pFile->pUnused);
24720   memset(pFile, 0, sizeof(unixFile));
24721   return SQLITE_OK;
24722 }
24723
24724 /*
24725 ** Close a file.
24726 */
24727 static int unixClose(sqlite3_file *id){
24728   int rc = SQLITE_OK;
24729   unixFile *pFile = (unixFile *)id;
24730   unixUnlock(id, NO_LOCK);
24731   unixEnterMutex();
24732
24733   /* unixFile.pInode is always valid here. Otherwise, a different close
24734   ** routine (e.g. nolockClose()) would be called instead.
24735   */
24736   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
24737   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
24738     /* If there are outstanding locks, do not actually close the file just
24739     ** yet because that would clear those locks.  Instead, add the file
24740     ** descriptor to pInode->pUnused list.  It will be automatically closed 
24741     ** when the last lock is cleared.
24742     */
24743     setPendingFd(pFile);
24744   }
24745   releaseInodeInfo(pFile);
24746   rc = closeUnixFile(id);
24747   unixLeaveMutex();
24748   return rc;
24749 }
24750
24751 /************** End of the posix advisory lock implementation *****************
24752 ******************************************************************************/
24753
24754 /******************************************************************************
24755 ****************************** No-op Locking **********************************
24756 **
24757 ** Of the various locking implementations available, this is by far the
24758 ** simplest:  locking is ignored.  No attempt is made to lock the database
24759 ** file for reading or writing.
24760 **
24761 ** This locking mode is appropriate for use on read-only databases
24762 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24763 ** also be used if the application employs some external mechanism to
24764 ** prevent simultaneous access of the same database by two or more
24765 ** database connections.  But there is a serious risk of database
24766 ** corruption if this locking mode is used in situations where multiple
24767 ** database connections are accessing the same database file at the same
24768 ** time and one or more of those connections are writing.
24769 */
24770
24771 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24772   UNUSED_PARAMETER(NotUsed);
24773   *pResOut = 0;
24774   return SQLITE_OK;
24775 }
24776 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24777   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24778   return SQLITE_OK;
24779 }
24780 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24781   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24782   return SQLITE_OK;
24783 }
24784
24785 /*
24786 ** Close the file.
24787 */
24788 static int nolockClose(sqlite3_file *id) {
24789   return closeUnixFile(id);
24790 }
24791
24792 /******************* End of the no-op lock implementation *********************
24793 ******************************************************************************/
24794
24795 /******************************************************************************
24796 ************************* Begin dot-file Locking ******************************
24797 **
24798 ** The dotfile locking implementation uses the existance of separate lock
24799 ** files (really a directory) to control access to the database.  This works
24800 ** on just about every filesystem imaginable.  But there are serious downsides:
24801 **
24802 **    (1)  There is zero concurrency.  A single reader blocks all other
24803 **         connections from reading or writing the database.
24804 **
24805 **    (2)  An application crash or power loss can leave stale lock files
24806 **         sitting around that need to be cleared manually.
24807 **
24808 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24809 ** other locking strategy is available.
24810 **
24811 ** Dotfile locking works by creating a subdirectory in the same directory as
24812 ** the database and with the same name but with a ".lock" extension added.
24813 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
24814 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24815 */
24816
24817 /*
24818 ** The file suffix added to the data base filename in order to create the
24819 ** lock directory.
24820 */
24821 #define DOTLOCK_SUFFIX ".lock"
24822
24823 /*
24824 ** This routine checks if there is a RESERVED lock held on the specified
24825 ** file by this or any other process. If such a lock is held, set *pResOut
24826 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24827 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24828 **
24829 ** In dotfile locking, either a lock exists or it does not.  So in this
24830 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24831 ** is held on the file and false if the file is unlocked.
24832 */
24833 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24834   int rc = SQLITE_OK;
24835   int reserved = 0;
24836   unixFile *pFile = (unixFile*)id;
24837
24838   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24839   
24840   assert( pFile );
24841
24842   /* Check if a thread in this process holds such a lock */
24843   if( pFile->eFileLock>SHARED_LOCK ){
24844     /* Either this connection or some other connection in the same process
24845     ** holds a lock on the file.  No need to check further. */
24846     reserved = 1;
24847   }else{
24848     /* The lock is held if and only if the lockfile exists */
24849     const char *zLockFile = (const char*)pFile->lockingContext;
24850     reserved = osAccess(zLockFile, 0)==0;
24851   }
24852   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24853   *pResOut = reserved;
24854   return rc;
24855 }
24856
24857 /*
24858 ** Lock the file with the lock specified by parameter eFileLock - one
24859 ** of the following:
24860 **
24861 **     (1) SHARED_LOCK
24862 **     (2) RESERVED_LOCK
24863 **     (3) PENDING_LOCK
24864 **     (4) EXCLUSIVE_LOCK
24865 **
24866 ** Sometimes when requesting one lock state, additional lock states
24867 ** are inserted in between.  The locking might fail on one of the later
24868 ** transitions leaving the lock state different from what it started but
24869 ** still short of its goal.  The following chart shows the allowed
24870 ** transitions and the inserted intermediate states:
24871 **
24872 **    UNLOCKED -> SHARED
24873 **    SHARED -> RESERVED
24874 **    SHARED -> (PENDING) -> EXCLUSIVE
24875 **    RESERVED -> (PENDING) -> EXCLUSIVE
24876 **    PENDING -> EXCLUSIVE
24877 **
24878 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24879 ** routine to lower a locking level.
24880 **
24881 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24882 ** But we track the other locking levels internally.
24883 */
24884 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24885   unixFile *pFile = (unixFile*)id;
24886   char *zLockFile = (char *)pFile->lockingContext;
24887   int rc = SQLITE_OK;
24888
24889
24890   /* If we have any lock, then the lock file already exists.  All we have
24891   ** to do is adjust our internal record of the lock level.
24892   */
24893   if( pFile->eFileLock > NO_LOCK ){
24894     pFile->eFileLock = eFileLock;
24895     /* Always update the timestamp on the old file */
24896 #ifdef HAVE_UTIME
24897     utime(zLockFile, NULL);
24898 #else
24899     utimes(zLockFile, NULL);
24900 #endif
24901     return SQLITE_OK;
24902   }
24903   
24904   /* grab an exclusive lock */
24905   rc = osMkdir(zLockFile, 0777);
24906   if( rc<0 ){
24907     /* failed to open/create the lock directory */
24908     int tErrno = errno;
24909     if( EEXIST == tErrno ){
24910       rc = SQLITE_BUSY;
24911     } else {
24912       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24913       if( IS_LOCK_ERROR(rc) ){
24914         pFile->lastErrno = tErrno;
24915       }
24916     }
24917     return rc;
24918   } 
24919   
24920   /* got it, set the type and return ok */
24921   pFile->eFileLock = eFileLock;
24922   return rc;
24923 }
24924
24925 /*
24926 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24927 ** must be either NO_LOCK or SHARED_LOCK.
24928 **
24929 ** If the locking level of the file descriptor is already at or below
24930 ** the requested locking level, this routine is a no-op.
24931 **
24932 ** When the locking level reaches NO_LOCK, delete the lock file.
24933 */
24934 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24935   unixFile *pFile = (unixFile*)id;
24936   char *zLockFile = (char *)pFile->lockingContext;
24937   int rc;
24938
24939   assert( pFile );
24940   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24941            pFile->eFileLock, getpid()));
24942   assert( eFileLock<=SHARED_LOCK );
24943   
24944   /* no-op if possible */
24945   if( pFile->eFileLock==eFileLock ){
24946     return SQLITE_OK;
24947   }
24948
24949   /* To downgrade to shared, simply update our internal notion of the
24950   ** lock state.  No need to mess with the file on disk.
24951   */
24952   if( eFileLock==SHARED_LOCK ){
24953     pFile->eFileLock = SHARED_LOCK;
24954     return SQLITE_OK;
24955   }
24956   
24957   /* To fully unlock the database, delete the lock file */
24958   assert( eFileLock==NO_LOCK );
24959   rc = osRmdir(zLockFile);
24960   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
24961   if( rc<0 ){
24962     int tErrno = errno;
24963     rc = 0;
24964     if( ENOENT != tErrno ){
24965       rc = SQLITE_IOERR_UNLOCK;
24966     }
24967     if( IS_LOCK_ERROR(rc) ){
24968       pFile->lastErrno = tErrno;
24969     }
24970     return rc; 
24971   }
24972   pFile->eFileLock = NO_LOCK;
24973   return SQLITE_OK;
24974 }
24975
24976 /*
24977 ** Close a file.  Make sure the lock has been released before closing.
24978 */
24979 static int dotlockClose(sqlite3_file *id) {
24980   int rc = SQLITE_OK;
24981   if( id ){
24982     unixFile *pFile = (unixFile*)id;
24983     dotlockUnlock(id, NO_LOCK);
24984     sqlite3_free(pFile->lockingContext);
24985     rc = closeUnixFile(id);
24986   }
24987   return rc;
24988 }
24989 /****************** End of the dot-file lock implementation *******************
24990 ******************************************************************************/
24991
24992 /******************************************************************************
24993 ************************** Begin flock Locking ********************************
24994 **
24995 ** Use the flock() system call to do file locking.
24996 **
24997 ** flock() locking is like dot-file locking in that the various
24998 ** fine-grain locking levels supported by SQLite are collapsed into
24999 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
25000 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25001 ** still works when you do this, but concurrency is reduced since
25002 ** only a single process can be reading the database at a time.
25003 **
25004 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25005 ** compiling for VXWORKS.
25006 */
25007 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25008
25009 /*
25010 ** Retry flock() calls that fail with EINTR
25011 */
25012 #ifdef EINTR
25013 static int robust_flock(int fd, int op){
25014   int rc;
25015   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25016   return rc;
25017 }
25018 #else
25019 # define robust_flock(a,b) flock(a,b)
25020 #endif
25021      
25022
25023 /*
25024 ** This routine checks if there is a RESERVED lock held on the specified
25025 ** file by this or any other process. If such a lock is held, set *pResOut
25026 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25027 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25028 */
25029 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25030   int rc = SQLITE_OK;
25031   int reserved = 0;
25032   unixFile *pFile = (unixFile*)id;
25033   
25034   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25035   
25036   assert( pFile );
25037   
25038   /* Check if a thread in this process holds such a lock */
25039   if( pFile->eFileLock>SHARED_LOCK ){
25040     reserved = 1;
25041   }
25042   
25043   /* Otherwise see if some other process holds it. */
25044   if( !reserved ){
25045     /* attempt to get the lock */
25046     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25047     if( !lrc ){
25048       /* got the lock, unlock it */
25049       lrc = robust_flock(pFile->h, LOCK_UN);
25050       if ( lrc ) {
25051         int tErrno = errno;
25052         /* unlock failed with an error */
25053         lrc = SQLITE_IOERR_UNLOCK; 
25054         if( IS_LOCK_ERROR(lrc) ){
25055           pFile->lastErrno = tErrno;
25056           rc = lrc;
25057         }
25058       }
25059     } else {
25060       int tErrno = errno;
25061       reserved = 1;
25062       /* someone else might have it reserved */
25063       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
25064       if( IS_LOCK_ERROR(lrc) ){
25065         pFile->lastErrno = tErrno;
25066         rc = lrc;
25067       }
25068     }
25069   }
25070   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25071
25072 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25073   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25074     rc = SQLITE_OK;
25075     reserved=1;
25076   }
25077 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25078   *pResOut = reserved;
25079   return rc;
25080 }
25081
25082 /*
25083 ** Lock the file with the lock specified by parameter eFileLock - one
25084 ** of the following:
25085 **
25086 **     (1) SHARED_LOCK
25087 **     (2) RESERVED_LOCK
25088 **     (3) PENDING_LOCK
25089 **     (4) EXCLUSIVE_LOCK
25090 **
25091 ** Sometimes when requesting one lock state, additional lock states
25092 ** are inserted in between.  The locking might fail on one of the later
25093 ** transitions leaving the lock state different from what it started but
25094 ** still short of its goal.  The following chart shows the allowed
25095 ** transitions and the inserted intermediate states:
25096 **
25097 **    UNLOCKED -> SHARED
25098 **    SHARED -> RESERVED
25099 **    SHARED -> (PENDING) -> EXCLUSIVE
25100 **    RESERVED -> (PENDING) -> EXCLUSIVE
25101 **    PENDING -> EXCLUSIVE
25102 **
25103 ** flock() only really support EXCLUSIVE locks.  We track intermediate
25104 ** lock states in the sqlite3_file structure, but all locks SHARED or
25105 ** above are really EXCLUSIVE locks and exclude all other processes from
25106 ** access the file.
25107 **
25108 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25109 ** routine to lower a locking level.
25110 */
25111 static int flockLock(sqlite3_file *id, int eFileLock) {
25112   int rc = SQLITE_OK;
25113   unixFile *pFile = (unixFile*)id;
25114
25115   assert( pFile );
25116
25117   /* if we already have a lock, it is exclusive.  
25118   ** Just adjust level and punt on outta here. */
25119   if (pFile->eFileLock > NO_LOCK) {
25120     pFile->eFileLock = eFileLock;
25121     return SQLITE_OK;
25122   }
25123   
25124   /* grab an exclusive lock */
25125   
25126   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25127     int tErrno = errno;
25128     /* didn't get, must be busy */
25129     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25130     if( IS_LOCK_ERROR(rc) ){
25131       pFile->lastErrno = tErrno;
25132     }
25133   } else {
25134     /* got it, set the type and return ok */
25135     pFile->eFileLock = eFileLock;
25136   }
25137   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
25138            rc==SQLITE_OK ? "ok" : "failed"));
25139 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25140   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25141     rc = SQLITE_BUSY;
25142   }
25143 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25144   return rc;
25145 }
25146
25147
25148 /*
25149 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25150 ** must be either NO_LOCK or SHARED_LOCK.
25151 **
25152 ** If the locking level of the file descriptor is already at or below
25153 ** the requested locking level, this routine is a no-op.
25154 */
25155 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25156   unixFile *pFile = (unixFile*)id;
25157   
25158   assert( pFile );
25159   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25160            pFile->eFileLock, getpid()));
25161   assert( eFileLock<=SHARED_LOCK );
25162   
25163   /* no-op if possible */
25164   if( pFile->eFileLock==eFileLock ){
25165     return SQLITE_OK;
25166   }
25167   
25168   /* shared can just be set because we always have an exclusive */
25169   if (eFileLock==SHARED_LOCK) {
25170     pFile->eFileLock = eFileLock;
25171     return SQLITE_OK;
25172   }
25173   
25174   /* no, really, unlock. */
25175   if( robust_flock(pFile->h, LOCK_UN) ){
25176 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25177     return SQLITE_OK;
25178 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25179     return SQLITE_IOERR_UNLOCK;
25180   }else{
25181     pFile->eFileLock = NO_LOCK;
25182     return SQLITE_OK;
25183   }
25184 }
25185
25186 /*
25187 ** Close a file.
25188 */
25189 static int flockClose(sqlite3_file *id) {
25190   int rc = SQLITE_OK;
25191   if( id ){
25192     flockUnlock(id, NO_LOCK);
25193     rc = closeUnixFile(id);
25194   }
25195   return rc;
25196 }
25197
25198 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25199
25200 /******************* End of the flock lock implementation *********************
25201 ******************************************************************************/
25202
25203 /******************************************************************************
25204 ************************ Begin Named Semaphore Locking ************************
25205 **
25206 ** Named semaphore locking is only supported on VxWorks.
25207 **
25208 ** Semaphore locking is like dot-lock and flock in that it really only
25209 ** supports EXCLUSIVE locking.  Only a single process can read or write
25210 ** the database file at a time.  This reduces potential concurrency, but
25211 ** makes the lock implementation much easier.
25212 */
25213 #if OS_VXWORKS
25214
25215 /*
25216 ** This routine checks if there is a RESERVED lock held on the specified
25217 ** file by this or any other process. If such a lock is held, set *pResOut
25218 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25219 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25220 */
25221 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25222   int rc = SQLITE_OK;
25223   int reserved = 0;
25224   unixFile *pFile = (unixFile*)id;
25225
25226   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25227   
25228   assert( pFile );
25229
25230   /* Check if a thread in this process holds such a lock */
25231   if( pFile->eFileLock>SHARED_LOCK ){
25232     reserved = 1;
25233   }
25234   
25235   /* Otherwise see if some other process holds it. */
25236   if( !reserved ){
25237     sem_t *pSem = pFile->pInode->pSem;
25238     struct stat statBuf;
25239
25240     if( sem_trywait(pSem)==-1 ){
25241       int tErrno = errno;
25242       if( EAGAIN != tErrno ){
25243         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25244         pFile->lastErrno = tErrno;
25245       } else {
25246         /* someone else has the lock when we are in NO_LOCK */
25247         reserved = (pFile->eFileLock < SHARED_LOCK);
25248       }
25249     }else{
25250       /* we could have it if we want it */
25251       sem_post(pSem);
25252     }
25253   }
25254   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25255
25256   *pResOut = reserved;
25257   return rc;
25258 }
25259
25260 /*
25261 ** Lock the file with the lock specified by parameter eFileLock - one
25262 ** of the following:
25263 **
25264 **     (1) SHARED_LOCK
25265 **     (2) RESERVED_LOCK
25266 **     (3) PENDING_LOCK
25267 **     (4) EXCLUSIVE_LOCK
25268 **
25269 ** Sometimes when requesting one lock state, additional lock states
25270 ** are inserted in between.  The locking might fail on one of the later
25271 ** transitions leaving the lock state different from what it started but
25272 ** still short of its goal.  The following chart shows the allowed
25273 ** transitions and the inserted intermediate states:
25274 **
25275 **    UNLOCKED -> SHARED
25276 **    SHARED -> RESERVED
25277 **    SHARED -> (PENDING) -> EXCLUSIVE
25278 **    RESERVED -> (PENDING) -> EXCLUSIVE
25279 **    PENDING -> EXCLUSIVE
25280 **
25281 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25282 ** lock states in the sqlite3_file structure, but all locks SHARED or
25283 ** above are really EXCLUSIVE locks and exclude all other processes from
25284 ** access the file.
25285 **
25286 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25287 ** routine to lower a locking level.
25288 */
25289 static int semLock(sqlite3_file *id, int eFileLock) {
25290   unixFile *pFile = (unixFile*)id;
25291   int fd;
25292   sem_t *pSem = pFile->pInode->pSem;
25293   int rc = SQLITE_OK;
25294
25295   /* if we already have a lock, it is exclusive.  
25296   ** Just adjust level and punt on outta here. */
25297   if (pFile->eFileLock > NO_LOCK) {
25298     pFile->eFileLock = eFileLock;
25299     rc = SQLITE_OK;
25300     goto sem_end_lock;
25301   }
25302   
25303   /* lock semaphore now but bail out when already locked. */
25304   if( sem_trywait(pSem)==-1 ){
25305     rc = SQLITE_BUSY;
25306     goto sem_end_lock;
25307   }
25308
25309   /* got it, set the type and return ok */
25310   pFile->eFileLock = eFileLock;
25311
25312  sem_end_lock:
25313   return rc;
25314 }
25315
25316 /*
25317 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25318 ** must be either NO_LOCK or SHARED_LOCK.
25319 **
25320 ** If the locking level of the file descriptor is already at or below
25321 ** the requested locking level, this routine is a no-op.
25322 */
25323 static int semUnlock(sqlite3_file *id, int eFileLock) {
25324   unixFile *pFile = (unixFile*)id;
25325   sem_t *pSem = pFile->pInode->pSem;
25326
25327   assert( pFile );
25328   assert( pSem );
25329   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25330            pFile->eFileLock, getpid()));
25331   assert( eFileLock<=SHARED_LOCK );
25332   
25333   /* no-op if possible */
25334   if( pFile->eFileLock==eFileLock ){
25335     return SQLITE_OK;
25336   }
25337   
25338   /* shared can just be set because we always have an exclusive */
25339   if (eFileLock==SHARED_LOCK) {
25340     pFile->eFileLock = eFileLock;
25341     return SQLITE_OK;
25342   }
25343   
25344   /* no, really unlock. */
25345   if ( sem_post(pSem)==-1 ) {
25346     int rc, tErrno = errno;
25347     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25348     if( IS_LOCK_ERROR(rc) ){
25349       pFile->lastErrno = tErrno;
25350     }
25351     return rc; 
25352   }
25353   pFile->eFileLock = NO_LOCK;
25354   return SQLITE_OK;
25355 }
25356
25357 /*
25358  ** Close a file.
25359  */
25360 static int semClose(sqlite3_file *id) {
25361   if( id ){
25362     unixFile *pFile = (unixFile*)id;
25363     semUnlock(id, NO_LOCK);
25364     assert( pFile );
25365     unixEnterMutex();
25366     releaseInodeInfo(pFile);
25367     unixLeaveMutex();
25368     closeUnixFile(id);
25369   }
25370   return SQLITE_OK;
25371 }
25372
25373 #endif /* OS_VXWORKS */
25374 /*
25375 ** Named semaphore locking is only available on VxWorks.
25376 **
25377 *************** End of the named semaphore lock implementation ****************
25378 ******************************************************************************/
25379
25380
25381 /******************************************************************************
25382 *************************** Begin AFP Locking *********************************
25383 **
25384 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25385 ** on Apple Macintosh computers - both OS9 and OSX.
25386 **
25387 ** Third-party implementations of AFP are available.  But this code here
25388 ** only works on OSX.
25389 */
25390
25391 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25392 /*
25393 ** The afpLockingContext structure contains all afp lock specific state
25394 */
25395 typedef struct afpLockingContext afpLockingContext;
25396 struct afpLockingContext {
25397   int reserved;
25398   const char *dbPath;             /* Name of the open file */
25399 };
25400
25401 struct ByteRangeLockPB2
25402 {
25403   unsigned long long offset;        /* offset to first byte to lock */
25404   unsigned long long length;        /* nbr of bytes to lock */
25405   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25406   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25407   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25408   int fd;                           /* file desc to assoc this lock with */
25409 };
25410
25411 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25412
25413 /*
25414 ** This is a utility for setting or clearing a bit-range lock on an
25415 ** AFP filesystem.
25416 ** 
25417 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25418 */
25419 static int afpSetLock(
25420   const char *path,              /* Name of the file to be locked or unlocked */
25421   unixFile *pFile,               /* Open file descriptor on path */
25422   unsigned long long offset,     /* First byte to be locked */
25423   unsigned long long length,     /* Number of bytes to lock */
25424   int setLockFlag                /* True to set lock.  False to clear lock */
25425 ){
25426   struct ByteRangeLockPB2 pb;
25427   int err;
25428   
25429   pb.unLockFlag = setLockFlag ? 0 : 1;
25430   pb.startEndFlag = 0;
25431   pb.offset = offset;
25432   pb.length = length; 
25433   pb.fd = pFile->h;
25434   
25435   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25436     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25437     offset, length));
25438   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25439   if ( err==-1 ) {
25440     int rc;
25441     int tErrno = errno;
25442     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25443              path, tErrno, strerror(tErrno)));
25444 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25445     rc = SQLITE_BUSY;
25446 #else
25447     rc = sqliteErrorFromPosixError(tErrno,
25448                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25449 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25450     if( IS_LOCK_ERROR(rc) ){
25451       pFile->lastErrno = tErrno;
25452     }
25453     return rc;
25454   } else {
25455     return SQLITE_OK;
25456   }
25457 }
25458
25459 /*
25460 ** This routine checks if there is a RESERVED lock held on the specified
25461 ** file by this or any other process. If such a lock is held, set *pResOut
25462 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25463 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25464 */
25465 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25466   int rc = SQLITE_OK;
25467   int reserved = 0;
25468   unixFile *pFile = (unixFile*)id;
25469   afpLockingContext *context;
25470   
25471   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25472   
25473   assert( pFile );
25474   context = (afpLockingContext *) pFile->lockingContext;
25475   if( context->reserved ){
25476     *pResOut = 1;
25477     return SQLITE_OK;
25478   }
25479   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25480   
25481   /* Check if a thread in this process holds such a lock */
25482   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25483     reserved = 1;
25484   }
25485   
25486   /* Otherwise see if some other process holds it.
25487    */
25488   if( !reserved ){
25489     /* lock the RESERVED byte */
25490     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25491     if( SQLITE_OK==lrc ){
25492       /* if we succeeded in taking the reserved lock, unlock it to restore
25493       ** the original state */
25494       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25495     } else {
25496       /* if we failed to get the lock then someone else must have it */
25497       reserved = 1;
25498     }
25499     if( IS_LOCK_ERROR(lrc) ){
25500       rc=lrc;
25501     }
25502   }
25503   
25504   unixLeaveMutex();
25505   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25506   
25507   *pResOut = reserved;
25508   return rc;
25509 }
25510
25511 /*
25512 ** Lock the file with the lock specified by parameter eFileLock - one
25513 ** of the following:
25514 **
25515 **     (1) SHARED_LOCK
25516 **     (2) RESERVED_LOCK
25517 **     (3) PENDING_LOCK
25518 **     (4) EXCLUSIVE_LOCK
25519 **
25520 ** Sometimes when requesting one lock state, additional lock states
25521 ** are inserted in between.  The locking might fail on one of the later
25522 ** transitions leaving the lock state different from what it started but
25523 ** still short of its goal.  The following chart shows the allowed
25524 ** transitions and the inserted intermediate states:
25525 **
25526 **    UNLOCKED -> SHARED
25527 **    SHARED -> RESERVED
25528 **    SHARED -> (PENDING) -> EXCLUSIVE
25529 **    RESERVED -> (PENDING) -> EXCLUSIVE
25530 **    PENDING -> EXCLUSIVE
25531 **
25532 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25533 ** routine to lower a locking level.
25534 */
25535 static int afpLock(sqlite3_file *id, int eFileLock){
25536   int rc = SQLITE_OK;
25537   unixFile *pFile = (unixFile*)id;
25538   unixInodeInfo *pInode = pFile->pInode;
25539   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25540   
25541   assert( pFile );
25542   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25543            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25544            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25545
25546   /* If there is already a lock of this type or more restrictive on the
25547   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25548   ** unixEnterMutex() hasn't been called yet.
25549   */
25550   if( pFile->eFileLock>=eFileLock ){
25551     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25552            azFileLock(eFileLock)));
25553     return SQLITE_OK;
25554   }
25555
25556   /* Make sure the locking sequence is correct
25557   **  (1) We never move from unlocked to anything higher than shared lock.
25558   **  (2) SQLite never explicitly requests a pendig lock.
25559   **  (3) A shared lock is always held when a reserve lock is requested.
25560   */
25561   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25562   assert( eFileLock!=PENDING_LOCK );
25563   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25564   
25565   /* This mutex is needed because pFile->pInode is shared across threads
25566   */
25567   unixEnterMutex();
25568   pInode = pFile->pInode;
25569
25570   /* If some thread using this PID has a lock via a different unixFile*
25571   ** handle that precludes the requested lock, return BUSY.
25572   */
25573   if( (pFile->eFileLock!=pInode->eFileLock && 
25574        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25575      ){
25576     rc = SQLITE_BUSY;
25577     goto afp_end_lock;
25578   }
25579   
25580   /* If a SHARED lock is requested, and some thread using this PID already
25581   ** has a SHARED or RESERVED lock, then increment reference counts and
25582   ** return SQLITE_OK.
25583   */
25584   if( eFileLock==SHARED_LOCK && 
25585      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25586     assert( eFileLock==SHARED_LOCK );
25587     assert( pFile->eFileLock==0 );
25588     assert( pInode->nShared>0 );
25589     pFile->eFileLock = SHARED_LOCK;
25590     pInode->nShared++;
25591     pInode->nLock++;
25592     goto afp_end_lock;
25593   }
25594     
25595   /* A PENDING lock is needed before acquiring a SHARED lock and before
25596   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25597   ** be released.
25598   */
25599   if( eFileLock==SHARED_LOCK 
25600       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25601   ){
25602     int failed;
25603     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25604     if (failed) {
25605       rc = failed;
25606       goto afp_end_lock;
25607     }
25608   }
25609   
25610   /* If control gets to this point, then actually go ahead and make
25611   ** operating system calls for the specified lock.
25612   */
25613   if( eFileLock==SHARED_LOCK ){
25614     int lrc1, lrc2, lrc1Errno = 0;
25615     long lk, mask;
25616     
25617     assert( pInode->nShared==0 );
25618     assert( pInode->eFileLock==0 );
25619         
25620     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25621     /* Now get the read-lock SHARED_LOCK */
25622     /* note that the quality of the randomness doesn't matter that much */
25623     lk = random(); 
25624     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25625     lrc1 = afpSetLock(context->dbPath, pFile, 
25626           SHARED_FIRST+pInode->sharedByte, 1, 1);
25627     if( IS_LOCK_ERROR(lrc1) ){
25628       lrc1Errno = pFile->lastErrno;
25629     }
25630     /* Drop the temporary PENDING lock */
25631     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25632     
25633     if( IS_LOCK_ERROR(lrc1) ) {
25634       pFile->lastErrno = lrc1Errno;
25635       rc = lrc1;
25636       goto afp_end_lock;
25637     } else if( IS_LOCK_ERROR(lrc2) ){
25638       rc = lrc2;
25639       goto afp_end_lock;
25640     } else if( lrc1 != SQLITE_OK ) {
25641       rc = lrc1;
25642     } else {
25643       pFile->eFileLock = SHARED_LOCK;
25644       pInode->nLock++;
25645       pInode->nShared = 1;
25646     }
25647   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25648     /* We are trying for an exclusive lock but another thread in this
25649      ** same process is still holding a shared lock. */
25650     rc = SQLITE_BUSY;
25651   }else{
25652     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25653     ** assumed that there is a SHARED or greater lock on the file
25654     ** already.
25655     */
25656     int failed = 0;
25657     assert( 0!=pFile->eFileLock );
25658     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25659         /* Acquire a RESERVED lock */
25660         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25661       if( !failed ){
25662         context->reserved = 1;
25663       }
25664     }
25665     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25666       /* Acquire an EXCLUSIVE lock */
25667         
25668       /* Remove the shared lock before trying the range.  we'll need to 
25669       ** reestablish the shared lock if we can't get the  afpUnlock
25670       */
25671       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25672                          pInode->sharedByte, 1, 0)) ){
25673         int failed2 = SQLITE_OK;
25674         /* now attemmpt to get the exclusive lock range */
25675         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25676                                SHARED_SIZE, 1);
25677         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25678                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25679           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25680           ** a critical I/O error
25681           */
25682           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25683                SQLITE_IOERR_LOCK;
25684           goto afp_end_lock;
25685         } 
25686       }else{
25687         rc = failed; 
25688       }
25689     }
25690     if( failed ){
25691       rc = failed;
25692     }
25693   }
25694   
25695   if( rc==SQLITE_OK ){
25696     pFile->eFileLock = eFileLock;
25697     pInode->eFileLock = eFileLock;
25698   }else if( eFileLock==EXCLUSIVE_LOCK ){
25699     pFile->eFileLock = PENDING_LOCK;
25700     pInode->eFileLock = PENDING_LOCK;
25701   }
25702   
25703 afp_end_lock:
25704   unixLeaveMutex();
25705   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25706          rc==SQLITE_OK ? "ok" : "failed"));
25707   return rc;
25708 }
25709
25710 /*
25711 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25712 ** must be either NO_LOCK or SHARED_LOCK.
25713 **
25714 ** If the locking level of the file descriptor is already at or below
25715 ** the requested locking level, this routine is a no-op.
25716 */
25717 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25718   int rc = SQLITE_OK;
25719   unixFile *pFile = (unixFile*)id;
25720   unixInodeInfo *pInode;
25721   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25722   int skipShared = 0;
25723 #ifdef SQLITE_TEST
25724   int h = pFile->h;
25725 #endif
25726
25727   assert( pFile );
25728   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25729            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25730            getpid()));
25731
25732   assert( eFileLock<=SHARED_LOCK );
25733   if( pFile->eFileLock<=eFileLock ){
25734     return SQLITE_OK;
25735   }
25736   unixEnterMutex();
25737   pInode = pFile->pInode;
25738   assert( pInode->nShared!=0 );
25739   if( pFile->eFileLock>SHARED_LOCK ){
25740     assert( pInode->eFileLock==pFile->eFileLock );
25741     SimulateIOErrorBenign(1);
25742     SimulateIOError( h=(-1) )
25743     SimulateIOErrorBenign(0);
25744     
25745 #ifdef SQLITE_DEBUG
25746     /* When reducing a lock such that other processes can start
25747     ** reading the database file again, make sure that the
25748     ** transaction counter was updated if any part of the database
25749     ** file changed.  If the transaction counter is not updated,
25750     ** other connections to the same file might not realize that
25751     ** the file has changed and hence might not know to flush their
25752     ** cache.  The use of a stale cache can lead to database corruption.
25753     */
25754     assert( pFile->inNormalWrite==0
25755            || pFile->dbUpdate==0
25756            || pFile->transCntrChng==1 );
25757     pFile->inNormalWrite = 0;
25758 #endif
25759     
25760     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25761       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25762       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25763         /* only re-establish the shared lock if necessary */
25764         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25765         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25766       } else {
25767         skipShared = 1;
25768       }
25769     }
25770     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25771       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25772     } 
25773     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25774       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25775       if( !rc ){ 
25776         context->reserved = 0; 
25777       }
25778     }
25779     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25780       pInode->eFileLock = SHARED_LOCK;
25781     }
25782   }
25783   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25784
25785     /* Decrement the shared lock counter.  Release the lock using an
25786     ** OS call only when all threads in this same process have released
25787     ** the lock.
25788     */
25789     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25790     pInode->nShared--;
25791     if( pInode->nShared==0 ){
25792       SimulateIOErrorBenign(1);
25793       SimulateIOError( h=(-1) )
25794       SimulateIOErrorBenign(0);
25795       if( !skipShared ){
25796         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25797       }
25798       if( !rc ){
25799         pInode->eFileLock = NO_LOCK;
25800         pFile->eFileLock = NO_LOCK;
25801       }
25802     }
25803     if( rc==SQLITE_OK ){
25804       pInode->nLock--;
25805       assert( pInode->nLock>=0 );
25806       if( pInode->nLock==0 ){
25807         closePendingFds(pFile);
25808       }
25809     }
25810   }
25811   
25812   unixLeaveMutex();
25813   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25814   return rc;
25815 }
25816
25817 /*
25818 ** Close a file & cleanup AFP specific locking context 
25819 */
25820 static int afpClose(sqlite3_file *id) {
25821   int rc = SQLITE_OK;
25822   if( id ){
25823     unixFile *pFile = (unixFile*)id;
25824     afpUnlock(id, NO_LOCK);
25825     unixEnterMutex();
25826     if( pFile->pInode && pFile->pInode->nLock ){
25827       /* If there are outstanding locks, do not actually close the file just
25828       ** yet because that would clear those locks.  Instead, add the file
25829       ** descriptor to pInode->aPending.  It will be automatically closed when
25830       ** the last lock is cleared.
25831       */
25832       setPendingFd(pFile);
25833     }
25834     releaseInodeInfo(pFile);
25835     sqlite3_free(pFile->lockingContext);
25836     rc = closeUnixFile(id);
25837     unixLeaveMutex();
25838   }
25839   return rc;
25840 }
25841
25842 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25843 /*
25844 ** The code above is the AFP lock implementation.  The code is specific
25845 ** to MacOSX and does not work on other unix platforms.  No alternative
25846 ** is available.  If you don't compile for a mac, then the "unix-afp"
25847 ** VFS is not available.
25848 **
25849 ********************* End of the AFP lock implementation **********************
25850 ******************************************************************************/
25851
25852 /******************************************************************************
25853 *************************** Begin NFS Locking ********************************/
25854
25855 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25856 /*
25857  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25858  ** must be either NO_LOCK or SHARED_LOCK.
25859  **
25860  ** If the locking level of the file descriptor is already at or below
25861  ** the requested locking level, this routine is a no-op.
25862  */
25863 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25864   return posixUnlock(id, eFileLock, 1);
25865 }
25866
25867 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25868 /*
25869 ** The code above is the NFS lock implementation.  The code is specific
25870 ** to MacOSX and does not work on other unix platforms.  No alternative
25871 ** is available.  
25872 **
25873 ********************* End of the NFS lock implementation **********************
25874 ******************************************************************************/
25875
25876 /******************************************************************************
25877 **************** Non-locking sqlite3_file methods *****************************
25878 **
25879 ** The next division contains implementations for all methods of the 
25880 ** sqlite3_file object other than the locking methods.  The locking
25881 ** methods were defined in divisions above (one locking method per
25882 ** division).  Those methods that are common to all locking modes
25883 ** are gather together into this division.
25884 */
25885
25886 /*
25887 ** Seek to the offset passed as the second argument, then read cnt 
25888 ** bytes into pBuf. Return the number of bytes actually read.
25889 **
25890 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25891 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25892 ** one system to another.  Since SQLite does not define USE_PREAD
25893 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25894 ** See tickets #2741 and #2681.
25895 **
25896 ** To avoid stomping the errno value on a failed read the lastErrno value
25897 ** is set before returning.
25898 */
25899 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25900   int got;
25901   int prior = 0;
25902 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25903   i64 newOffset;
25904 #endif
25905   TIMER_START;
25906   assert( cnt==(cnt&0x1ffff) );
25907   cnt &= 0x1ffff;
25908   do{
25909 #if defined(USE_PREAD)
25910     got = osPread(id->h, pBuf, cnt, offset);
25911     SimulateIOError( got = -1 );
25912 #elif defined(USE_PREAD64)
25913     got = osPread64(id->h, pBuf, cnt, offset);
25914     SimulateIOError( got = -1 );
25915 #else
25916     newOffset = lseek(id->h, offset, SEEK_SET);
25917     SimulateIOError( newOffset-- );
25918     if( newOffset!=offset ){
25919       if( newOffset == -1 ){
25920         ((unixFile*)id)->lastErrno = errno;
25921       }else{
25922         ((unixFile*)id)->lastErrno = 0;
25923       }
25924       return -1;
25925     }
25926     got = osRead(id->h, pBuf, cnt);
25927 #endif
25928     if( got==cnt ) break;
25929     if( got<0 ){
25930       if( errno==EINTR ){ got = 1; continue; }
25931       prior = 0;
25932       ((unixFile*)id)->lastErrno = errno;
25933       break;
25934     }else if( got>0 ){
25935       cnt -= got;
25936       offset += got;
25937       prior += got;
25938       pBuf = (void*)(got + (char*)pBuf);
25939     }
25940   }while( got>0 );
25941   TIMER_END;
25942   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
25943             id->h, got+prior, offset-prior, TIMER_ELAPSED));
25944   return got+prior;
25945 }
25946
25947 /*
25948 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25949 ** bytes were read successfully and SQLITE_IOERR if anything goes
25950 ** wrong.
25951 */
25952 static int unixRead(
25953   sqlite3_file *id, 
25954   void *pBuf, 
25955   int amt,
25956   sqlite3_int64 offset
25957 ){
25958   unixFile *pFile = (unixFile *)id;
25959   int got;
25960   assert( id );
25961
25962   /* If this is a database file (not a journal, master-journal or temp
25963   ** file), the bytes in the locking range should never be read or written. */
25964 #if 0
25965   assert( pFile->pUnused==0
25966        || offset>=PENDING_BYTE+512
25967        || offset+amt<=PENDING_BYTE 
25968   );
25969 #endif
25970
25971   got = seekAndRead(pFile, offset, pBuf, amt);
25972   if( got==amt ){
25973     return SQLITE_OK;
25974   }else if( got<0 ){
25975     /* lastErrno set by seekAndRead */
25976     return SQLITE_IOERR_READ;
25977   }else{
25978     pFile->lastErrno = 0; /* not a system error */
25979     /* Unread parts of the buffer must be zero-filled */
25980     memset(&((char*)pBuf)[got], 0, amt-got);
25981     return SQLITE_IOERR_SHORT_READ;
25982   }
25983 }
25984
25985 /*
25986 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25987 ** Return the number of bytes actually read.  Update the offset.
25988 **
25989 ** To avoid stomping the errno value on a failed write the lastErrno value
25990 ** is set before returning.
25991 */
25992 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25993   int got;
25994 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25995   i64 newOffset;
25996 #endif
25997   assert( cnt==(cnt&0x1ffff) );
25998   cnt &= 0x1ffff;
25999   TIMER_START;
26000 #if defined(USE_PREAD)
26001   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
26002 #elif defined(USE_PREAD64)
26003   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
26004 #else
26005   do{
26006     newOffset = lseek(id->h, offset, SEEK_SET);
26007     SimulateIOError( newOffset-- );
26008     if( newOffset!=offset ){
26009       if( newOffset == -1 ){
26010         ((unixFile*)id)->lastErrno = errno;
26011       }else{
26012         ((unixFile*)id)->lastErrno = 0;
26013       }
26014       return -1;
26015     }
26016     got = osWrite(id->h, pBuf, cnt);
26017   }while( got<0 && errno==EINTR );
26018 #endif
26019   TIMER_END;
26020   if( got<0 ){
26021     ((unixFile*)id)->lastErrno = errno;
26022   }
26023
26024   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
26025   return got;
26026 }
26027
26028
26029 /*
26030 ** Write data from a buffer into a file.  Return SQLITE_OK on success
26031 ** or some other error code on failure.
26032 */
26033 static int unixWrite(
26034   sqlite3_file *id, 
26035   const void *pBuf, 
26036   int amt,
26037   sqlite3_int64 offset 
26038 ){
26039   unixFile *pFile = (unixFile*)id;
26040   int wrote = 0;
26041   assert( id );
26042   assert( amt>0 );
26043
26044   /* If this is a database file (not a journal, master-journal or temp
26045   ** file), the bytes in the locking range should never be read or written. */
26046 #if 0
26047   assert( pFile->pUnused==0
26048        || offset>=PENDING_BYTE+512
26049        || offset+amt<=PENDING_BYTE 
26050   );
26051 #endif
26052
26053 #ifdef SQLITE_DEBUG
26054   /* If we are doing a normal write to a database file (as opposed to
26055   ** doing a hot-journal rollback or a write to some file other than a
26056   ** normal database file) then record the fact that the database
26057   ** has changed.  If the transaction counter is modified, record that
26058   ** fact too.
26059   */
26060   if( pFile->inNormalWrite ){
26061     pFile->dbUpdate = 1;  /* The database has been modified */
26062     if( offset<=24 && offset+amt>=27 ){
26063       int rc;
26064       char oldCntr[4];
26065       SimulateIOErrorBenign(1);
26066       rc = seekAndRead(pFile, 24, oldCntr, 4);
26067       SimulateIOErrorBenign(0);
26068       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26069         pFile->transCntrChng = 1;  /* The transaction counter has changed */
26070       }
26071     }
26072   }
26073 #endif
26074
26075   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26076     amt -= wrote;
26077     offset += wrote;
26078     pBuf = &((char*)pBuf)[wrote];
26079   }
26080   SimulateIOError(( wrote=(-1), amt=1 ));
26081   SimulateDiskfullError(( wrote=0, amt=1 ));
26082
26083   if( amt>0 ){
26084     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26085       /* lastErrno set by seekAndWrite */
26086       return SQLITE_IOERR_WRITE;
26087     }else{
26088       pFile->lastErrno = 0; /* not a system error */
26089       return SQLITE_FULL;
26090     }
26091   }
26092
26093   return SQLITE_OK;
26094 }
26095
26096 #ifdef SQLITE_TEST
26097 /*
26098 ** Count the number of fullsyncs and normal syncs.  This is used to test
26099 ** that syncs and fullsyncs are occurring at the right times.
26100 */
26101 SQLITE_API int sqlite3_sync_count = 0;
26102 SQLITE_API int sqlite3_fullsync_count = 0;
26103 #endif
26104
26105 /*
26106 ** We do not trust systems to provide a working fdatasync().  Some do.
26107 ** Others do no.  To be safe, we will stick with the (slightly slower)
26108 ** fsync(). If you know that your system does support fdatasync() correctly,
26109 ** then simply compile with -Dfdatasync=fdatasync
26110 */
26111 #if !defined(fdatasync)
26112 # define fdatasync fsync
26113 #endif
26114
26115 /*
26116 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26117 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26118 ** only available on Mac OS X.  But that could change.
26119 */
26120 #ifdef F_FULLFSYNC
26121 # define HAVE_FULLFSYNC 1
26122 #else
26123 # define HAVE_FULLFSYNC 0
26124 #endif
26125
26126
26127 /*
26128 ** The fsync() system call does not work as advertised on many
26129 ** unix systems.  The following procedure is an attempt to make
26130 ** it work better.
26131 **
26132 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26133 ** for testing when we want to run through the test suite quickly.
26134 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26135 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26136 ** or power failure will likely corrupt the database file.
26137 **
26138 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26139 ** The idea behind dataOnly is that it should only write the file content
26140 ** to disk, not the inode.  We only set dataOnly if the file size is 
26141 ** unchanged since the file size is part of the inode.  However, 
26142 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26143 ** file size has changed.  The only real difference between fdatasync()
26144 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26145 ** inode if the mtime or owner or other inode attributes have changed.
26146 ** We only care about the file size, not the other file attributes, so
26147 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26148 ** So, we always use fdatasync() if it is available, regardless of
26149 ** the value of the dataOnly flag.
26150 */
26151 static int full_fsync(int fd, int fullSync, int dataOnly){
26152   int rc;
26153
26154   /* The following "ifdef/elif/else/" block has the same structure as
26155   ** the one below. It is replicated here solely to avoid cluttering 
26156   ** up the real code with the UNUSED_PARAMETER() macros.
26157   */
26158 #ifdef SQLITE_NO_SYNC
26159   UNUSED_PARAMETER(fd);
26160   UNUSED_PARAMETER(fullSync);
26161   UNUSED_PARAMETER(dataOnly);
26162 #elif HAVE_FULLFSYNC
26163   UNUSED_PARAMETER(dataOnly);
26164 #else
26165   UNUSED_PARAMETER(fullSync);
26166   UNUSED_PARAMETER(dataOnly);
26167 #endif
26168
26169   /* Record the number of times that we do a normal fsync() and 
26170   ** FULLSYNC.  This is used during testing to verify that this procedure
26171   ** gets called with the correct arguments.
26172   */
26173 #ifdef SQLITE_TEST
26174   if( fullSync ) sqlite3_fullsync_count++;
26175   sqlite3_sync_count++;
26176 #endif
26177
26178   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26179   ** no-op
26180   */
26181 #ifdef SQLITE_NO_SYNC
26182   rc = SQLITE_OK;
26183 #elif HAVE_FULLFSYNC
26184   if( fullSync ){
26185     rc = osFcntl(fd, F_FULLFSYNC, 0);
26186   }else{
26187     rc = 1;
26188   }
26189   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26190   ** It shouldn't be possible for fullfsync to fail on the local 
26191   ** file system (on OSX), so failure indicates that FULLFSYNC
26192   ** isn't supported for this file system. So, attempt an fsync 
26193   ** and (for now) ignore the overhead of a superfluous fcntl call.  
26194   ** It'd be better to detect fullfsync support once and avoid 
26195   ** the fcntl call every time sync is called.
26196   */
26197   if( rc ) rc = fsync(fd);
26198
26199 #elif defined(__APPLE__)
26200   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26201   ** so currently we default to the macro that redefines fdatasync to fsync
26202   */
26203   rc = fsync(fd);
26204 #else 
26205   rc = fdatasync(fd);
26206 #if OS_VXWORKS
26207   if( rc==-1 && errno==ENOTSUP ){
26208     rc = fsync(fd);
26209   }
26210 #endif /* OS_VXWORKS */
26211 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26212
26213   if( OS_VXWORKS && rc!= -1 ){
26214     rc = 0;
26215   }
26216   return rc;
26217 }
26218
26219 /*
26220 ** Open a file descriptor to the directory containing file zFilename.
26221 ** If successful, *pFd is set to the opened file descriptor and
26222 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26223 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26224 ** value.
26225 **
26226 ** The directory file descriptor is used for only one thing - to
26227 ** fsync() a directory to make sure file creation and deletion events
26228 ** are flushed to disk.  Such fsyncs are not needed on newer
26229 ** journaling filesystems, but are required on older filesystems.
26230 **
26231 ** This routine can be overridden using the xSetSysCall interface.
26232 ** The ability to override this routine was added in support of the
26233 ** chromium sandbox.  Opening a directory is a security risk (we are
26234 ** told) so making it overrideable allows the chromium sandbox to
26235 ** replace this routine with a harmless no-op.  To make this routine
26236 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26237 ** *pFd set to a negative number.
26238 **
26239 ** If SQLITE_OK is returned, the caller is responsible for closing
26240 ** the file descriptor *pFd using close().
26241 */
26242 static int openDirectory(const char *zFilename, int *pFd){
26243   int ii;
26244   int fd = -1;
26245   char zDirname[MAX_PATHNAME+1];
26246
26247   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26248   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26249   if( ii>0 ){
26250     zDirname[ii] = '\0';
26251     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26252     if( fd>=0 ){
26253       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26254     }
26255   }
26256   *pFd = fd;
26257   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26258 }
26259
26260 /*
26261 ** Make sure all writes to a particular file are committed to disk.
26262 **
26263 ** If dataOnly==0 then both the file itself and its metadata (file
26264 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26265 ** file data is synced.
26266 **
26267 ** Under Unix, also make sure that the directory entry for the file
26268 ** has been created by fsync-ing the directory that contains the file.
26269 ** If we do not do this and we encounter a power failure, the directory
26270 ** entry for the journal might not exist after we reboot.  The next
26271 ** SQLite to access the file will not know that the journal exists (because
26272 ** the directory entry for the journal was never created) and the transaction
26273 ** will not roll back - possibly leading to database corruption.
26274 */
26275 static int unixSync(sqlite3_file *id, int flags){
26276   int rc;
26277   unixFile *pFile = (unixFile*)id;
26278
26279   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26280   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26281
26282   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26283   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26284       || (flags&0x0F)==SQLITE_SYNC_FULL
26285   );
26286
26287   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26288   ** line is to test that doing so does not cause any problems.
26289   */
26290   SimulateDiskfullError( return SQLITE_FULL );
26291
26292   assert( pFile );
26293   OSTRACE(("SYNC    %-3d\n", pFile->h));
26294   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26295   SimulateIOError( rc=1 );
26296   if( rc ){
26297     pFile->lastErrno = errno;
26298     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26299   }
26300
26301   /* Also fsync the directory containing the file if the DIRSYNC flag
26302   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
26303   ** are unable to fsync a directory, so ignore errors on the fsync.
26304   */
26305   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26306     int dirfd;
26307     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26308             HAVE_FULLFSYNC, isFullsync));
26309     rc = osOpenDirectory(pFile->zPath, &dirfd);
26310     if( rc==SQLITE_OK && dirfd>=0 ){
26311       full_fsync(dirfd, 0, 0);
26312       robust_close(pFile, dirfd, __LINE__);
26313     }else if( rc==SQLITE_CANTOPEN ){
26314       rc = SQLITE_OK;
26315     }
26316     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26317   }
26318   return rc;
26319 }
26320
26321 /*
26322 ** Truncate an open file to a specified size
26323 */
26324 static int unixTruncate(sqlite3_file *id, i64 nByte){
26325   unixFile *pFile = (unixFile *)id;
26326   int rc;
26327   assert( pFile );
26328   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26329
26330   /* If the user has configured a chunk-size for this file, truncate the
26331   ** file so that it consists of an integer number of chunks (i.e. the
26332   ** actual file size after the operation may be larger than the requested
26333   ** size).
26334   */
26335   if( pFile->szChunk>0 ){
26336     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26337   }
26338
26339   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26340   if( rc ){
26341     pFile->lastErrno = errno;
26342     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26343   }else{
26344 #ifdef SQLITE_DEBUG
26345     /* If we are doing a normal write to a database file (as opposed to
26346     ** doing a hot-journal rollback or a write to some file other than a
26347     ** normal database file) and we truncate the file to zero length,
26348     ** that effectively updates the change counter.  This might happen
26349     ** when restoring a database using the backup API from a zero-length
26350     ** source.
26351     */
26352     if( pFile->inNormalWrite && nByte==0 ){
26353       pFile->transCntrChng = 1;
26354     }
26355 #endif
26356
26357     return SQLITE_OK;
26358   }
26359 }
26360
26361 /*
26362 ** Determine the current size of a file in bytes
26363 */
26364 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26365   int rc;
26366   struct stat buf;
26367   assert( id );
26368   rc = osFstat(((unixFile*)id)->h, &buf);
26369   SimulateIOError( rc=1 );
26370   if( rc!=0 ){
26371     ((unixFile*)id)->lastErrno = errno;
26372     return SQLITE_IOERR_FSTAT;
26373   }
26374   *pSize = buf.st_size;
26375
26376   /* When opening a zero-size database, the findInodeInfo() procedure
26377   ** writes a single byte into that file in order to work around a bug
26378   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26379   ** layers, we need to report this file size as zero even though it is
26380   ** really 1.   Ticket #3260.
26381   */
26382   if( *pSize==1 ) *pSize = 0;
26383
26384
26385   return SQLITE_OK;
26386 }
26387
26388 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26389 /*
26390 ** Handler for proxy-locking file-control verbs.  Defined below in the
26391 ** proxying locking division.
26392 */
26393 static int proxyFileControl(sqlite3_file*,int,void*);
26394 #endif
26395
26396 /* 
26397 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26398 ** file-control operation.  Enlarge the database to nBytes in size
26399 ** (rounded up to the next chunk-size).  If the database is already
26400 ** nBytes or larger, this routine is a no-op.
26401 */
26402 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26403   if( pFile->szChunk>0 ){
26404     i64 nSize;                    /* Required file size */
26405     struct stat buf;              /* Used to hold return values of fstat() */
26406    
26407     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26408
26409     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26410     if( nSize>(i64)buf.st_size ){
26411
26412 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26413       /* The code below is handling the return value of osFallocate() 
26414       ** correctly. posix_fallocate() is defined to "returns zero on success, 
26415       ** or an error number on  failure". See the manpage for details. */
26416       int err;
26417       do{
26418         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26419       }while( err==EINTR );
26420       if( err ) return SQLITE_IOERR_WRITE;
26421 #else
26422       /* If the OS does not have posix_fallocate(), fake it. First use
26423       ** ftruncate() to set the file size, then write a single byte to
26424       ** the last byte in each block within the extended region. This
26425       ** is the same technique used by glibc to implement posix_fallocate()
26426       ** on systems that do not have a real fallocate() system call.
26427       */
26428       int nBlk = buf.st_blksize;  /* File-system block size */
26429       i64 iWrite;                 /* Next offset to write to */
26430
26431       if( robust_ftruncate(pFile->h, nSize) ){
26432         pFile->lastErrno = errno;
26433         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26434       }
26435       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26436       while( iWrite<nSize ){
26437         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26438         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26439         iWrite += nBlk;
26440       }
26441 #endif
26442     }
26443   }
26444
26445   return SQLITE_OK;
26446 }
26447
26448 /*
26449 ** If *pArg is inititially negative then this is a query.  Set *pArg to
26450 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26451 **
26452 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26453 */
26454 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26455   if( *pArg<0 ){
26456     *pArg = (pFile->ctrlFlags & mask)!=0;
26457   }else if( (*pArg)==0 ){
26458     pFile->ctrlFlags &= ~mask;
26459   }else{
26460     pFile->ctrlFlags |= mask;
26461   }
26462 }
26463
26464 /* Forward declaration */
26465 static int unixGetTempname(int nBuf, char *zBuf);
26466
26467 /*
26468 ** Information and control of an open file handle.
26469 */
26470 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26471   unixFile *pFile = (unixFile*)id;
26472   switch( op ){
26473     case SQLITE_FCNTL_LOCKSTATE: {
26474       *(int*)pArg = pFile->eFileLock;
26475       return SQLITE_OK;
26476     }
26477     case SQLITE_LAST_ERRNO: {
26478       *(int*)pArg = pFile->lastErrno;
26479       return SQLITE_OK;
26480     }
26481     case SQLITE_FCNTL_CHUNK_SIZE: {
26482       pFile->szChunk = *(int *)pArg;
26483       return SQLITE_OK;
26484     }
26485     case SQLITE_FCNTL_SIZE_HINT: {
26486       int rc;
26487       SimulateIOErrorBenign(1);
26488       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26489       SimulateIOErrorBenign(0);
26490       return rc;
26491     }
26492     case SQLITE_FCNTL_PERSIST_WAL: {
26493       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26494       return SQLITE_OK;
26495     }
26496     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26497       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26498       return SQLITE_OK;
26499     }
26500     case SQLITE_FCNTL_VFSNAME: {
26501       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26502       return SQLITE_OK;
26503     }
26504     case SQLITE_FCNTL_TEMPFILENAME: {
26505       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26506       if( zTFile ){
26507         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26508         *(char**)pArg = zTFile;
26509       }
26510       return SQLITE_OK;
26511     }
26512 #ifdef SQLITE_DEBUG
26513     /* The pager calls this method to signal that it has done
26514     ** a rollback and that the database is therefore unchanged and
26515     ** it hence it is OK for the transaction change counter to be
26516     ** unchanged.
26517     */
26518     case SQLITE_FCNTL_DB_UNCHANGED: {
26519       ((unixFile*)id)->dbUpdate = 0;
26520       return SQLITE_OK;
26521     }
26522 #endif
26523 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26524     case SQLITE_SET_LOCKPROXYFILE:
26525     case SQLITE_GET_LOCKPROXYFILE: {
26526       return proxyFileControl(id,op,pArg);
26527     }
26528 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26529   }
26530   return SQLITE_NOTFOUND;
26531 }
26532
26533 /*
26534 ** Return the sector size in bytes of the underlying block device for
26535 ** the specified file. This is almost always 512 bytes, but may be
26536 ** larger for some devices.
26537 **
26538 ** SQLite code assumes this function cannot fail. It also assumes that
26539 ** if two files are created in the same file-system directory (i.e.
26540 ** a database and its journal file) that the sector size will be the
26541 ** same for both.
26542 */
26543 #ifndef __QNXNTO__ 
26544 static int unixSectorSize(sqlite3_file *NotUsed){
26545   UNUSED_PARAMETER(NotUsed);
26546   return SQLITE_DEFAULT_SECTOR_SIZE;
26547 }
26548 #endif
26549
26550 /*
26551 ** The following version of unixSectorSize() is optimized for QNX.
26552 */
26553 #ifdef __QNXNTO__
26554 #include <sys/dcmd_blk.h>
26555 #include <sys/statvfs.h>
26556 static int unixSectorSize(sqlite3_file *id){
26557   unixFile *pFile = (unixFile*)id;
26558   if( pFile->sectorSize == 0 ){
26559     struct statvfs fsInfo;
26560        
26561     /* Set defaults for non-supported filesystems */
26562     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26563     pFile->deviceCharacteristics = 0;
26564     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26565       return pFile->sectorSize;
26566     }
26567
26568     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26569       pFile->sectorSize = fsInfo.f_bsize;
26570       pFile->deviceCharacteristics =
26571         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
26572         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26573                                       ** the write succeeds */
26574         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26575                                       ** so it is ordered */
26576         0;
26577     }else if( strstr(fsInfo.f_basetype, "etfs") ){
26578       pFile->sectorSize = fsInfo.f_bsize;
26579       pFile->deviceCharacteristics =
26580         /* etfs cluster size writes are atomic */
26581         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26582         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26583                                       ** the write succeeds */
26584         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26585                                       ** so it is ordered */
26586         0;
26587     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26588       pFile->sectorSize = fsInfo.f_bsize;
26589       pFile->deviceCharacteristics =
26590         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
26591         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26592                                       ** the write succeeds */
26593         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26594                                       ** so it is ordered */
26595         0;
26596     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26597       pFile->sectorSize = fsInfo.f_bsize;
26598       pFile->deviceCharacteristics =
26599         /* full bitset of atomics from max sector size and smaller */
26600         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26601         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26602                                       ** so it is ordered */
26603         0;
26604     }else if( strstr(fsInfo.f_basetype, "dos") ){
26605       pFile->sectorSize = fsInfo.f_bsize;
26606       pFile->deviceCharacteristics =
26607         /* full bitset of atomics from max sector size and smaller */
26608         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26609         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26610                                       ** so it is ordered */
26611         0;
26612     }else{
26613       pFile->deviceCharacteristics =
26614         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
26615         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26616                                       ** the write succeeds */
26617         0;
26618     }
26619   }
26620   /* Last chance verification.  If the sector size isn't a multiple of 512
26621   ** then it isn't valid.*/
26622   if( pFile->sectorSize % 512 != 0 ){
26623     pFile->deviceCharacteristics = 0;
26624     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26625   }
26626   return pFile->sectorSize;
26627 }
26628 #endif /* __QNXNTO__ */
26629
26630 /*
26631 ** Return the device characteristics for the file.
26632 **
26633 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
26634 ** However, that choice is contraversial since technically the underlying
26635 ** file system does not always provide powersafe overwrites.  (In other
26636 ** words, after a power-loss event, parts of the file that were never
26637 ** written might end up being altered.)  However, non-PSOW behavior is very,
26638 ** very rare.  And asserting PSOW makes a large reduction in the amount
26639 ** of required I/O for journaling, since a lot of padding is eliminated.
26640 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
26641 ** available to turn it off and URI query parameter available to turn it off.
26642 */
26643 static int unixDeviceCharacteristics(sqlite3_file *id){
26644   unixFile *p = (unixFile*)id;
26645   int rc = 0;
26646 #ifdef __QNXNTO__
26647   if( p->sectorSize==0 ) unixSectorSize(id);
26648   rc = p->deviceCharacteristics;
26649 #endif
26650   if( p->ctrlFlags & UNIXFILE_PSOW ){
26651     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
26652   }
26653   return rc;
26654 }
26655
26656 #ifndef SQLITE_OMIT_WAL
26657
26658
26659 /*
26660 ** Object used to represent an shared memory buffer.  
26661 **
26662 ** When multiple threads all reference the same wal-index, each thread
26663 ** has its own unixShm object, but they all point to a single instance
26664 ** of this unixShmNode object.  In other words, each wal-index is opened
26665 ** only once per process.
26666 **
26667 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26668 ** We could coalesce this object into unixInodeInfo, but that would mean
26669 ** every open file that does not use shared memory (in other words, most
26670 ** open files) would have to carry around this extra information.  So
26671 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26672 ** and the unixShmNode object is created only when needed.
26673 **
26674 ** unixMutexHeld() must be true when creating or destroying
26675 ** this object or while reading or writing the following fields:
26676 **
26677 **      nRef
26678 **
26679 ** The following fields are read-only after the object is created:
26680 ** 
26681 **      fid
26682 **      zFilename
26683 **
26684 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26685 ** unixMutexHeld() is true when reading or writing any other field
26686 ** in this structure.
26687 */
26688 struct unixShmNode {
26689   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26690   sqlite3_mutex *mutex;      /* Mutex to access this object */
26691   char *zFilename;           /* Name of the mmapped file */
26692   int h;                     /* Open file descriptor */
26693   int szRegion;              /* Size of shared-memory regions */
26694   u16 nRegion;               /* Size of array apRegion */
26695   u8 isReadonly;             /* True if read-only */
26696   char **apRegion;           /* Array of mapped shared-memory regions */
26697   int nRef;                  /* Number of unixShm objects pointing to this */
26698   unixShm *pFirst;           /* All unixShm objects pointing to this */
26699 #ifdef SQLITE_DEBUG
26700   u8 exclMask;               /* Mask of exclusive locks held */
26701   u8 sharedMask;             /* Mask of shared locks held */
26702   u8 nextShmId;              /* Next available unixShm.id value */
26703 #endif
26704 };
26705
26706 /*
26707 ** Structure used internally by this VFS to record the state of an
26708 ** open shared memory connection.
26709 **
26710 ** The following fields are initialized when this object is created and
26711 ** are read-only thereafter:
26712 **
26713 **    unixShm.pFile
26714 **    unixShm.id
26715 **
26716 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26717 ** while accessing any read/write fields.
26718 */
26719 struct unixShm {
26720   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26721   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26722   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26723   u8 id;                     /* Id of this connection within its unixShmNode */
26724   u16 sharedMask;            /* Mask of shared locks held */
26725   u16 exclMask;              /* Mask of exclusive locks held */
26726 };
26727
26728 /*
26729 ** Constants used for locking
26730 */
26731 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26732 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26733
26734 /*
26735 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26736 **
26737 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26738 ** otherwise.
26739 */
26740 static int unixShmSystemLock(
26741   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26742   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26743   int ofst,              /* First byte of the locking range */
26744   int n                  /* Number of bytes to lock */
26745 ){
26746   struct flock f;       /* The posix advisory locking structure */
26747   int rc = SQLITE_OK;   /* Result code form fcntl() */
26748
26749   /* Access to the unixShmNode object is serialized by the caller */
26750   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26751
26752   /* Shared locks never span more than one byte */
26753   assert( n==1 || lockType!=F_RDLCK );
26754
26755   /* Locks are within range */
26756   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26757
26758   if( pShmNode->h>=0 ){
26759     /* Initialize the locking parameters */
26760     memset(&f, 0, sizeof(f));
26761     f.l_type = lockType;
26762     f.l_whence = SEEK_SET;
26763     f.l_start = ofst;
26764     f.l_len = n;
26765
26766     rc = osFcntl(pShmNode->h, F_SETLK, &f);
26767     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26768   }
26769
26770   /* Update the global lock state and do debug tracing */
26771 #ifdef SQLITE_DEBUG
26772   { u16 mask;
26773   OSTRACE(("SHM-LOCK "));
26774   mask = (1<<(ofst+n)) - (1<<ofst);
26775   if( rc==SQLITE_OK ){
26776     if( lockType==F_UNLCK ){
26777       OSTRACE(("unlock %d ok", ofst));
26778       pShmNode->exclMask &= ~mask;
26779       pShmNode->sharedMask &= ~mask;
26780     }else if( lockType==F_RDLCK ){
26781       OSTRACE(("read-lock %d ok", ofst));
26782       pShmNode->exclMask &= ~mask;
26783       pShmNode->sharedMask |= mask;
26784     }else{
26785       assert( lockType==F_WRLCK );
26786       OSTRACE(("write-lock %d ok", ofst));
26787       pShmNode->exclMask |= mask;
26788       pShmNode->sharedMask &= ~mask;
26789     }
26790   }else{
26791     if( lockType==F_UNLCK ){
26792       OSTRACE(("unlock %d failed", ofst));
26793     }else if( lockType==F_RDLCK ){
26794       OSTRACE(("read-lock failed"));
26795     }else{
26796       assert( lockType==F_WRLCK );
26797       OSTRACE(("write-lock %d failed", ofst));
26798     }
26799   }
26800   OSTRACE((" - afterwards %03x,%03x\n",
26801            pShmNode->sharedMask, pShmNode->exclMask));
26802   }
26803 #endif
26804
26805   return rc;        
26806 }
26807
26808
26809 /*
26810 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26811 **
26812 ** This is not a VFS shared-memory method; it is a utility function called
26813 ** by VFS shared-memory methods.
26814 */
26815 static void unixShmPurge(unixFile *pFd){
26816   unixShmNode *p = pFd->pInode->pShmNode;
26817   assert( unixMutexHeld() );
26818   if( p && p->nRef==0 ){
26819     int i;
26820     assert( p->pInode==pFd->pInode );
26821     sqlite3_mutex_free(p->mutex);
26822     for(i=0; i<p->nRegion; i++){
26823       if( p->h>=0 ){
26824         munmap(p->apRegion[i], p->szRegion);
26825       }else{
26826         sqlite3_free(p->apRegion[i]);
26827       }
26828     }
26829     sqlite3_free(p->apRegion);
26830     if( p->h>=0 ){
26831       robust_close(pFd, p->h, __LINE__);
26832       p->h = -1;
26833     }
26834     p->pInode->pShmNode = 0;
26835     sqlite3_free(p);
26836   }
26837 }
26838
26839 /*
26840 ** Open a shared-memory area associated with open database file pDbFd.  
26841 ** This particular implementation uses mmapped files.
26842 **
26843 ** The file used to implement shared-memory is in the same directory
26844 ** as the open database file and has the same name as the open database
26845 ** file with the "-shm" suffix added.  For example, if the database file
26846 ** is "/home/user1/config.db" then the file that is created and mmapped
26847 ** for shared memory will be called "/home/user1/config.db-shm".  
26848 **
26849 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26850 ** some other tmpfs mount. But if a file in a different directory
26851 ** from the database file is used, then differing access permissions
26852 ** or a chroot() might cause two different processes on the same
26853 ** database to end up using different files for shared memory - 
26854 ** meaning that their memory would not really be shared - resulting
26855 ** in database corruption.  Nevertheless, this tmpfs file usage
26856 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26857 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26858 ** option results in an incompatible build of SQLite;  builds of SQLite
26859 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26860 ** same database file at the same time, database corruption will likely
26861 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26862 ** "unsupported" and may go away in a future SQLite release.
26863 **
26864 ** When opening a new shared-memory file, if no other instances of that
26865 ** file are currently open, in this process or in other processes, then
26866 ** the file must be truncated to zero length or have its header cleared.
26867 **
26868 ** If the original database file (pDbFd) is using the "unix-excl" VFS
26869 ** that means that an exclusive lock is held on the database file and
26870 ** that no other processes are able to read or write the database.  In
26871 ** that case, we do not really need shared memory.  No shared memory
26872 ** file is created.  The shared memory will be simulated with heap memory.
26873 */
26874 static int unixOpenSharedMemory(unixFile *pDbFd){
26875   struct unixShm *p = 0;          /* The connection to be opened */
26876   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26877   int rc;                         /* Result code */
26878   unixInodeInfo *pInode;          /* The inode of fd */
26879   char *zShmFilename;             /* Name of the file used for SHM */
26880   int nShmFilename;               /* Size of the SHM filename in bytes */
26881
26882   /* Allocate space for the new unixShm object. */
26883   p = sqlite3_malloc( sizeof(*p) );
26884   if( p==0 ) return SQLITE_NOMEM;
26885   memset(p, 0, sizeof(*p));
26886   assert( pDbFd->pShm==0 );
26887
26888   /* Check to see if a unixShmNode object already exists. Reuse an existing
26889   ** one if present. Create a new one if necessary.
26890   */
26891   unixEnterMutex();
26892   pInode = pDbFd->pInode;
26893   pShmNode = pInode->pShmNode;
26894   if( pShmNode==0 ){
26895     struct stat sStat;                 /* fstat() info for database file */
26896
26897     /* Call fstat() to figure out the permissions on the database file. If
26898     ** a new *-shm file is created, an attempt will be made to create it
26899     ** with the same permissions.
26900     */
26901     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
26902       rc = SQLITE_IOERR_FSTAT;
26903       goto shm_open_err;
26904     }
26905
26906 #ifdef SQLITE_SHM_DIRECTORY
26907     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
26908 #else
26909     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
26910 #endif
26911     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26912     if( pShmNode==0 ){
26913       rc = SQLITE_NOMEM;
26914       goto shm_open_err;
26915     }
26916     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
26917     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26918 #ifdef SQLITE_SHM_DIRECTORY
26919     sqlite3_snprintf(nShmFilename, zShmFilename, 
26920                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26921                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26922 #else
26923     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26924     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
26925 #endif
26926     pShmNode->h = -1;
26927     pDbFd->pInode->pShmNode = pShmNode;
26928     pShmNode->pInode = pDbFd->pInode;
26929     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26930     if( pShmNode->mutex==0 ){
26931       rc = SQLITE_NOMEM;
26932       goto shm_open_err;
26933     }
26934
26935     if( pInode->bProcessLock==0 ){
26936       int openFlags = O_RDWR | O_CREAT;
26937       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
26938         openFlags = O_RDONLY;
26939         pShmNode->isReadonly = 1;
26940       }
26941       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
26942       if( pShmNode->h<0 ){
26943         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
26944         goto shm_open_err;
26945       }
26946
26947       /* If this process is running as root, make sure that the SHM file
26948       ** is owned by the same user that owns the original database.  Otherwise,
26949       ** the original owner will not be able to connect.
26950       */
26951       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
26952   
26953       /* Check to see if another process is holding the dead-man switch.
26954       ** If not, truncate the file to zero length. 
26955       */
26956       rc = SQLITE_OK;
26957       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26958         if( robust_ftruncate(pShmNode->h, 0) ){
26959           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
26960         }
26961       }
26962       if( rc==SQLITE_OK ){
26963         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26964       }
26965       if( rc ) goto shm_open_err;
26966     }
26967   }
26968
26969   /* Make the new connection a child of the unixShmNode */
26970   p->pShmNode = pShmNode;
26971 #ifdef SQLITE_DEBUG
26972   p->id = pShmNode->nextShmId++;
26973 #endif
26974   pShmNode->nRef++;
26975   pDbFd->pShm = p;
26976   unixLeaveMutex();
26977
26978   /* The reference count on pShmNode has already been incremented under
26979   ** the cover of the unixEnterMutex() mutex and the pointer from the
26980   ** new (struct unixShm) object to the pShmNode has been set. All that is
26981   ** left to do is to link the new object into the linked list starting
26982   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26983   ** mutex.
26984   */
26985   sqlite3_mutex_enter(pShmNode->mutex);
26986   p->pNext = pShmNode->pFirst;
26987   pShmNode->pFirst = p;
26988   sqlite3_mutex_leave(pShmNode->mutex);
26989   return SQLITE_OK;
26990
26991   /* Jump here on any error */
26992 shm_open_err:
26993   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26994   sqlite3_free(p);
26995   unixLeaveMutex();
26996   return rc;
26997 }
26998
26999 /*
27000 ** This function is called to obtain a pointer to region iRegion of the 
27001 ** shared-memory associated with the database file fd. Shared-memory regions 
27002 ** are numbered starting from zero. Each shared-memory region is szRegion 
27003 ** bytes in size.
27004 **
27005 ** If an error occurs, an error code is returned and *pp is set to NULL.
27006 **
27007 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27008 ** region has not been allocated (by any client, including one running in a
27009 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27010 ** bExtend is non-zero and the requested shared-memory region has not yet 
27011 ** been allocated, it is allocated by this function.
27012 **
27013 ** If the shared-memory region has already been allocated or is allocated by
27014 ** this call as described above, then it is mapped into this processes 
27015 ** address space (if it is not already), *pp is set to point to the mapped 
27016 ** memory and SQLITE_OK returned.
27017 */
27018 static int unixShmMap(
27019   sqlite3_file *fd,               /* Handle open on database file */
27020   int iRegion,                    /* Region to retrieve */
27021   int szRegion,                   /* Size of regions */
27022   int bExtend,                    /* True to extend file if necessary */
27023   void volatile **pp              /* OUT: Mapped memory */
27024 ){
27025   unixFile *pDbFd = (unixFile*)fd;
27026   unixShm *p;
27027   unixShmNode *pShmNode;
27028   int rc = SQLITE_OK;
27029
27030   /* If the shared-memory file has not yet been opened, open it now. */
27031   if( pDbFd->pShm==0 ){
27032     rc = unixOpenSharedMemory(pDbFd);
27033     if( rc!=SQLITE_OK ) return rc;
27034   }
27035
27036   p = pDbFd->pShm;
27037   pShmNode = p->pShmNode;
27038   sqlite3_mutex_enter(pShmNode->mutex);
27039   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27040   assert( pShmNode->pInode==pDbFd->pInode );
27041   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27042   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27043
27044   if( pShmNode->nRegion<=iRegion ){
27045     char **apNew;                      /* New apRegion[] array */
27046     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27047     struct stat sStat;                 /* Used by fstat() */
27048
27049     pShmNode->szRegion = szRegion;
27050
27051     if( pShmNode->h>=0 ){
27052       /* The requested region is not mapped into this processes address space.
27053       ** Check to see if it has been allocated (i.e. if the wal-index file is
27054       ** large enough to contain the requested region).
27055       */
27056       if( osFstat(pShmNode->h, &sStat) ){
27057         rc = SQLITE_IOERR_SHMSIZE;
27058         goto shmpage_out;
27059       }
27060   
27061       if( sStat.st_size<nByte ){
27062         /* The requested memory region does not exist. If bExtend is set to
27063         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27064         **
27065         ** Alternatively, if bExtend is true, use ftruncate() to allocate
27066         ** the requested memory region.
27067         */
27068         if( !bExtend ) goto shmpage_out;
27069 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27070         if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
27071           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
27072                             pShmNode->zFilename);
27073           goto shmpage_out;
27074         }
27075 #else
27076         if( robust_ftruncate(pShmNode->h, nByte) ){
27077           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
27078                             pShmNode->zFilename);
27079           goto shmpage_out;
27080         }
27081 #endif
27082       }
27083     }
27084
27085     /* Map the requested memory region into this processes address space. */
27086     apNew = (char **)sqlite3_realloc(
27087         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27088     );
27089     if( !apNew ){
27090       rc = SQLITE_IOERR_NOMEM;
27091       goto shmpage_out;
27092     }
27093     pShmNode->apRegion = apNew;
27094     while(pShmNode->nRegion<=iRegion){
27095       void *pMem;
27096       if( pShmNode->h>=0 ){
27097         pMem = mmap(0, szRegion,
27098             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
27099             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27100         );
27101         if( pMem==MAP_FAILED ){
27102           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27103           goto shmpage_out;
27104         }
27105       }else{
27106         pMem = sqlite3_malloc(szRegion);
27107         if( pMem==0 ){
27108           rc = SQLITE_NOMEM;
27109           goto shmpage_out;
27110         }
27111         memset(pMem, 0, szRegion);
27112       }
27113       pShmNode->apRegion[pShmNode->nRegion] = pMem;
27114       pShmNode->nRegion++;
27115     }
27116   }
27117
27118 shmpage_out:
27119   if( pShmNode->nRegion>iRegion ){
27120     *pp = pShmNode->apRegion[iRegion];
27121   }else{
27122     *pp = 0;
27123   }
27124   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27125   sqlite3_mutex_leave(pShmNode->mutex);
27126   return rc;
27127 }
27128
27129 /*
27130 ** Change the lock state for a shared-memory segment.
27131 **
27132 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27133 ** different here than in posix.  In xShmLock(), one can go from unlocked
27134 ** to shared and back or from unlocked to exclusive and back.  But one may
27135 ** not go from shared to exclusive or from exclusive to shared.
27136 */
27137 static int unixShmLock(
27138   sqlite3_file *fd,          /* Database file holding the shared memory */
27139   int ofst,                  /* First lock to acquire or release */
27140   int n,                     /* Number of locks to acquire or release */
27141   int flags                  /* What to do with the lock */
27142 ){
27143   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27144   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27145   unixShm *pX;                          /* For looping over all siblings */
27146   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27147   int rc = SQLITE_OK;                   /* Result code */
27148   u16 mask;                             /* Mask of locks to take or release */
27149
27150   assert( pShmNode==pDbFd->pInode->pShmNode );
27151   assert( pShmNode->pInode==pDbFd->pInode );
27152   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27153   assert( n>=1 );
27154   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27155        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27156        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27157        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27158   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27159   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27160   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27161
27162   mask = (1<<(ofst+n)) - (1<<ofst);
27163   assert( n>1 || mask==(1<<ofst) );
27164   sqlite3_mutex_enter(pShmNode->mutex);
27165   if( flags & SQLITE_SHM_UNLOCK ){
27166     u16 allMask = 0; /* Mask of locks held by siblings */
27167
27168     /* See if any siblings hold this same lock */
27169     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27170       if( pX==p ) continue;
27171       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27172       allMask |= pX->sharedMask;
27173     }
27174
27175     /* Unlock the system-level locks */
27176     if( (mask & allMask)==0 ){
27177       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27178     }else{
27179       rc = SQLITE_OK;
27180     }
27181
27182     /* Undo the local locks */
27183     if( rc==SQLITE_OK ){
27184       p->exclMask &= ~mask;
27185       p->sharedMask &= ~mask;
27186     } 
27187   }else if( flags & SQLITE_SHM_SHARED ){
27188     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27189
27190     /* Find out which shared locks are already held by sibling connections.
27191     ** If any sibling already holds an exclusive lock, go ahead and return
27192     ** SQLITE_BUSY.
27193     */
27194     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27195       if( (pX->exclMask & mask)!=0 ){
27196         rc = SQLITE_BUSY;
27197         break;
27198       }
27199       allShared |= pX->sharedMask;
27200     }
27201
27202     /* Get shared locks at the system level, if necessary */
27203     if( rc==SQLITE_OK ){
27204       if( (allShared & mask)==0 ){
27205         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27206       }else{
27207         rc = SQLITE_OK;
27208       }
27209     }
27210
27211     /* Get the local shared locks */
27212     if( rc==SQLITE_OK ){
27213       p->sharedMask |= mask;
27214     }
27215   }else{
27216     /* Make sure no sibling connections hold locks that will block this
27217     ** lock.  If any do, return SQLITE_BUSY right away.
27218     */
27219     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27220       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27221         rc = SQLITE_BUSY;
27222         break;
27223       }
27224     }
27225   
27226     /* Get the exclusive locks at the system level.  Then if successful
27227     ** also mark the local connection as being locked.
27228     */
27229     if( rc==SQLITE_OK ){
27230       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27231       if( rc==SQLITE_OK ){
27232         assert( (p->sharedMask & mask)==0 );
27233         p->exclMask |= mask;
27234       }
27235     }
27236   }
27237   sqlite3_mutex_leave(pShmNode->mutex);
27238   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27239            p->id, getpid(), p->sharedMask, p->exclMask));
27240   return rc;
27241 }
27242
27243 /*
27244 ** Implement a memory barrier or memory fence on shared memory.  
27245 **
27246 ** All loads and stores begun before the barrier must complete before
27247 ** any load or store begun after the barrier.
27248 */
27249 static void unixShmBarrier(
27250   sqlite3_file *fd                /* Database file holding the shared memory */
27251 ){
27252   UNUSED_PARAMETER(fd);
27253   unixEnterMutex();
27254   unixLeaveMutex();
27255 }
27256
27257 /*
27258 ** Close a connection to shared-memory.  Delete the underlying 
27259 ** storage if deleteFlag is true.
27260 **
27261 ** If there is no shared memory associated with the connection then this
27262 ** routine is a harmless no-op.
27263 */
27264 static int unixShmUnmap(
27265   sqlite3_file *fd,               /* The underlying database file */
27266   int deleteFlag                  /* Delete shared-memory if true */
27267 ){
27268   unixShm *p;                     /* The connection to be closed */
27269   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27270   unixShm **pp;                   /* For looping over sibling connections */
27271   unixFile *pDbFd;                /* The underlying database file */
27272
27273   pDbFd = (unixFile*)fd;
27274   p = pDbFd->pShm;
27275   if( p==0 ) return SQLITE_OK;
27276   pShmNode = p->pShmNode;
27277
27278   assert( pShmNode==pDbFd->pInode->pShmNode );
27279   assert( pShmNode->pInode==pDbFd->pInode );
27280
27281   /* Remove connection p from the set of connections associated
27282   ** with pShmNode */
27283   sqlite3_mutex_enter(pShmNode->mutex);
27284   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27285   *pp = p->pNext;
27286
27287   /* Free the connection p */
27288   sqlite3_free(p);
27289   pDbFd->pShm = 0;
27290   sqlite3_mutex_leave(pShmNode->mutex);
27291
27292   /* If pShmNode->nRef has reached 0, then close the underlying
27293   ** shared-memory file, too */
27294   unixEnterMutex();
27295   assert( pShmNode->nRef>0 );
27296   pShmNode->nRef--;
27297   if( pShmNode->nRef==0 ){
27298     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27299     unixShmPurge(pDbFd);
27300   }
27301   unixLeaveMutex();
27302
27303   return SQLITE_OK;
27304 }
27305
27306
27307 #else
27308 # define unixShmMap     0
27309 # define unixShmLock    0
27310 # define unixShmBarrier 0
27311 # define unixShmUnmap   0
27312 #endif /* #ifndef SQLITE_OMIT_WAL */
27313
27314 /*
27315 ** Here ends the implementation of all sqlite3_file methods.
27316 **
27317 ********************** End sqlite3_file Methods *******************************
27318 ******************************************************************************/
27319
27320 /*
27321 ** This division contains definitions of sqlite3_io_methods objects that
27322 ** implement various file locking strategies.  It also contains definitions
27323 ** of "finder" functions.  A finder-function is used to locate the appropriate
27324 ** sqlite3_io_methods object for a particular database file.  The pAppData
27325 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27326 ** the correct finder-function for that VFS.
27327 **
27328 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27329 ** object.  The only interesting finder-function is autolockIoFinder, which
27330 ** looks at the filesystem type and tries to guess the best locking
27331 ** strategy from that.
27332 **
27333 ** For finder-funtion F, two objects are created:
27334 **
27335 **    (1) The real finder-function named "FImpt()".
27336 **
27337 **    (2) A constant pointer to this function named just "F".
27338 **
27339 **
27340 ** A pointer to the F pointer is used as the pAppData value for VFS
27341 ** objects.  We have to do this instead of letting pAppData point
27342 ** directly at the finder-function since C90 rules prevent a void*
27343 ** from be cast into a function pointer.
27344 **
27345 **
27346 ** Each instance of this macro generates two objects:
27347 **
27348 **   *  A constant sqlite3_io_methods object call METHOD that has locking
27349 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27350 **
27351 **   *  An I/O method finder function called FINDER that returns a pointer
27352 **      to the METHOD object in the previous bullet.
27353 */
27354 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27355 static const sqlite3_io_methods METHOD = {                                   \
27356    VERSION,                    /* iVersion */                                \
27357    CLOSE,                      /* xClose */                                  \
27358    unixRead,                   /* xRead */                                   \
27359    unixWrite,                  /* xWrite */                                  \
27360    unixTruncate,               /* xTruncate */                               \
27361    unixSync,                   /* xSync */                                   \
27362    unixFileSize,               /* xFileSize */                               \
27363    LOCK,                       /* xLock */                                   \
27364    UNLOCK,                     /* xUnlock */                                 \
27365    CKLOCK,                     /* xCheckReservedLock */                      \
27366    unixFileControl,            /* xFileControl */                            \
27367    unixSectorSize,             /* xSectorSize */                             \
27368    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27369    unixShmMap,                 /* xShmMap */                                 \
27370    unixShmLock,                /* xShmLock */                                \
27371    unixShmBarrier,             /* xShmBarrier */                             \
27372    unixShmUnmap                /* xShmUnmap */                               \
27373 };                                                                           \
27374 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27375   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27376   return &METHOD;                                                            \
27377 }                                                                            \
27378 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27379     = FINDER##Impl;
27380
27381 /*
27382 ** Here are all of the sqlite3_io_methods objects for each of the
27383 ** locking strategies.  Functions that return pointers to these methods
27384 ** are also created.
27385 */
27386 IOMETHODS(
27387   posixIoFinder,            /* Finder function name */
27388   posixIoMethods,           /* sqlite3_io_methods object name */
27389   2,                        /* shared memory is enabled */
27390   unixClose,                /* xClose method */
27391   unixLock,                 /* xLock method */
27392   unixUnlock,               /* xUnlock method */
27393   unixCheckReservedLock     /* xCheckReservedLock method */
27394 )
27395 IOMETHODS(
27396   nolockIoFinder,           /* Finder function name */
27397   nolockIoMethods,          /* sqlite3_io_methods object name */
27398   1,                        /* shared memory is disabled */
27399   nolockClose,              /* xClose method */
27400   nolockLock,               /* xLock method */
27401   nolockUnlock,             /* xUnlock method */
27402   nolockCheckReservedLock   /* xCheckReservedLock method */
27403 )
27404 IOMETHODS(
27405   dotlockIoFinder,          /* Finder function name */
27406   dotlockIoMethods,         /* sqlite3_io_methods object name */
27407   1,                        /* shared memory is disabled */
27408   dotlockClose,             /* xClose method */
27409   dotlockLock,              /* xLock method */
27410   dotlockUnlock,            /* xUnlock method */
27411   dotlockCheckReservedLock  /* xCheckReservedLock method */
27412 )
27413
27414 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27415 IOMETHODS(
27416   flockIoFinder,            /* Finder function name */
27417   flockIoMethods,           /* sqlite3_io_methods object name */
27418   1,                        /* shared memory is disabled */
27419   flockClose,               /* xClose method */
27420   flockLock,                /* xLock method */
27421   flockUnlock,              /* xUnlock method */
27422   flockCheckReservedLock    /* xCheckReservedLock method */
27423 )
27424 #endif
27425
27426 #if OS_VXWORKS
27427 IOMETHODS(
27428   semIoFinder,              /* Finder function name */
27429   semIoMethods,             /* sqlite3_io_methods object name */
27430   1,                        /* shared memory is disabled */
27431   semClose,                 /* xClose method */
27432   semLock,                  /* xLock method */
27433   semUnlock,                /* xUnlock method */
27434   semCheckReservedLock      /* xCheckReservedLock method */
27435 )
27436 #endif
27437
27438 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27439 IOMETHODS(
27440   afpIoFinder,              /* Finder function name */
27441   afpIoMethods,             /* sqlite3_io_methods object name */
27442   1,                        /* shared memory is disabled */
27443   afpClose,                 /* xClose method */
27444   afpLock,                  /* xLock method */
27445   afpUnlock,                /* xUnlock method */
27446   afpCheckReservedLock      /* xCheckReservedLock method */
27447 )
27448 #endif
27449
27450 /*
27451 ** The proxy locking method is a "super-method" in the sense that it
27452 ** opens secondary file descriptors for the conch and lock files and
27453 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
27454 ** secondary files.  For this reason, the division that implements
27455 ** proxy locking is located much further down in the file.  But we need
27456 ** to go ahead and define the sqlite3_io_methods and finder function
27457 ** for proxy locking here.  So we forward declare the I/O methods.
27458 */
27459 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27460 static int proxyClose(sqlite3_file*);
27461 static int proxyLock(sqlite3_file*, int);
27462 static int proxyUnlock(sqlite3_file*, int);
27463 static int proxyCheckReservedLock(sqlite3_file*, int*);
27464 IOMETHODS(
27465   proxyIoFinder,            /* Finder function name */
27466   proxyIoMethods,           /* sqlite3_io_methods object name */
27467   1,                        /* shared memory is disabled */
27468   proxyClose,               /* xClose method */
27469   proxyLock,                /* xLock method */
27470   proxyUnlock,              /* xUnlock method */
27471   proxyCheckReservedLock    /* xCheckReservedLock method */
27472 )
27473 #endif
27474
27475 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
27476 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27477 IOMETHODS(
27478   nfsIoFinder,               /* Finder function name */
27479   nfsIoMethods,              /* sqlite3_io_methods object name */
27480   1,                         /* shared memory is disabled */
27481   unixClose,                 /* xClose method */
27482   unixLock,                  /* xLock method */
27483   nfsUnlock,                 /* xUnlock method */
27484   unixCheckReservedLock      /* xCheckReservedLock method */
27485 )
27486 #endif
27487
27488 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27489 /* 
27490 ** This "finder" function attempts to determine the best locking strategy 
27491 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27492 ** object that implements that strategy.
27493 **
27494 ** This is for MacOSX only.
27495 */
27496 static const sqlite3_io_methods *autolockIoFinderImpl(
27497   const char *filePath,    /* name of the database file */
27498   unixFile *pNew           /* open file object for the database file */
27499 ){
27500   static const struct Mapping {
27501     const char *zFilesystem;              /* Filesystem type name */
27502     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
27503   } aMap[] = {
27504     { "hfs",    &posixIoMethods },
27505     { "ufs",    &posixIoMethods },
27506     { "afpfs",  &afpIoMethods },
27507     { "smbfs",  &afpIoMethods },
27508     { "webdav", &nolockIoMethods },
27509     { 0, 0 }
27510   };
27511   int i;
27512   struct statfs fsInfo;
27513   struct flock lockInfo;
27514
27515   if( !filePath ){
27516     /* If filePath==NULL that means we are dealing with a transient file
27517     ** that does not need to be locked. */
27518     return &nolockIoMethods;
27519   }
27520   if( statfs(filePath, &fsInfo) != -1 ){
27521     if( fsInfo.f_flags & MNT_RDONLY ){
27522       return &nolockIoMethods;
27523     }
27524     for(i=0; aMap[i].zFilesystem; i++){
27525       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
27526         return aMap[i].pMethods;
27527       }
27528     }
27529   }
27530
27531   /* Default case. Handles, amongst others, "nfs".
27532   ** Test byte-range lock using fcntl(). If the call succeeds, 
27533   ** assume that the file-system supports POSIX style locks. 
27534   */
27535   lockInfo.l_len = 1;
27536   lockInfo.l_start = 0;
27537   lockInfo.l_whence = SEEK_SET;
27538   lockInfo.l_type = F_RDLCK;
27539   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27540     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
27541       return &nfsIoMethods;
27542     } else {
27543       return &posixIoMethods;
27544     }
27545   }else{
27546     return &dotlockIoMethods;
27547   }
27548 }
27549 static const sqlite3_io_methods 
27550   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27551
27552 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27553
27554 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
27555 /* 
27556 ** This "finder" function attempts to determine the best locking strategy 
27557 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27558 ** object that implements that strategy.
27559 **
27560 ** This is for VXWorks only.
27561 */
27562 static const sqlite3_io_methods *autolockIoFinderImpl(
27563   const char *filePath,    /* name of the database file */
27564   unixFile *pNew           /* the open file object */
27565 ){
27566   struct flock lockInfo;
27567
27568   if( !filePath ){
27569     /* If filePath==NULL that means we are dealing with a transient file
27570     ** that does not need to be locked. */
27571     return &nolockIoMethods;
27572   }
27573
27574   /* Test if fcntl() is supported and use POSIX style locks.
27575   ** Otherwise fall back to the named semaphore method.
27576   */
27577   lockInfo.l_len = 1;
27578   lockInfo.l_start = 0;
27579   lockInfo.l_whence = SEEK_SET;
27580   lockInfo.l_type = F_RDLCK;
27581   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27582     return &posixIoMethods;
27583   }else{
27584     return &semIoMethods;
27585   }
27586 }
27587 static const sqlite3_io_methods 
27588   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27589
27590 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27591
27592 /*
27593 ** An abstract type for a pointer to a IO method finder function:
27594 */
27595 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27596
27597
27598 /****************************************************************************
27599 **************************** sqlite3_vfs methods ****************************
27600 **
27601 ** This division contains the implementation of methods on the
27602 ** sqlite3_vfs object.
27603 */
27604
27605 /*
27606 ** Initialize the contents of the unixFile structure pointed to by pId.
27607 */
27608 static int fillInUnixFile(
27609   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27610   int h,                  /* Open file descriptor of file being opened */
27611   sqlite3_file *pId,      /* Write to the unixFile structure here */
27612   const char *zFilename,  /* Name of the file being opened */
27613   int ctrlFlags           /* Zero or more UNIXFILE_* values */
27614 ){
27615   const sqlite3_io_methods *pLockingStyle;
27616   unixFile *pNew = (unixFile *)pId;
27617   int rc = SQLITE_OK;
27618
27619   assert( pNew->pInode==NULL );
27620
27621   /* Usually the path zFilename should not be a relative pathname. The
27622   ** exception is when opening the proxy "conch" file in builds that
27623   ** include the special Apple locking styles.
27624   */
27625 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27626   assert( zFilename==0 || zFilename[0]=='/' 
27627     || pVfs->pAppData==(void*)&autolockIoFinder );
27628 #else
27629   assert( zFilename==0 || zFilename[0]=='/' );
27630 #endif
27631
27632   /* No locking occurs in temporary files */
27633   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
27634
27635   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27636   pNew->h = h;
27637   pNew->pVfs = pVfs;
27638   pNew->zPath = zFilename;
27639   pNew->ctrlFlags = (u8)ctrlFlags;
27640   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
27641                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
27642     pNew->ctrlFlags |= UNIXFILE_PSOW;
27643   }
27644   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
27645     pNew->ctrlFlags |= UNIXFILE_EXCL;
27646   }
27647
27648 #if OS_VXWORKS
27649   pNew->pId = vxworksFindFileId(zFilename);
27650   if( pNew->pId==0 ){
27651     ctrlFlags |= UNIXFILE_NOLOCK;
27652     rc = SQLITE_NOMEM;
27653   }
27654 #endif
27655
27656   if( ctrlFlags & UNIXFILE_NOLOCK ){
27657     pLockingStyle = &nolockIoMethods;
27658   }else{
27659     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27660 #if SQLITE_ENABLE_LOCKING_STYLE
27661     /* Cache zFilename in the locking context (AFP and dotlock override) for
27662     ** proxyLock activation is possible (remote proxy is based on db name)
27663     ** zFilename remains valid until file is closed, to support */
27664     pNew->lockingContext = (void*)zFilename;
27665 #endif
27666   }
27667
27668   if( pLockingStyle == &posixIoMethods
27669 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27670     || pLockingStyle == &nfsIoMethods
27671 #endif
27672   ){
27673     unixEnterMutex();
27674     rc = findInodeInfo(pNew, &pNew->pInode);
27675     if( rc!=SQLITE_OK ){
27676       /* If an error occured in findInodeInfo(), close the file descriptor
27677       ** immediately, before releasing the mutex. findInodeInfo() may fail
27678       ** in two scenarios:
27679       **
27680       **   (a) A call to fstat() failed.
27681       **   (b) A malloc failed.
27682       **
27683       ** Scenario (b) may only occur if the process is holding no other
27684       ** file descriptors open on the same file. If there were other file
27685       ** descriptors on this file, then no malloc would be required by
27686       ** findInodeInfo(). If this is the case, it is quite safe to close
27687       ** handle h - as it is guaranteed that no posix locks will be released
27688       ** by doing so.
27689       **
27690       ** If scenario (a) caused the error then things are not so safe. The
27691       ** implicit assumption here is that if fstat() fails, things are in
27692       ** such bad shape that dropping a lock or two doesn't matter much.
27693       */
27694       robust_close(pNew, h, __LINE__);
27695       h = -1;
27696     }
27697     unixLeaveMutex();
27698   }
27699
27700 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27701   else if( pLockingStyle == &afpIoMethods ){
27702     /* AFP locking uses the file path so it needs to be included in
27703     ** the afpLockingContext.
27704     */
27705     afpLockingContext *pCtx;
27706     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27707     if( pCtx==0 ){
27708       rc = SQLITE_NOMEM;
27709     }else{
27710       /* NB: zFilename exists and remains valid until the file is closed
27711       ** according to requirement F11141.  So we do not need to make a
27712       ** copy of the filename. */
27713       pCtx->dbPath = zFilename;
27714       pCtx->reserved = 0;
27715       srandomdev();
27716       unixEnterMutex();
27717       rc = findInodeInfo(pNew, &pNew->pInode);
27718       if( rc!=SQLITE_OK ){
27719         sqlite3_free(pNew->lockingContext);
27720         robust_close(pNew, h, __LINE__);
27721         h = -1;
27722       }
27723       unixLeaveMutex();        
27724     }
27725   }
27726 #endif
27727
27728   else if( pLockingStyle == &dotlockIoMethods ){
27729     /* Dotfile locking uses the file path so it needs to be included in
27730     ** the dotlockLockingContext 
27731     */
27732     char *zLockFile;
27733     int nFilename;
27734     assert( zFilename!=0 );
27735     nFilename = (int)strlen(zFilename) + 6;
27736     zLockFile = (char *)sqlite3_malloc(nFilename);
27737     if( zLockFile==0 ){
27738       rc = SQLITE_NOMEM;
27739     }else{
27740       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27741     }
27742     pNew->lockingContext = zLockFile;
27743   }
27744
27745 #if OS_VXWORKS
27746   else if( pLockingStyle == &semIoMethods ){
27747     /* Named semaphore locking uses the file path so it needs to be
27748     ** included in the semLockingContext
27749     */
27750     unixEnterMutex();
27751     rc = findInodeInfo(pNew, &pNew->pInode);
27752     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27753       char *zSemName = pNew->pInode->aSemName;
27754       int n;
27755       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27756                        pNew->pId->zCanonicalName);
27757       for( n=1; zSemName[n]; n++ )
27758         if( zSemName[n]=='/' ) zSemName[n] = '_';
27759       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27760       if( pNew->pInode->pSem == SEM_FAILED ){
27761         rc = SQLITE_NOMEM;
27762         pNew->pInode->aSemName[0] = '\0';
27763       }
27764     }
27765     unixLeaveMutex();
27766   }
27767 #endif
27768   
27769   pNew->lastErrno = 0;
27770 #if OS_VXWORKS
27771   if( rc!=SQLITE_OK ){
27772     if( h>=0 ) robust_close(pNew, h, __LINE__);
27773     h = -1;
27774     osUnlink(zFilename);
27775     isDelete = 0;
27776   }
27777   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
27778 #endif
27779   if( rc!=SQLITE_OK ){
27780     if( h>=0 ) robust_close(pNew, h, __LINE__);
27781   }else{
27782     pNew->pMethod = pLockingStyle;
27783     OpenCounter(+1);
27784   }
27785   return rc;
27786 }
27787
27788 /*
27789 ** Return the name of a directory in which to put temporary files.
27790 ** If no suitable temporary file directory can be found, return NULL.
27791 */
27792 static const char *unixTempFileDir(void){
27793   static const char *azDirs[] = {
27794      0,
27795      0,
27796      "/var/tmp",
27797      "/usr/tmp",
27798      "/tmp",
27799      0        /* List terminator */
27800   };
27801   unsigned int i;
27802   struct stat buf;
27803   const char *zDir = 0;
27804
27805   azDirs[0] = sqlite3_temp_directory;
27806   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27807   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27808     if( zDir==0 ) continue;
27809     if( osStat(zDir, &buf) ) continue;
27810     if( !S_ISDIR(buf.st_mode) ) continue;
27811     if( osAccess(zDir, 07) ) continue;
27812     break;
27813   }
27814   return zDir;
27815 }
27816
27817 /*
27818 ** Create a temporary file name in zBuf.  zBuf must be allocated
27819 ** by the calling process and must be big enough to hold at least
27820 ** pVfs->mxPathname bytes.
27821 */
27822 static int unixGetTempname(int nBuf, char *zBuf){
27823   static const unsigned char zChars[] =
27824     "abcdefghijklmnopqrstuvwxyz"
27825     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27826     "0123456789";
27827   unsigned int i, j;
27828   const char *zDir;
27829
27830   /* It's odd to simulate an io-error here, but really this is just
27831   ** using the io-error infrastructure to test that SQLite handles this
27832   ** function failing. 
27833   */
27834   SimulateIOError( return SQLITE_IOERR );
27835
27836   zDir = unixTempFileDir();
27837   if( zDir==0 ) zDir = ".";
27838
27839   /* Check that the output buffer is large enough for the temporary file 
27840   ** name. If it is not, return SQLITE_ERROR.
27841   */
27842   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
27843     return SQLITE_ERROR;
27844   }
27845
27846   do{
27847     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27848     j = (int)strlen(zBuf);
27849     sqlite3_randomness(15, &zBuf[j]);
27850     for(i=0; i<15; i++, j++){
27851       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27852     }
27853     zBuf[j] = 0;
27854     zBuf[j+1] = 0;
27855   }while( osAccess(zBuf,0)==0 );
27856   return SQLITE_OK;
27857 }
27858
27859 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27860 /*
27861 ** Routine to transform a unixFile into a proxy-locking unixFile.
27862 ** Implementation in the proxy-lock division, but used by unixOpen()
27863 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27864 */
27865 static int proxyTransformUnixFile(unixFile*, const char*);
27866 #endif
27867
27868 /*
27869 ** Search for an unused file descriptor that was opened on the database 
27870 ** file (not a journal or master-journal file) identified by pathname
27871 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27872 ** argument to this function.
27873 **
27874 ** Such a file descriptor may exist if a database connection was closed
27875 ** but the associated file descriptor could not be closed because some
27876 ** other file descriptor open on the same file is holding a file-lock.
27877 ** Refer to comments in the unixClose() function and the lengthy comment
27878 ** describing "Posix Advisory Locking" at the start of this file for 
27879 ** further details. Also, ticket #4018.
27880 **
27881 ** If a suitable file descriptor is found, then it is returned. If no
27882 ** such file descriptor is located, -1 is returned.
27883 */
27884 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27885   UnixUnusedFd *pUnused = 0;
27886
27887   /* Do not search for an unused file descriptor on vxworks. Not because
27888   ** vxworks would not benefit from the change (it might, we're not sure),
27889   ** but because no way to test it is currently available. It is better 
27890   ** not to risk breaking vxworks support for the sake of such an obscure 
27891   ** feature.  */
27892 #if !OS_VXWORKS
27893   struct stat sStat;                   /* Results of stat() call */
27894
27895   /* A stat() call may fail for various reasons. If this happens, it is
27896   ** almost certain that an open() call on the same path will also fail.
27897   ** For this reason, if an error occurs in the stat() call here, it is
27898   ** ignored and -1 is returned. The caller will try to open a new file
27899   ** descriptor on the same path, fail, and return an error to SQLite.
27900   **
27901   ** Even if a subsequent open() call does succeed, the consequences of
27902   ** not searching for a resusable file descriptor are not dire.  */
27903   if( 0==osStat(zPath, &sStat) ){
27904     unixInodeInfo *pInode;
27905
27906     unixEnterMutex();
27907     pInode = inodeList;
27908     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27909                      || pInode->fileId.ino!=sStat.st_ino) ){
27910        pInode = pInode->pNext;
27911     }
27912     if( pInode ){
27913       UnixUnusedFd **pp;
27914       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27915       pUnused = *pp;
27916       if( pUnused ){
27917         *pp = pUnused->pNext;
27918       }
27919     }
27920     unixLeaveMutex();
27921   }
27922 #endif    /* if !OS_VXWORKS */
27923   return pUnused;
27924 }
27925
27926 /*
27927 ** This function is called by unixOpen() to determine the unix permissions
27928 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27929 ** and a value suitable for passing as the third argument to open(2) is
27930 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27931 ** returned and the value of *pMode is not modified.
27932 **
27933 ** In most cases cases, this routine sets *pMode to 0, which will become
27934 ** an indication to robust_open() to create the file using
27935 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
27936 ** But if the file being opened is a WAL or regular journal file, then 
27937 ** this function queries the file-system for the permissions on the 
27938 ** corresponding database file and sets *pMode to this value. Whenever 
27939 ** possible, WAL and journal files are created using the same permissions 
27940 ** as the associated database file.
27941 **
27942 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
27943 ** original filename is unavailable.  But 8_3_NAMES is only used for
27944 ** FAT filesystems and permissions do not matter there, so just use
27945 ** the default permissions.
27946 */
27947 static int findCreateFileMode(
27948   const char *zPath,              /* Path of file (possibly) being created */
27949   int flags,                      /* Flags passed as 4th argument to xOpen() */
27950   mode_t *pMode,                  /* OUT: Permissions to open file with */
27951   uid_t *pUid,                    /* OUT: uid to set on the file */
27952   gid_t *pGid                     /* OUT: gid to set on the file */
27953 ){
27954   int rc = SQLITE_OK;             /* Return Code */
27955   *pMode = 0;
27956   *pUid = 0;
27957   *pGid = 0;
27958   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27959     char zDb[MAX_PATHNAME+1];     /* Database file path */
27960     int nDb;                      /* Number of valid bytes in zDb */
27961     struct stat sStat;            /* Output of stat() on database file */
27962
27963     /* zPath is a path to a WAL or journal file. The following block derives
27964     ** the path to the associated database file from zPath. This block handles
27965     ** the following naming conventions:
27966     **
27967     **   "<path to db>-journal"
27968     **   "<path to db>-wal"
27969     **   "<path to db>-journalNN"
27970     **   "<path to db>-walNN"
27971     **
27972     ** where NN is a decimal number. The NN naming schemes are 
27973     ** used by the test_multiplex.c module.
27974     */
27975     nDb = sqlite3Strlen30(zPath) - 1; 
27976 #ifdef SQLITE_ENABLE_8_3_NAMES
27977     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
27978     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
27979 #else
27980     while( zPath[nDb]!='-' ){
27981       assert( nDb>0 );
27982       assert( zPath[nDb]!='\n' );
27983       nDb--;
27984     }
27985 #endif
27986     memcpy(zDb, zPath, nDb);
27987     zDb[nDb] = '\0';
27988
27989     if( 0==osStat(zDb, &sStat) ){
27990       *pMode = sStat.st_mode & 0777;
27991       *pUid = sStat.st_uid;
27992       *pGid = sStat.st_gid;
27993     }else{
27994       rc = SQLITE_IOERR_FSTAT;
27995     }
27996   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27997     *pMode = 0600;
27998   }
27999   return rc;
28000 }
28001
28002 /*
28003 ** Open the file zPath.
28004 ** 
28005 ** Previously, the SQLite OS layer used three functions in place of this
28006 ** one:
28007 **
28008 **     sqlite3OsOpenReadWrite();
28009 **     sqlite3OsOpenReadOnly();
28010 **     sqlite3OsOpenExclusive();
28011 **
28012 ** These calls correspond to the following combinations of flags:
28013 **
28014 **     ReadWrite() ->     (READWRITE | CREATE)
28015 **     ReadOnly()  ->     (READONLY) 
28016 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28017 **
28018 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28019 ** true, the file was configured to be automatically deleted when the
28020 ** file handle closed. To achieve the same effect using this new 
28021 ** interface, add the DELETEONCLOSE flag to those specified above for 
28022 ** OpenExclusive().
28023 */
28024 static int unixOpen(
28025   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28026   const char *zPath,           /* Pathname of file to be opened */
28027   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28028   int flags,                   /* Input flags to control the opening */
28029   int *pOutFlags               /* Output flags returned to SQLite core */
28030 ){
28031   unixFile *p = (unixFile *)pFile;
28032   int fd = -1;                   /* File descriptor returned by open() */
28033   int openFlags = 0;             /* Flags to pass to open() */
28034   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28035   int noLock;                    /* True to omit locking primitives */
28036   int rc = SQLITE_OK;            /* Function Return Code */
28037   int ctrlFlags = 0;             /* UNIXFILE_* flags */
28038
28039   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28040   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28041   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28042   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28043   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28044 #if SQLITE_ENABLE_LOCKING_STYLE
28045   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28046 #endif
28047 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28048   struct statfs fsInfo;
28049 #endif
28050
28051   /* If creating a master or main-file journal, this function will open
28052   ** a file-descriptor on the directory too. The first time unixSync()
28053   ** is called the directory file descriptor will be fsync()ed and close()d.
28054   */
28055   int syncDir = (isCreate && (
28056         eType==SQLITE_OPEN_MASTER_JOURNAL 
28057      || eType==SQLITE_OPEN_MAIN_JOURNAL 
28058      || eType==SQLITE_OPEN_WAL
28059   ));
28060
28061   /* If argument zPath is a NULL pointer, this function is required to open
28062   ** a temporary file. Use this buffer to store the file name in.
28063   */
28064   char zTmpname[MAX_PATHNAME+2];
28065   const char *zName = zPath;
28066
28067   /* Check the following statements are true: 
28068   **
28069   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
28070   **   (b) if CREATE is set, then READWRITE must also be set, and
28071   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28072   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28073   */
28074   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28075   assert(isCreate==0 || isReadWrite);
28076   assert(isExclusive==0 || isCreate);
28077   assert(isDelete==0 || isCreate);
28078
28079   /* The main DB, main journal, WAL file and master journal are never 
28080   ** automatically deleted. Nor are they ever temporary files.  */
28081   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28082   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28083   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28084   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28085
28086   /* Assert that the upper layer has set one of the "file-type" flags. */
28087   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
28088        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
28089        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
28090        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28091   );
28092
28093   memset(p, 0, sizeof(unixFile));
28094
28095   if( eType==SQLITE_OPEN_MAIN_DB ){
28096     UnixUnusedFd *pUnused;
28097     pUnused = findReusableFd(zName, flags);
28098     if( pUnused ){
28099       fd = pUnused->fd;
28100     }else{
28101       pUnused = sqlite3_malloc(sizeof(*pUnused));
28102       if( !pUnused ){
28103         return SQLITE_NOMEM;
28104       }
28105     }
28106     p->pUnused = pUnused;
28107
28108     /* Database filenames are double-zero terminated if they are not
28109     ** URIs with parameters.  Hence, they can always be passed into
28110     ** sqlite3_uri_parameter(). */
28111     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28112
28113   }else if( !zName ){
28114     /* If zName is NULL, the upper layer is requesting a temp file. */
28115     assert(isDelete && !syncDir);
28116     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28117     if( rc!=SQLITE_OK ){
28118       return rc;
28119     }
28120     zName = zTmpname;
28121
28122     /* Generated temporary filenames are always double-zero terminated
28123     ** for use by sqlite3_uri_parameter(). */
28124     assert( zName[strlen(zName)+1]==0 );
28125   }
28126
28127   /* Determine the value of the flags parameter passed to POSIX function
28128   ** open(). These must be calculated even if open() is not called, as
28129   ** they may be stored as part of the file handle and used by the 
28130   ** 'conch file' locking functions later on.  */
28131   if( isReadonly )  openFlags |= O_RDONLY;
28132   if( isReadWrite ) openFlags |= O_RDWR;
28133   if( isCreate )    openFlags |= O_CREAT;
28134   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28135   openFlags |= (O_LARGEFILE|O_BINARY);
28136
28137   if( fd<0 ){
28138     mode_t openMode;              /* Permissions to create file with */
28139     uid_t uid;                    /* Userid for the file */
28140     gid_t gid;                    /* Groupid for the file */
28141     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28142     if( rc!=SQLITE_OK ){
28143       assert( !p->pUnused );
28144       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28145       return rc;
28146     }
28147     fd = robust_open(zName, openFlags, openMode);
28148     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
28149     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28150       /* Failed to open the file for read/write access. Try read-only. */
28151       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28152       openFlags &= ~(O_RDWR|O_CREAT);
28153       flags |= SQLITE_OPEN_READONLY;
28154       openFlags |= O_RDONLY;
28155       isReadonly = 1;
28156       fd = robust_open(zName, openFlags, openMode);
28157     }
28158     if( fd<0 ){
28159       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28160       goto open_finished;
28161     }
28162
28163     /* If this process is running as root and if creating a new rollback
28164     ** journal or WAL file, set the ownership of the journal or WAL to be
28165     ** the same as the original database.
28166     */
28167     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28168       osFchown(fd, uid, gid);
28169     }
28170   }
28171   assert( fd>=0 );
28172   if( pOutFlags ){
28173     *pOutFlags = flags;
28174   }
28175
28176   if( p->pUnused ){
28177     p->pUnused->fd = fd;
28178     p->pUnused->flags = flags;
28179   }
28180
28181   if( isDelete ){
28182 #if OS_VXWORKS
28183     zPath = zName;
28184 #else
28185     osUnlink(zName);
28186 #endif
28187   }
28188 #if SQLITE_ENABLE_LOCKING_STYLE
28189   else{
28190     p->openFlags = openFlags;
28191   }
28192 #endif
28193
28194   noLock = eType!=SQLITE_OPEN_MAIN_DB;
28195
28196   
28197 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28198   if( fstatfs(fd, &fsInfo) == -1 ){
28199     ((unixFile*)pFile)->lastErrno = errno;
28200     robust_close(p, fd, __LINE__);
28201     return SQLITE_IOERR_ACCESS;
28202   }
28203   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28204     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28205   }
28206 #endif
28207
28208   /* Set up appropriate ctrlFlags */
28209   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
28210   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
28211   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
28212   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
28213   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28214
28215 #if SQLITE_ENABLE_LOCKING_STYLE
28216 #if SQLITE_PREFER_PROXY_LOCKING
28217   isAutoProxy = 1;
28218 #endif
28219   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28220     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28221     int useProxy = 0;
28222
28223     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
28224     ** never use proxy, NULL means use proxy for non-local files only.  */
28225     if( envforce!=NULL ){
28226       useProxy = atoi(envforce)>0;
28227     }else{
28228       if( statfs(zPath, &fsInfo) == -1 ){
28229         /* In theory, the close(fd) call is sub-optimal. If the file opened
28230         ** with fd is a database file, and there are other connections open
28231         ** on that file that are currently holding advisory locks on it,
28232         ** then the call to close() will cancel those locks. In practice,
28233         ** we're assuming that statfs() doesn't fail very often. At least
28234         ** not while other file descriptors opened by the same process on
28235         ** the same file are working.  */
28236         p->lastErrno = errno;
28237         robust_close(p, fd, __LINE__);
28238         rc = SQLITE_IOERR_ACCESS;
28239         goto open_finished;
28240       }
28241       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28242     }
28243     if( useProxy ){
28244       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28245       if( rc==SQLITE_OK ){
28246         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28247         if( rc!=SQLITE_OK ){
28248           /* Use unixClose to clean up the resources added in fillInUnixFile 
28249           ** and clear all the structure's references.  Specifically, 
28250           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
28251           */
28252           unixClose(pFile);
28253           return rc;
28254         }
28255       }
28256       goto open_finished;
28257     }
28258   }
28259 #endif
28260   
28261   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28262
28263 open_finished:
28264   if( rc!=SQLITE_OK ){
28265     sqlite3_free(p->pUnused);
28266   }
28267   return rc;
28268 }
28269
28270
28271 /*
28272 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28273 ** the directory after deleting the file.
28274 */
28275 static int unixDelete(
28276   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28277   const char *zPath,        /* Name of file to be deleted */
28278   int dirSync               /* If true, fsync() directory after deleting file */
28279 ){
28280   int rc = SQLITE_OK;
28281   UNUSED_PARAMETER(NotUsed);
28282   SimulateIOError(return SQLITE_IOERR_DELETE);
28283   if( osUnlink(zPath)==(-1) ){
28284     if( errno==ENOENT ){
28285       rc = SQLITE_IOERR_DELETE_NOENT;
28286     }else{
28287       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28288     }
28289     return rc;
28290   }
28291 #ifndef SQLITE_DISABLE_DIRSYNC
28292   if( (dirSync & 1)!=0 ){
28293     int fd;
28294     rc = osOpenDirectory(zPath, &fd);
28295     if( rc==SQLITE_OK ){
28296 #if OS_VXWORKS
28297       if( fsync(fd)==-1 )
28298 #else
28299       if( fsync(fd) )
28300 #endif
28301       {
28302         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28303       }
28304       robust_close(0, fd, __LINE__);
28305     }else if( rc==SQLITE_CANTOPEN ){
28306       rc = SQLITE_OK;
28307     }
28308   }
28309 #endif
28310   return rc;
28311 }
28312
28313 /*
28314 ** Test the existance of or access permissions of file zPath. The
28315 ** test performed depends on the value of flags:
28316 **
28317 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28318 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28319 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28320 **
28321 ** Otherwise return 0.
28322 */
28323 static int unixAccess(
28324   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28325   const char *zPath,      /* Path of the file to examine */
28326   int flags,              /* What do we want to learn about the zPath file? */
28327   int *pResOut            /* Write result boolean here */
28328 ){
28329   int amode = 0;
28330   UNUSED_PARAMETER(NotUsed);
28331   SimulateIOError( return SQLITE_IOERR_ACCESS; );
28332   switch( flags ){
28333     case SQLITE_ACCESS_EXISTS:
28334       amode = F_OK;
28335       break;
28336     case SQLITE_ACCESS_READWRITE:
28337       amode = W_OK|R_OK;
28338       break;
28339     case SQLITE_ACCESS_READ:
28340       amode = R_OK;
28341       break;
28342
28343     default:
28344       assert(!"Invalid flags argument");
28345   }
28346   *pResOut = (osAccess(zPath, amode)==0);
28347   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28348     struct stat buf;
28349     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28350       *pResOut = 0;
28351     }
28352   }
28353   return SQLITE_OK;
28354 }
28355
28356
28357 /*
28358 ** Turn a relative pathname into a full pathname. The relative path
28359 ** is stored as a nul-terminated string in the buffer pointed to by
28360 ** zPath. 
28361 **
28362 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
28363 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28364 ** this buffer before returning.
28365 */
28366 static int unixFullPathname(
28367   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28368   const char *zPath,            /* Possibly relative input path */
28369   int nOut,                     /* Size of output buffer in bytes */
28370   char *zOut                    /* Output buffer */
28371 ){
28372
28373   /* It's odd to simulate an io-error here, but really this is just
28374   ** using the io-error infrastructure to test that SQLite handles this
28375   ** function failing. This function could fail if, for example, the
28376   ** current working directory has been unlinked.
28377   */
28378   SimulateIOError( return SQLITE_ERROR );
28379
28380   assert( pVfs->mxPathname==MAX_PATHNAME );
28381   UNUSED_PARAMETER(pVfs);
28382
28383   zOut[nOut-1] = '\0';
28384   if( zPath[0]=='/' ){
28385     sqlite3_snprintf(nOut, zOut, "%s", zPath);
28386   }else{
28387     int nCwd;
28388     if( osGetcwd(zOut, nOut-1)==0 ){
28389       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
28390     }
28391     nCwd = (int)strlen(zOut);
28392     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
28393   }
28394   return SQLITE_OK;
28395 }
28396
28397
28398 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28399 /*
28400 ** Interfaces for opening a shared library, finding entry points
28401 ** within the shared library, and closing the shared library.
28402 */
28403 #include <dlfcn.h>
28404 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
28405   UNUSED_PARAMETER(NotUsed);
28406   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
28407 }
28408
28409 /*
28410 ** SQLite calls this function immediately after a call to unixDlSym() or
28411 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
28412 ** message is available, it is written to zBufOut. If no error message
28413 ** is available, zBufOut is left unmodified and SQLite uses a default
28414 ** error message.
28415 */
28416 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
28417   const char *zErr;
28418   UNUSED_PARAMETER(NotUsed);
28419   unixEnterMutex();
28420   zErr = dlerror();
28421   if( zErr ){
28422     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
28423   }
28424   unixLeaveMutex();
28425 }
28426 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
28427   /* 
28428   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
28429   ** cast into a pointer to a function.  And yet the library dlsym() routine
28430   ** returns a void* which is really a pointer to a function.  So how do we
28431   ** use dlsym() with -pedantic-errors?
28432   **
28433   ** Variable x below is defined to be a pointer to a function taking
28434   ** parameters void* and const char* and returning a pointer to a function.
28435   ** We initialize x by assigning it a pointer to the dlsym() function.
28436   ** (That assignment requires a cast.)  Then we call the function that
28437   ** x points to.  
28438   **
28439   ** This work-around is unlikely to work correctly on any system where
28440   ** you really cannot cast a function pointer into void*.  But then, on the
28441   ** other hand, dlsym() will not work on such a system either, so we have
28442   ** not really lost anything.
28443   */
28444   void (*(*x)(void*,const char*))(void);
28445   UNUSED_PARAMETER(NotUsed);
28446   x = (void(*(*)(void*,const char*))(void))dlsym;
28447   return (*x)(p, zSym);
28448 }
28449 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
28450   UNUSED_PARAMETER(NotUsed);
28451   dlclose(pHandle);
28452 }
28453 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28454   #define unixDlOpen  0
28455   #define unixDlError 0
28456   #define unixDlSym   0
28457   #define unixDlClose 0
28458 #endif
28459
28460 /*
28461 ** Write nBuf bytes of random data to the supplied buffer zBuf.
28462 */
28463 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
28464   UNUSED_PARAMETER(NotUsed);
28465   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
28466
28467   /* We have to initialize zBuf to prevent valgrind from reporting
28468   ** errors.  The reports issued by valgrind are incorrect - we would
28469   ** prefer that the randomness be increased by making use of the
28470   ** uninitialized space in zBuf - but valgrind errors tend to worry
28471   ** some users.  Rather than argue, it seems easier just to initialize
28472   ** the whole array and silence valgrind, even if that means less randomness
28473   ** in the random seed.
28474   **
28475   ** When testing, initializing zBuf[] to zero is all we do.  That means
28476   ** that we always use the same random number sequence.  This makes the
28477   ** tests repeatable.
28478   */
28479   memset(zBuf, 0, nBuf);
28480 #if !defined(SQLITE_TEST)
28481   {
28482     int pid, fd, got;
28483     fd = robust_open("/dev/urandom", O_RDONLY, 0);
28484     if( fd<0 ){
28485       time_t t;
28486       time(&t);
28487       memcpy(zBuf, &t, sizeof(t));
28488       pid = getpid();
28489       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
28490       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
28491       nBuf = sizeof(t) + sizeof(pid);
28492     }else{
28493       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
28494       robust_close(0, fd, __LINE__);
28495     }
28496   }
28497 #endif
28498   return nBuf;
28499 }
28500
28501
28502 /*
28503 ** Sleep for a little while.  Return the amount of time slept.
28504 ** The argument is the number of microseconds we want to sleep.
28505 ** The return value is the number of microseconds of sleep actually
28506 ** requested from the underlying operating system, a number which
28507 ** might be greater than or equal to the argument, but not less
28508 ** than the argument.
28509 */
28510 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
28511 #if OS_VXWORKS
28512   struct timespec sp;
28513
28514   sp.tv_sec = microseconds / 1000000;
28515   sp.tv_nsec = (microseconds % 1000000) * 1000;
28516   nanosleep(&sp, NULL);
28517   UNUSED_PARAMETER(NotUsed);
28518   return microseconds;
28519 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
28520   usleep(microseconds);
28521   UNUSED_PARAMETER(NotUsed);
28522   return microseconds;
28523 #else
28524   int seconds = (microseconds+999999)/1000000;
28525   sleep(seconds);
28526   UNUSED_PARAMETER(NotUsed);
28527   return seconds*1000000;
28528 #endif
28529 }
28530
28531 /*
28532 ** The following variable, if set to a non-zero value, is interpreted as
28533 ** the number of seconds since 1970 and is used to set the result of
28534 ** sqlite3OsCurrentTime() during testing.
28535 */
28536 #ifdef SQLITE_TEST
28537 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
28538 #endif
28539
28540 /*
28541 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
28542 ** the current time and date as a Julian Day number times 86_400_000.  In
28543 ** other words, write into *piNow the number of milliseconds since the Julian
28544 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
28545 ** proleptic Gregorian calendar.
28546 **
28547 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
28548 ** cannot be found.
28549 */
28550 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
28551   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
28552   int rc = SQLITE_OK;
28553 #if defined(NO_GETTOD)
28554   time_t t;
28555   time(&t);
28556   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
28557 #elif OS_VXWORKS
28558   struct timespec sNow;
28559   clock_gettime(CLOCK_REALTIME, &sNow);
28560   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
28561 #else
28562   struct timeval sNow;
28563   if( gettimeofday(&sNow, 0)==0 ){
28564     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28565   }else{
28566     rc = SQLITE_ERROR;
28567   }
28568 #endif
28569
28570 #ifdef SQLITE_TEST
28571   if( sqlite3_current_time ){
28572     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28573   }
28574 #endif
28575   UNUSED_PARAMETER(NotUsed);
28576   return rc;
28577 }
28578
28579 /*
28580 ** Find the current time (in Universal Coordinated Time).  Write the
28581 ** current time and date as a Julian Day number into *prNow and
28582 ** return 0.  Return 1 if the time and date cannot be found.
28583 */
28584 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28585   sqlite3_int64 i = 0;
28586   int rc;
28587   UNUSED_PARAMETER(NotUsed);
28588   rc = unixCurrentTimeInt64(0, &i);
28589   *prNow = i/86400000.0;
28590   return rc;
28591 }
28592
28593 /*
28594 ** We added the xGetLastError() method with the intention of providing
28595 ** better low-level error messages when operating-system problems come up
28596 ** during SQLite operation.  But so far, none of that has been implemented
28597 ** in the core.  So this routine is never called.  For now, it is merely
28598 ** a place-holder.
28599 */
28600 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28601   UNUSED_PARAMETER(NotUsed);
28602   UNUSED_PARAMETER(NotUsed2);
28603   UNUSED_PARAMETER(NotUsed3);
28604   return 0;
28605 }
28606
28607
28608 /*
28609 ************************ End of sqlite3_vfs methods ***************************
28610 ******************************************************************************/
28611
28612 /******************************************************************************
28613 ************************** Begin Proxy Locking ********************************
28614 **
28615 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28616 ** other locking methods on secondary lock files.  Proxy locking is a
28617 ** meta-layer over top of the primitive locking implemented above.  For
28618 ** this reason, the division that implements of proxy locking is deferred
28619 ** until late in the file (here) after all of the other I/O methods have
28620 ** been defined - so that the primitive locking methods are available
28621 ** as services to help with the implementation of proxy locking.
28622 **
28623 ****
28624 **
28625 ** The default locking schemes in SQLite use byte-range locks on the
28626 ** database file to coordinate safe, concurrent access by multiple readers
28627 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28628 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28629 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28630 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28631 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28632 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28633 ** address in the shared range is taken for a SHARED lock, the entire
28634 ** shared range is taken for an EXCLUSIVE lock):
28635 **
28636 **      PENDING_BYTE        0x40000000
28637 **      RESERVED_BYTE       0x40000001
28638 **      SHARED_RANGE        0x40000002 -> 0x40000200
28639 **
28640 ** This works well on the local file system, but shows a nearly 100x
28641 ** slowdown in read performance on AFP because the AFP client disables
28642 ** the read cache when byte-range locks are present.  Enabling the read
28643 ** cache exposes a cache coherency problem that is present on all OS X
28644 ** supported network file systems.  NFS and AFP both observe the
28645 ** close-to-open semantics for ensuring cache coherency
28646 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28647 ** address the requirements for concurrent database access by multiple
28648 ** readers and writers
28649 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28650 **
28651 ** To address the performance and cache coherency issues, proxy file locking
28652 ** changes the way database access is controlled by limiting access to a
28653 ** single host at a time and moving file locks off of the database file
28654 ** and onto a proxy file on the local file system.  
28655 **
28656 **
28657 ** Using proxy locks
28658 ** -----------------
28659 **
28660 ** C APIs
28661 **
28662 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28663 **                       <proxy_path> | ":auto:");
28664 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28665 **
28666 **
28667 ** SQL pragmas
28668 **
28669 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28670 **  PRAGMA [database.]lock_proxy_file
28671 **
28672 ** Specifying ":auto:" means that if there is a conch file with a matching
28673 ** host ID in it, the proxy path in the conch file will be used, otherwise
28674 ** a proxy path based on the user's temp dir
28675 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28676 ** actual proxy file name is generated from the name and path of the
28677 ** database file.  For example:
28678 **
28679 **       For database path "/Users/me/foo.db" 
28680 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28681 **
28682 ** Once a lock proxy is configured for a database connection, it can not
28683 ** be removed, however it may be switched to a different proxy path via
28684 ** the above APIs (assuming the conch file is not being held by another
28685 ** connection or process). 
28686 **
28687 **
28688 ** How proxy locking works
28689 ** -----------------------
28690 **
28691 ** Proxy file locking relies primarily on two new supporting files: 
28692 **
28693 **   *  conch file to limit access to the database file to a single host
28694 **      at a time
28695 **
28696 **   *  proxy file to act as a proxy for the advisory locks normally
28697 **      taken on the database
28698 **
28699 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28700 ** by taking an sqlite-style shared lock on the conch file, reading the
28701 ** contents and comparing the host's unique host ID (see below) and lock
28702 ** proxy path against the values stored in the conch.  The conch file is
28703 ** stored in the same directory as the database file and the file name
28704 ** is patterned after the database file name as ".<databasename>-conch".
28705 ** If the conch file does not exist, or it's contents do not match the
28706 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28707 ** lock and the conch file contents is updated with the host ID and proxy
28708 ** path and the lock is downgraded to a shared lock again.  If the conch
28709 ** is held by another process (with a shared lock), the exclusive lock
28710 ** will fail and SQLITE_BUSY is returned.
28711 **
28712 ** The proxy file - a single-byte file used for all advisory file locks
28713 ** normally taken on the database file.   This allows for safe sharing
28714 ** of the database file for multiple readers and writers on the same
28715 ** host (the conch ensures that they all use the same local lock file).
28716 **
28717 ** Requesting the lock proxy does not immediately take the conch, it is
28718 ** only taken when the first request to lock database file is made.  
28719 ** This matches the semantics of the traditional locking behavior, where
28720 ** opening a connection to a database file does not take a lock on it.
28721 ** The shared lock and an open file descriptor are maintained until 
28722 ** the connection to the database is closed. 
28723 **
28724 ** The proxy file and the lock file are never deleted so they only need
28725 ** to be created the first time they are used.
28726 **
28727 ** Configuration options
28728 ** ---------------------
28729 **
28730 **  SQLITE_PREFER_PROXY_LOCKING
28731 **
28732 **       Database files accessed on non-local file systems are
28733 **       automatically configured for proxy locking, lock files are
28734 **       named automatically using the same logic as
28735 **       PRAGMA lock_proxy_file=":auto:"
28736 **    
28737 **  SQLITE_PROXY_DEBUG
28738 **
28739 **       Enables the logging of error messages during host id file
28740 **       retrieval and creation
28741 **
28742 **  LOCKPROXYDIR
28743 **
28744 **       Overrides the default directory used for lock proxy files that
28745 **       are named automatically via the ":auto:" setting
28746 **
28747 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28748 **
28749 **       Permissions to use when creating a directory for storing the
28750 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28751 **    
28752 **    
28753 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28754 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28755 ** force proxy locking to be used for every database file opened, and 0
28756 ** will force automatic proxy locking to be disabled for all database
28757 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28758 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28759 */
28760
28761 /*
28762 ** Proxy locking is only available on MacOSX 
28763 */
28764 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28765
28766 /*
28767 ** The proxyLockingContext has the path and file structures for the remote 
28768 ** and local proxy files in it
28769 */
28770 typedef struct proxyLockingContext proxyLockingContext;
28771 struct proxyLockingContext {
28772   unixFile *conchFile;         /* Open conch file */
28773   char *conchFilePath;         /* Name of the conch file */
28774   unixFile *lockProxy;         /* Open proxy lock file */
28775   char *lockProxyPath;         /* Name of the proxy lock file */
28776   char *dbPath;                /* Name of the open file */
28777   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28778   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28779   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28780 };
28781
28782 /* 
28783 ** The proxy lock file path for the database at dbPath is written into lPath, 
28784 ** which must point to valid, writable memory large enough for a maxLen length
28785 ** file path. 
28786 */
28787 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28788   int len;
28789   int dbLen;
28790   int i;
28791
28792 #ifdef LOCKPROXYDIR
28793   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28794 #else
28795 # ifdef _CS_DARWIN_USER_TEMP_DIR
28796   {
28797     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28798       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28799                lPath, errno, getpid()));
28800       return SQLITE_IOERR_LOCK;
28801     }
28802     len = strlcat(lPath, "sqliteplocks", maxLen);    
28803   }
28804 # else
28805   len = strlcpy(lPath, "/tmp/", maxLen);
28806 # endif
28807 #endif
28808
28809   if( lPath[len-1]!='/' ){
28810     len = strlcat(lPath, "/", maxLen);
28811   }
28812   
28813   /* transform the db path to a unique cache name */
28814   dbLen = (int)strlen(dbPath);
28815   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28816     char c = dbPath[i];
28817     lPath[i+len] = (c=='/')?'_':c;
28818   }
28819   lPath[i+len]='\0';
28820   strlcat(lPath, ":auto:", maxLen);
28821   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28822   return SQLITE_OK;
28823 }
28824
28825 /* 
28826  ** Creates the lock file and any missing directories in lockPath
28827  */
28828 static int proxyCreateLockPath(const char *lockPath){
28829   int i, len;
28830   char buf[MAXPATHLEN];
28831   int start = 0;
28832   
28833   assert(lockPath!=NULL);
28834   /* try to create all the intermediate directories */
28835   len = (int)strlen(lockPath);
28836   buf[0] = lockPath[0];
28837   for( i=1; i<len; i++ ){
28838     if( lockPath[i] == '/' && (i - start > 0) ){
28839       /* only mkdir if leaf dir != "." or "/" or ".." */
28840       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28841          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28842         buf[i]='\0';
28843         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28844           int err=errno;
28845           if( err!=EEXIST ) {
28846             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28847                      "'%s' proxy lock path=%s pid=%d\n",
28848                      buf, strerror(err), lockPath, getpid()));
28849             return err;
28850           }
28851         }
28852       }
28853       start=i+1;
28854     }
28855     buf[i] = lockPath[i];
28856   }
28857   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28858   return 0;
28859 }
28860
28861 /*
28862 ** Create a new VFS file descriptor (stored in memory obtained from
28863 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28864 **
28865 ** The caller is responsible not only for closing the file descriptor
28866 ** but also for freeing the memory associated with the file descriptor.
28867 */
28868 static int proxyCreateUnixFile(
28869     const char *path,        /* path for the new unixFile */
28870     unixFile **ppFile,       /* unixFile created and returned by ref */
28871     int islockfile           /* if non zero missing dirs will be created */
28872 ) {
28873   int fd = -1;
28874   unixFile *pNew;
28875   int rc = SQLITE_OK;
28876   int openFlags = O_RDWR | O_CREAT;
28877   sqlite3_vfs dummyVfs;
28878   int terrno = 0;
28879   UnixUnusedFd *pUnused = NULL;
28880
28881   /* 1. first try to open/create the file
28882   ** 2. if that fails, and this is a lock file (not-conch), try creating
28883   ** the parent directories and then try again.
28884   ** 3. if that fails, try to open the file read-only
28885   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28886   */
28887   pUnused = findReusableFd(path, openFlags);
28888   if( pUnused ){
28889     fd = pUnused->fd;
28890   }else{
28891     pUnused = sqlite3_malloc(sizeof(*pUnused));
28892     if( !pUnused ){
28893       return SQLITE_NOMEM;
28894     }
28895   }
28896   if( fd<0 ){
28897     fd = robust_open(path, openFlags, 0);
28898     terrno = errno;
28899     if( fd<0 && errno==ENOENT && islockfile ){
28900       if( proxyCreateLockPath(path) == SQLITE_OK ){
28901         fd = robust_open(path, openFlags, 0);
28902       }
28903     }
28904   }
28905   if( fd<0 ){
28906     openFlags = O_RDONLY;
28907     fd = robust_open(path, openFlags, 0);
28908     terrno = errno;
28909   }
28910   if( fd<0 ){
28911     if( islockfile ){
28912       return SQLITE_BUSY;
28913     }
28914     switch (terrno) {
28915       case EACCES:
28916         return SQLITE_PERM;
28917       case EIO: 
28918         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28919       default:
28920         return SQLITE_CANTOPEN_BKPT;
28921     }
28922   }
28923   
28924   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28925   if( pNew==NULL ){
28926     rc = SQLITE_NOMEM;
28927     goto end_create_proxy;
28928   }
28929   memset(pNew, 0, sizeof(unixFile));
28930   pNew->openFlags = openFlags;
28931   memset(&dummyVfs, 0, sizeof(dummyVfs));
28932   dummyVfs.pAppData = (void*)&autolockIoFinder;
28933   dummyVfs.zName = "dummy";
28934   pUnused->fd = fd;
28935   pUnused->flags = openFlags;
28936   pNew->pUnused = pUnused;
28937   
28938   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
28939   if( rc==SQLITE_OK ){
28940     *ppFile = pNew;
28941     return SQLITE_OK;
28942   }
28943 end_create_proxy:    
28944   robust_close(pNew, fd, __LINE__);
28945   sqlite3_free(pNew);
28946   sqlite3_free(pUnused);
28947   return rc;
28948 }
28949
28950 #ifdef SQLITE_TEST
28951 /* simulate multiple hosts by creating unique hostid file paths */
28952 SQLITE_API int sqlite3_hostid_num = 0;
28953 #endif
28954
28955 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
28956
28957 /* Not always defined in the headers as it ought to be */
28958 extern int gethostuuid(uuid_t id, const struct timespec *wait);
28959
28960 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28961 ** bytes of writable memory.
28962 */
28963 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28964   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28965   memset(pHostID, 0, PROXY_HOSTIDLEN);
28966 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28967                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28968   {
28969     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
28970     if( gethostuuid(pHostID, &timeout) ){
28971       int err = errno;
28972       if( pError ){
28973         *pError = err;
28974       }
28975       return SQLITE_IOERR;
28976     }
28977   }
28978 #else
28979   UNUSED_PARAMETER(pError);
28980 #endif
28981 #ifdef SQLITE_TEST
28982   /* simulate multiple hosts by creating unique hostid file paths */
28983   if( sqlite3_hostid_num != 0){
28984     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28985   }
28986 #endif
28987   
28988   return SQLITE_OK;
28989 }
28990
28991 /* The conch file contains the header, host id and lock file path
28992  */
28993 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28994 #define PROXY_HEADERLEN    1   /* conch file header length */
28995 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28996 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28997
28998 /* 
28999 ** Takes an open conch file, copies the contents to a new path and then moves 
29000 ** it back.  The newly created file's file descriptor is assigned to the
29001 ** conch file structure and finally the original conch file descriptor is 
29002 ** closed.  Returns zero if successful.
29003 */
29004 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29005   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29006   unixFile *conchFile = pCtx->conchFile;
29007   char tPath[MAXPATHLEN];
29008   char buf[PROXY_MAXCONCHLEN];
29009   char *cPath = pCtx->conchFilePath;
29010   size_t readLen = 0;
29011   size_t pathLen = 0;
29012   char errmsg[64] = "";
29013   int fd = -1;
29014   int rc = -1;
29015   UNUSED_PARAMETER(myHostID);
29016
29017   /* create a new path by replace the trailing '-conch' with '-break' */
29018   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29019   if( pathLen>MAXPATHLEN || pathLen<6 || 
29020      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29021     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29022     goto end_breaklock;
29023   }
29024   /* read the conch content */
29025   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29026   if( readLen<PROXY_PATHINDEX ){
29027     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29028     goto end_breaklock;
29029   }
29030   /* write it out to the temporary break file */
29031   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29032   if( fd<0 ){
29033     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29034     goto end_breaklock;
29035   }
29036   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29037     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29038     goto end_breaklock;
29039   }
29040   if( rename(tPath, cPath) ){
29041     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29042     goto end_breaklock;
29043   }
29044   rc = 0;
29045   fprintf(stderr, "broke stale lock on %s\n", cPath);
29046   robust_close(pFile, conchFile->h, __LINE__);
29047   conchFile->h = fd;
29048   conchFile->openFlags = O_RDWR | O_CREAT;
29049
29050 end_breaklock:
29051   if( rc ){
29052     if( fd>=0 ){
29053       osUnlink(tPath);
29054       robust_close(pFile, fd, __LINE__);
29055     }
29056     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29057   }
29058   return rc;
29059 }
29060
29061 /* Take the requested lock on the conch file and break a stale lock if the 
29062 ** host id matches.
29063 */
29064 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29065   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29066   unixFile *conchFile = pCtx->conchFile;
29067   int rc = SQLITE_OK;
29068   int nTries = 0;
29069   struct timespec conchModTime;
29070   
29071   memset(&conchModTime, 0, sizeof(conchModTime));
29072   do {
29073     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29074     nTries ++;
29075     if( rc==SQLITE_BUSY ){
29076       /* If the lock failed (busy):
29077        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
29078        * 2nd try: fail if the mod time changed or host id is different, wait 
29079        *           10 sec and try again
29080        * 3rd try: break the lock unless the mod time has changed.
29081        */
29082       struct stat buf;
29083       if( osFstat(conchFile->h, &buf) ){
29084         pFile->lastErrno = errno;
29085         return SQLITE_IOERR_LOCK;
29086       }
29087       
29088       if( nTries==1 ){
29089         conchModTime = buf.st_mtimespec;
29090         usleep(500000); /* wait 0.5 sec and try the lock again*/
29091         continue;  
29092       }
29093
29094       assert( nTries>1 );
29095       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
29096          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29097         return SQLITE_BUSY;
29098       }
29099       
29100       if( nTries==2 ){  
29101         char tBuf[PROXY_MAXCONCHLEN];
29102         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29103         if( len<0 ){
29104           pFile->lastErrno = errno;
29105           return SQLITE_IOERR_LOCK;
29106         }
29107         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29108           /* don't break the lock if the host id doesn't match */
29109           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29110             return SQLITE_BUSY;
29111           }
29112         }else{
29113           /* don't break the lock on short read or a version mismatch */
29114           return SQLITE_BUSY;
29115         }
29116         usleep(10000000); /* wait 10 sec and try the lock again */
29117         continue; 
29118       }
29119       
29120       assert( nTries==3 );
29121       if( 0==proxyBreakConchLock(pFile, myHostID) ){
29122         rc = SQLITE_OK;
29123         if( lockType==EXCLUSIVE_LOCK ){
29124           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
29125         }
29126         if( !rc ){
29127           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29128         }
29129       }
29130     }
29131   } while( rc==SQLITE_BUSY && nTries<3 );
29132   
29133   return rc;
29134 }
29135
29136 /* Takes the conch by taking a shared lock and read the contents conch, if 
29137 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
29138 ** lockPath means that the lockPath in the conch file will be used if the 
29139 ** host IDs match, or a new lock path will be generated automatically 
29140 ** and written to the conch file.
29141 */
29142 static int proxyTakeConch(unixFile *pFile){
29143   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29144   
29145   if( pCtx->conchHeld!=0 ){
29146     return SQLITE_OK;
29147   }else{
29148     unixFile *conchFile = pCtx->conchFile;
29149     uuid_t myHostID;
29150     int pError = 0;
29151     char readBuf[PROXY_MAXCONCHLEN];
29152     char lockPath[MAXPATHLEN];
29153     char *tempLockPath = NULL;
29154     int rc = SQLITE_OK;
29155     int createConch = 0;
29156     int hostIdMatch = 0;
29157     int readLen = 0;
29158     int tryOldLockPath = 0;
29159     int forceNewLockPath = 0;
29160     
29161     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
29162              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29163
29164     rc = proxyGetHostID(myHostID, &pError);
29165     if( (rc&0xff)==SQLITE_IOERR ){
29166       pFile->lastErrno = pError;
29167       goto end_takeconch;
29168     }
29169     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29170     if( rc!=SQLITE_OK ){
29171       goto end_takeconch;
29172     }
29173     /* read the existing conch file */
29174     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29175     if( readLen<0 ){
29176       /* I/O error: lastErrno set by seekAndRead */
29177       pFile->lastErrno = conchFile->lastErrno;
29178       rc = SQLITE_IOERR_READ;
29179       goto end_takeconch;
29180     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
29181              readBuf[0]!=(char)PROXY_CONCHVERSION ){
29182       /* a short read or version format mismatch means we need to create a new 
29183       ** conch file. 
29184       */
29185       createConch = 1;
29186     }
29187     /* if the host id matches and the lock path already exists in the conch
29188     ** we'll try to use the path there, if we can't open that path, we'll 
29189     ** retry with a new auto-generated path 
29190     */
29191     do { /* in case we need to try again for an :auto: named lock file */
29192
29193       if( !createConch && !forceNewLockPath ){
29194         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
29195                                   PROXY_HOSTIDLEN);
29196         /* if the conch has data compare the contents */
29197         if( !pCtx->lockProxyPath ){
29198           /* for auto-named local lock file, just check the host ID and we'll
29199            ** use the local lock file path that's already in there
29200            */
29201           if( hostIdMatch ){
29202             size_t pathLen = (readLen - PROXY_PATHINDEX);
29203             
29204             if( pathLen>=MAXPATHLEN ){
29205               pathLen=MAXPATHLEN-1;
29206             }
29207             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29208             lockPath[pathLen] = 0;
29209             tempLockPath = lockPath;
29210             tryOldLockPath = 1;
29211             /* create a copy of the lock path if the conch is taken */
29212             goto end_takeconch;
29213           }
29214         }else if( hostIdMatch
29215                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29216                            readLen-PROXY_PATHINDEX)
29217         ){
29218           /* conch host and lock path match */
29219           goto end_takeconch; 
29220         }
29221       }
29222       
29223       /* if the conch isn't writable and doesn't match, we can't take it */
29224       if( (conchFile->openFlags&O_RDWR) == 0 ){
29225         rc = SQLITE_BUSY;
29226         goto end_takeconch;
29227       }
29228       
29229       /* either the conch didn't match or we need to create a new one */
29230       if( !pCtx->lockProxyPath ){
29231         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29232         tempLockPath = lockPath;
29233         /* create a copy of the lock path _only_ if the conch is taken */
29234       }
29235       
29236       /* update conch with host and path (this will fail if other process
29237       ** has a shared lock already), if the host id matches, use the big
29238       ** stick.
29239       */
29240       futimes(conchFile->h, NULL);
29241       if( hostIdMatch && !createConch ){
29242         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29243           /* We are trying for an exclusive lock but another thread in this
29244            ** same process is still holding a shared lock. */
29245           rc = SQLITE_BUSY;
29246         } else {          
29247           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29248         }
29249       }else{
29250         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29251       }
29252       if( rc==SQLITE_OK ){
29253         char writeBuffer[PROXY_MAXCONCHLEN];
29254         int writeSize = 0;
29255         
29256         writeBuffer[0] = (char)PROXY_CONCHVERSION;
29257         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29258         if( pCtx->lockProxyPath!=NULL ){
29259           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29260         }else{
29261           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29262         }
29263         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29264         robust_ftruncate(conchFile->h, writeSize);
29265         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29266         fsync(conchFile->h);
29267         /* If we created a new conch file (not just updated the contents of a 
29268          ** valid conch file), try to match the permissions of the database 
29269          */
29270         if( rc==SQLITE_OK && createConch ){
29271           struct stat buf;
29272           int err = osFstat(pFile->h, &buf);
29273           if( err==0 ){
29274             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29275                                         S_IROTH|S_IWOTH);
29276             /* try to match the database file R/W permissions, ignore failure */
29277 #ifndef SQLITE_PROXY_DEBUG
29278             osFchmod(conchFile->h, cmode);
29279 #else
29280             do{
29281               rc = osFchmod(conchFile->h, cmode);
29282             }while( rc==(-1) && errno==EINTR );
29283             if( rc!=0 ){
29284               int code = errno;
29285               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29286                       cmode, code, strerror(code));
29287             } else {
29288               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29289             }
29290           }else{
29291             int code = errno;
29292             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
29293                     err, code, strerror(code));
29294 #endif
29295           }
29296         }
29297       }
29298       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29299       
29300     end_takeconch:
29301       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29302       if( rc==SQLITE_OK && pFile->openFlags ){
29303         int fd;
29304         if( pFile->h>=0 ){
29305           robust_close(pFile, pFile->h, __LINE__);
29306         }
29307         pFile->h = -1;
29308         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29309         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29310         if( fd>=0 ){
29311           pFile->h = fd;
29312         }else{
29313           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29314            during locking */
29315         }
29316       }
29317       if( rc==SQLITE_OK && !pCtx->lockProxy ){
29318         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29319         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29320         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29321           /* we couldn't create the proxy lock file with the old lock file path
29322            ** so try again via auto-naming 
29323            */
29324           forceNewLockPath = 1;
29325           tryOldLockPath = 0;
29326           continue; /* go back to the do {} while start point, try again */
29327         }
29328       }
29329       if( rc==SQLITE_OK ){
29330         /* Need to make a copy of path if we extracted the value
29331          ** from the conch file or the path was allocated on the stack
29332          */
29333         if( tempLockPath ){
29334           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29335           if( !pCtx->lockProxyPath ){
29336             rc = SQLITE_NOMEM;
29337           }
29338         }
29339       }
29340       if( rc==SQLITE_OK ){
29341         pCtx->conchHeld = 1;
29342         
29343         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29344           afpLockingContext *afpCtx;
29345           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29346           afpCtx->dbPath = pCtx->lockProxyPath;
29347         }
29348       } else {
29349         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29350       }
29351       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29352                rc==SQLITE_OK?"ok":"failed"));
29353       return rc;
29354     } while (1); /* in case we need to retry the :auto: lock file - 
29355                  ** we should never get here except via the 'continue' call. */
29356   }
29357 }
29358
29359 /*
29360 ** If pFile holds a lock on a conch file, then release that lock.
29361 */
29362 static int proxyReleaseConch(unixFile *pFile){
29363   int rc = SQLITE_OK;         /* Subroutine return code */
29364   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29365   unixFile *conchFile;        /* Name of the conch file */
29366
29367   pCtx = (proxyLockingContext *)pFile->lockingContext;
29368   conchFile = pCtx->conchFile;
29369   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29370            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
29371            getpid()));
29372   if( pCtx->conchHeld>0 ){
29373     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29374   }
29375   pCtx->conchHeld = 0;
29376   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29377            (rc==SQLITE_OK ? "ok" : "failed")));
29378   return rc;
29379 }
29380
29381 /*
29382 ** Given the name of a database file, compute the name of its conch file.
29383 ** Store the conch filename in memory obtained from sqlite3_malloc().
29384 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29385 ** or SQLITE_NOMEM if unable to obtain memory.
29386 **
29387 ** The caller is responsible for ensuring that the allocated memory
29388 ** space is eventually freed.
29389 **
29390 ** *pConchPath is set to NULL if a memory allocation error occurs.
29391 */
29392 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
29393   int i;                        /* Loop counter */
29394   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
29395   char *conchPath;              /* buffer in which to construct conch name */
29396
29397   /* Allocate space for the conch filename and initialize the name to
29398   ** the name of the original database file. */  
29399   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
29400   if( conchPath==0 ){
29401     return SQLITE_NOMEM;
29402   }
29403   memcpy(conchPath, dbPath, len+1);
29404   
29405   /* now insert a "." before the last / character */
29406   for( i=(len-1); i>=0; i-- ){
29407     if( conchPath[i]=='/' ){
29408       i++;
29409       break;
29410     }
29411   }
29412   conchPath[i]='.';
29413   while ( i<len ){
29414     conchPath[i+1]=dbPath[i];
29415     i++;
29416   }
29417
29418   /* append the "-conch" suffix to the file */
29419   memcpy(&conchPath[i+1], "-conch", 7);
29420   assert( (int)strlen(conchPath) == len+7 );
29421
29422   return SQLITE_OK;
29423 }
29424
29425
29426 /* Takes a fully configured proxy locking-style unix file and switches
29427 ** the local lock file path 
29428 */
29429 static int switchLockProxyPath(unixFile *pFile, const char *path) {
29430   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29431   char *oldPath = pCtx->lockProxyPath;
29432   int rc = SQLITE_OK;
29433
29434   if( pFile->eFileLock!=NO_LOCK ){
29435     return SQLITE_BUSY;
29436   }  
29437
29438   /* nothing to do if the path is NULL, :auto: or matches the existing path */
29439   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
29440     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
29441     return SQLITE_OK;
29442   }else{
29443     unixFile *lockProxy = pCtx->lockProxy;
29444     pCtx->lockProxy=NULL;
29445     pCtx->conchHeld = 0;
29446     if( lockProxy!=NULL ){
29447       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
29448       if( rc ) return rc;
29449       sqlite3_free(lockProxy);
29450     }
29451     sqlite3_free(oldPath);
29452     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
29453   }
29454   
29455   return rc;
29456 }
29457
29458 /*
29459 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
29460 ** is a string buffer at least MAXPATHLEN+1 characters in size.
29461 **
29462 ** This routine find the filename associated with pFile and writes it
29463 ** int dbPath.
29464 */
29465 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
29466 #if defined(__APPLE__)
29467   if( pFile->pMethod == &afpIoMethods ){
29468     /* afp style keeps a reference to the db path in the filePath field 
29469     ** of the struct */
29470     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29471     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
29472   } else
29473 #endif
29474   if( pFile->pMethod == &dotlockIoMethods ){
29475     /* dot lock style uses the locking context to store the dot lock
29476     ** file path */
29477     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
29478     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
29479   }else{
29480     /* all other styles use the locking context to store the db file path */
29481     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29482     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
29483   }
29484   return SQLITE_OK;
29485 }
29486
29487 /*
29488 ** Takes an already filled in unix file and alters it so all file locking 
29489 ** will be performed on the local proxy lock file.  The following fields
29490 ** are preserved in the locking context so that they can be restored and 
29491 ** the unix structure properly cleaned up at close time:
29492 **  ->lockingContext
29493 **  ->pMethod
29494 */
29495 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
29496   proxyLockingContext *pCtx;
29497   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
29498   char *lockPath=NULL;
29499   int rc = SQLITE_OK;
29500   
29501   if( pFile->eFileLock!=NO_LOCK ){
29502     return SQLITE_BUSY;
29503   }
29504   proxyGetDbPathForUnixFile(pFile, dbPath);
29505   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
29506     lockPath=NULL;
29507   }else{
29508     lockPath=(char *)path;
29509   }
29510   
29511   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
29512            (lockPath ? lockPath : ":auto:"), getpid()));
29513
29514   pCtx = sqlite3_malloc( sizeof(*pCtx) );
29515   if( pCtx==0 ){
29516     return SQLITE_NOMEM;
29517   }
29518   memset(pCtx, 0, sizeof(*pCtx));
29519
29520   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
29521   if( rc==SQLITE_OK ){
29522     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
29523     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
29524       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
29525       ** (c) the file system is read-only, then enable no-locking access.
29526       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
29527       ** that openFlags will have only one of O_RDONLY or O_RDWR.
29528       */
29529       struct statfs fsInfo;
29530       struct stat conchInfo;
29531       int goLockless = 0;
29532
29533       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
29534         int err = errno;
29535         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
29536           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
29537         }
29538       }
29539       if( goLockless ){
29540         pCtx->conchHeld = -1; /* read only FS/ lockless */
29541         rc = SQLITE_OK;
29542       }
29543     }
29544   }  
29545   if( rc==SQLITE_OK && lockPath ){
29546     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
29547   }
29548
29549   if( rc==SQLITE_OK ){
29550     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
29551     if( pCtx->dbPath==NULL ){
29552       rc = SQLITE_NOMEM;
29553     }
29554   }
29555   if( rc==SQLITE_OK ){
29556     /* all memory is allocated, proxys are created and assigned, 
29557     ** switch the locking context and pMethod then return.
29558     */
29559     pCtx->oldLockingContext = pFile->lockingContext;
29560     pFile->lockingContext = pCtx;
29561     pCtx->pOldMethod = pFile->pMethod;
29562     pFile->pMethod = &proxyIoMethods;
29563   }else{
29564     if( pCtx->conchFile ){ 
29565       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
29566       sqlite3_free(pCtx->conchFile);
29567     }
29568     sqlite3DbFree(0, pCtx->lockProxyPath);
29569     sqlite3_free(pCtx->conchFilePath); 
29570     sqlite3_free(pCtx);
29571   }
29572   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29573            (rc==SQLITE_OK ? "ok" : "failed")));
29574   return rc;
29575 }
29576
29577
29578 /*
29579 ** This routine handles sqlite3_file_control() calls that are specific
29580 ** to proxy locking.
29581 */
29582 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29583   switch( op ){
29584     case SQLITE_GET_LOCKPROXYFILE: {
29585       unixFile *pFile = (unixFile*)id;
29586       if( pFile->pMethod == &proxyIoMethods ){
29587         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29588         proxyTakeConch(pFile);
29589         if( pCtx->lockProxyPath ){
29590           *(const char **)pArg = pCtx->lockProxyPath;
29591         }else{
29592           *(const char **)pArg = ":auto: (not held)";
29593         }
29594       } else {
29595         *(const char **)pArg = NULL;
29596       }
29597       return SQLITE_OK;
29598     }
29599     case SQLITE_SET_LOCKPROXYFILE: {
29600       unixFile *pFile = (unixFile*)id;
29601       int rc = SQLITE_OK;
29602       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29603       if( pArg==NULL || (const char *)pArg==0 ){
29604         if( isProxyStyle ){
29605           /* turn off proxy locking - not supported */
29606           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29607         }else{
29608           /* turn off proxy locking - already off - NOOP */
29609           rc = SQLITE_OK;
29610         }
29611       }else{
29612         const char *proxyPath = (const char *)pArg;
29613         if( isProxyStyle ){
29614           proxyLockingContext *pCtx = 
29615             (proxyLockingContext*)pFile->lockingContext;
29616           if( !strcmp(pArg, ":auto:") 
29617            || (pCtx->lockProxyPath &&
29618                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29619           ){
29620             rc = SQLITE_OK;
29621           }else{
29622             rc = switchLockProxyPath(pFile, proxyPath);
29623           }
29624         }else{
29625           /* turn on proxy file locking */
29626           rc = proxyTransformUnixFile(pFile, proxyPath);
29627         }
29628       }
29629       return rc;
29630     }
29631     default: {
29632       assert( 0 );  /* The call assures that only valid opcodes are sent */
29633     }
29634   }
29635   /*NOTREACHED*/
29636   return SQLITE_ERROR;
29637 }
29638
29639 /*
29640 ** Within this division (the proxying locking implementation) the procedures
29641 ** above this point are all utilities.  The lock-related methods of the
29642 ** proxy-locking sqlite3_io_method object follow.
29643 */
29644
29645
29646 /*
29647 ** This routine checks if there is a RESERVED lock held on the specified
29648 ** file by this or any other process. If such a lock is held, set *pResOut
29649 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29650 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29651 */
29652 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29653   unixFile *pFile = (unixFile*)id;
29654   int rc = proxyTakeConch(pFile);
29655   if( rc==SQLITE_OK ){
29656     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29657     if( pCtx->conchHeld>0 ){
29658       unixFile *proxy = pCtx->lockProxy;
29659       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29660     }else{ /* conchHeld < 0 is lockless */
29661       pResOut=0;
29662     }
29663   }
29664   return rc;
29665 }
29666
29667 /*
29668 ** Lock the file with the lock specified by parameter eFileLock - one
29669 ** of the following:
29670 **
29671 **     (1) SHARED_LOCK
29672 **     (2) RESERVED_LOCK
29673 **     (3) PENDING_LOCK
29674 **     (4) EXCLUSIVE_LOCK
29675 **
29676 ** Sometimes when requesting one lock state, additional lock states
29677 ** are inserted in between.  The locking might fail on one of the later
29678 ** transitions leaving the lock state different from what it started but
29679 ** still short of its goal.  The following chart shows the allowed
29680 ** transitions and the inserted intermediate states:
29681 **
29682 **    UNLOCKED -> SHARED
29683 **    SHARED -> RESERVED
29684 **    SHARED -> (PENDING) -> EXCLUSIVE
29685 **    RESERVED -> (PENDING) -> EXCLUSIVE
29686 **    PENDING -> EXCLUSIVE
29687 **
29688 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29689 ** routine to lower a locking level.
29690 */
29691 static int proxyLock(sqlite3_file *id, int eFileLock) {
29692   unixFile *pFile = (unixFile*)id;
29693   int rc = proxyTakeConch(pFile);
29694   if( rc==SQLITE_OK ){
29695     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29696     if( pCtx->conchHeld>0 ){
29697       unixFile *proxy = pCtx->lockProxy;
29698       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29699       pFile->eFileLock = proxy->eFileLock;
29700     }else{
29701       /* conchHeld < 0 is lockless */
29702     }
29703   }
29704   return rc;
29705 }
29706
29707
29708 /*
29709 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29710 ** must be either NO_LOCK or SHARED_LOCK.
29711 **
29712 ** If the locking level of the file descriptor is already at or below
29713 ** the requested locking level, this routine is a no-op.
29714 */
29715 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29716   unixFile *pFile = (unixFile*)id;
29717   int rc = proxyTakeConch(pFile);
29718   if( rc==SQLITE_OK ){
29719     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29720     if( pCtx->conchHeld>0 ){
29721       unixFile *proxy = pCtx->lockProxy;
29722       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29723       pFile->eFileLock = proxy->eFileLock;
29724     }else{
29725       /* conchHeld < 0 is lockless */
29726     }
29727   }
29728   return rc;
29729 }
29730
29731 /*
29732 ** Close a file that uses proxy locks.
29733 */
29734 static int proxyClose(sqlite3_file *id) {
29735   if( id ){
29736     unixFile *pFile = (unixFile*)id;
29737     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29738     unixFile *lockProxy = pCtx->lockProxy;
29739     unixFile *conchFile = pCtx->conchFile;
29740     int rc = SQLITE_OK;
29741     
29742     if( lockProxy ){
29743       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29744       if( rc ) return rc;
29745       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29746       if( rc ) return rc;
29747       sqlite3_free(lockProxy);
29748       pCtx->lockProxy = 0;
29749     }
29750     if( conchFile ){
29751       if( pCtx->conchHeld ){
29752         rc = proxyReleaseConch(pFile);
29753         if( rc ) return rc;
29754       }
29755       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29756       if( rc ) return rc;
29757       sqlite3_free(conchFile);
29758     }
29759     sqlite3DbFree(0, pCtx->lockProxyPath);
29760     sqlite3_free(pCtx->conchFilePath);
29761     sqlite3DbFree(0, pCtx->dbPath);
29762     /* restore the original locking context and pMethod then close it */
29763     pFile->lockingContext = pCtx->oldLockingContext;
29764     pFile->pMethod = pCtx->pOldMethod;
29765     sqlite3_free(pCtx);
29766     return pFile->pMethod->xClose(id);
29767   }
29768   return SQLITE_OK;
29769 }
29770
29771
29772
29773 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29774 /*
29775 ** The proxy locking style is intended for use with AFP filesystems.
29776 ** And since AFP is only supported on MacOSX, the proxy locking is also
29777 ** restricted to MacOSX.
29778 ** 
29779 **
29780 ******************* End of the proxy lock implementation **********************
29781 ******************************************************************************/
29782
29783 /*
29784 ** Initialize the operating system interface.
29785 **
29786 ** This routine registers all VFS implementations for unix-like operating
29787 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29788 ** should be the only routines in this file that are visible from other
29789 ** files.
29790 **
29791 ** This routine is called once during SQLite initialization and by a
29792 ** single thread.  The memory allocation and mutex subsystems have not
29793 ** necessarily been initialized when this routine is called, and so they
29794 ** should not be used.
29795 */
29796 SQLITE_API int sqlite3_os_init(void){ 
29797   /* 
29798   ** The following macro defines an initializer for an sqlite3_vfs object.
29799   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29800   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29801   ** silly C90 rules prohibit a void* from being cast to a function pointer
29802   ** and so we have to go through the intermediate pointer to avoid problems
29803   ** when compiling with -pedantic-errors on GCC.)
29804   **
29805   ** The FINDER parameter to this macro is the name of the pointer to the
29806   ** finder-function.  The finder-function returns a pointer to the
29807   ** sqlite_io_methods object that implements the desired locking
29808   ** behaviors.  See the division above that contains the IOMETHODS
29809   ** macro for addition information on finder-functions.
29810   **
29811   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29812   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29813   ** more than that; it looks at the filesystem type that hosts the 
29814   ** database file and tries to choose an locking method appropriate for
29815   ** that filesystem time.
29816   */
29817   #define UNIXVFS(VFSNAME, FINDER) {                        \
29818     3,                    /* iVersion */                    \
29819     sizeof(unixFile),     /* szOsFile */                    \
29820     MAX_PATHNAME,         /* mxPathname */                  \
29821     0,                    /* pNext */                       \
29822     VFSNAME,              /* zName */                       \
29823     (void*)&FINDER,       /* pAppData */                    \
29824     unixOpen,             /* xOpen */                       \
29825     unixDelete,           /* xDelete */                     \
29826     unixAccess,           /* xAccess */                     \
29827     unixFullPathname,     /* xFullPathname */               \
29828     unixDlOpen,           /* xDlOpen */                     \
29829     unixDlError,          /* xDlError */                    \
29830     unixDlSym,            /* xDlSym */                      \
29831     unixDlClose,          /* xDlClose */                    \
29832     unixRandomness,       /* xRandomness */                 \
29833     unixSleep,            /* xSleep */                      \
29834     unixCurrentTime,      /* xCurrentTime */                \
29835     unixGetLastError,     /* xGetLastError */               \
29836     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29837     unixSetSystemCall,    /* xSetSystemCall */              \
29838     unixGetSystemCall,    /* xGetSystemCall */              \
29839     unixNextSystemCall,   /* xNextSystemCall */             \
29840   }
29841
29842   /*
29843   ** All default VFSes for unix are contained in the following array.
29844   **
29845   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29846   ** by the SQLite core when the VFS is registered.  So the following
29847   ** array cannot be const.
29848   */
29849   static sqlite3_vfs aVfs[] = {
29850 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29851     UNIXVFS("unix",          autolockIoFinder ),
29852 #else
29853     UNIXVFS("unix",          posixIoFinder ),
29854 #endif
29855     UNIXVFS("unix-none",     nolockIoFinder ),
29856     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29857     UNIXVFS("unix-excl",     posixIoFinder ),
29858 #if OS_VXWORKS
29859     UNIXVFS("unix-namedsem", semIoFinder ),
29860 #endif
29861 #if SQLITE_ENABLE_LOCKING_STYLE
29862     UNIXVFS("unix-posix",    posixIoFinder ),
29863 #if !OS_VXWORKS
29864     UNIXVFS("unix-flock",    flockIoFinder ),
29865 #endif
29866 #endif
29867 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29868     UNIXVFS("unix-afp",      afpIoFinder ),
29869     UNIXVFS("unix-nfs",      nfsIoFinder ),
29870     UNIXVFS("unix-proxy",    proxyIoFinder ),
29871 #endif
29872   };
29873   unsigned int i;          /* Loop counter */
29874
29875   /* Double-check that the aSyscall[] array has been constructed
29876   ** correctly.  See ticket [bb3a86e890c8e96ab] */
29877   assert( ArraySize(aSyscall)==22 );
29878
29879   /* Register all VFSes defined in the aVfs[] array */
29880   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29881     sqlite3_vfs_register(&aVfs[i], i==0);
29882   }
29883   return SQLITE_OK; 
29884 }
29885
29886 /*
29887 ** Shutdown the operating system interface.
29888 **
29889 ** Some operating systems might need to do some cleanup in this routine,
29890 ** to release dynamically allocated objects.  But not on unix.
29891 ** This routine is a no-op for unix.
29892 */
29893 SQLITE_API int sqlite3_os_end(void){ 
29894   return SQLITE_OK; 
29895 }
29896  
29897 #endif /* SQLITE_OS_UNIX */
29898
29899 /************** End of os_unix.c *********************************************/
29900 /************** Begin file os_win.c ******************************************/
29901 /*
29902 ** 2004 May 22
29903 **
29904 ** The author disclaims copyright to this source code.  In place of
29905 ** a legal notice, here is a blessing:
29906 **
29907 **    May you do good and not evil.
29908 **    May you find forgiveness for yourself and forgive others.
29909 **    May you share freely, never taking more than you give.
29910 **
29911 ******************************************************************************
29912 **
29913 ** This file contains code that is specific to Windows.
29914 */
29915 #if SQLITE_OS_WIN               /* This file is used for Windows only */
29916
29917 #ifdef __CYGWIN__
29918 # include <sys/cygwin.h>
29919 #endif
29920
29921 /*
29922 ** Include code that is common to all os_*.c files
29923 */
29924 /************** Include os_common.h in the middle of os_win.c ****************/
29925 /************** Begin file os_common.h ***************************************/
29926 /*
29927 ** 2004 May 22
29928 **
29929 ** The author disclaims copyright to this source code.  In place of
29930 ** a legal notice, here is a blessing:
29931 **
29932 **    May you do good and not evil.
29933 **    May you find forgiveness for yourself and forgive others.
29934 **    May you share freely, never taking more than you give.
29935 **
29936 ******************************************************************************
29937 **
29938 ** This file contains macros and a little bit of code that is common to
29939 ** all of the platform-specific files (os_*.c) and is #included into those
29940 ** files.
29941 **
29942 ** This file should be #included by the os_*.c files only.  It is not a
29943 ** general purpose header file.
29944 */
29945 #ifndef _OS_COMMON_H_
29946 #define _OS_COMMON_H_
29947
29948 /*
29949 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29950 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29951 ** switch.  The following code should catch this problem at compile-time.
29952 */
29953 #ifdef MEMORY_DEBUG
29954 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29955 #endif
29956
29957 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
29958 # ifndef SQLITE_DEBUG_OS_TRACE
29959 #   define SQLITE_DEBUG_OS_TRACE 0
29960 # endif
29961   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
29962 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29963 #else
29964 # define OSTRACE(X)
29965 #endif
29966
29967 /*
29968 ** Macros for performance tracing.  Normally turned off.  Only works
29969 ** on i486 hardware.
29970 */
29971 #ifdef SQLITE_PERFORMANCE_TRACE
29972
29973 /* 
29974 ** hwtime.h contains inline assembler code for implementing 
29975 ** high-performance timing routines.
29976 */
29977 /************** Include hwtime.h in the middle of os_common.h ****************/
29978 /************** Begin file hwtime.h ******************************************/
29979 /*
29980 ** 2008 May 27
29981 **
29982 ** The author disclaims copyright to this source code.  In place of
29983 ** a legal notice, here is a blessing:
29984 **
29985 **    May you do good and not evil.
29986 **    May you find forgiveness for yourself and forgive others.
29987 **    May you share freely, never taking more than you give.
29988 **
29989 ******************************************************************************
29990 **
29991 ** This file contains inline asm code for retrieving "high-performance"
29992 ** counters for x86 class CPUs.
29993 */
29994 #ifndef _HWTIME_H_
29995 #define _HWTIME_H_
29996
29997 /*
29998 ** The following routine only works on pentium-class (or newer) processors.
29999 ** It uses the RDTSC opcode to read the cycle count value out of the
30000 ** processor and returns that value.  This can be used for high-res
30001 ** profiling.
30002 */
30003 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30004       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30005
30006   #if defined(__GNUC__)
30007
30008   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30009      unsigned int lo, hi;
30010      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30011      return (sqlite_uint64)hi << 32 | lo;
30012   }
30013
30014   #elif defined(_MSC_VER)
30015
30016   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30017      __asm {
30018         rdtsc
30019         ret       ; return value at EDX:EAX
30020      }
30021   }
30022
30023   #endif
30024
30025 #elif (defined(__GNUC__) && defined(__x86_64__))
30026
30027   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30028       unsigned long val;
30029       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30030       return val;
30031   }
30032  
30033 #elif (defined(__GNUC__) && defined(__ppc__))
30034
30035   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30036       unsigned long long retval;
30037       unsigned long junk;
30038       __asm__ __volatile__ ("\n\
30039           1:      mftbu   %1\n\
30040                   mftb    %L0\n\
30041                   mftbu   %0\n\
30042                   cmpw    %0,%1\n\
30043                   bne     1b"
30044                   : "=r" (retval), "=r" (junk));
30045       return retval;
30046   }
30047
30048 #else
30049
30050   #error Need implementation of sqlite3Hwtime() for your platform.
30051
30052   /*
30053   ** To compile without implementing sqlite3Hwtime() for your platform,
30054   ** you can remove the above #error and use the following
30055   ** stub function.  You will lose timing support for many
30056   ** of the debugging and testing utilities, but it should at
30057   ** least compile and run.
30058   */
30059 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30060
30061 #endif
30062
30063 #endif /* !defined(_HWTIME_H_) */
30064
30065 /************** End of hwtime.h **********************************************/
30066 /************** Continuing where we left off in os_common.h ******************/
30067
30068 static sqlite_uint64 g_start;
30069 static sqlite_uint64 g_elapsed;
30070 #define TIMER_START       g_start=sqlite3Hwtime()
30071 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30072 #define TIMER_ELAPSED     g_elapsed
30073 #else
30074 #define TIMER_START
30075 #define TIMER_END
30076 #define TIMER_ELAPSED     ((sqlite_uint64)0)
30077 #endif
30078
30079 /*
30080 ** If we compile with the SQLITE_TEST macro set, then the following block
30081 ** of code will give us the ability to simulate a disk I/O error.  This
30082 ** is used for testing the I/O recovery logic.
30083 */
30084 #ifdef SQLITE_TEST
30085 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30086 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30087 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30088 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30089 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30090 SQLITE_API int sqlite3_diskfull_pending = 0;
30091 SQLITE_API int sqlite3_diskfull = 0;
30092 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30093 #define SimulateIOError(CODE)  \
30094   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30095        || sqlite3_io_error_pending-- == 1 )  \
30096               { local_ioerr(); CODE; }
30097 static void local_ioerr(){
30098   IOTRACE(("IOERR\n"));
30099   sqlite3_io_error_hit++;
30100   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30101 }
30102 #define SimulateDiskfullError(CODE) \
30103    if( sqlite3_diskfull_pending ){ \
30104      if( sqlite3_diskfull_pending == 1 ){ \
30105        local_ioerr(); \
30106        sqlite3_diskfull = 1; \
30107        sqlite3_io_error_hit = 1; \
30108        CODE; \
30109      }else{ \
30110        sqlite3_diskfull_pending--; \
30111      } \
30112    }
30113 #else
30114 #define SimulateIOErrorBenign(X)
30115 #define SimulateIOError(A)
30116 #define SimulateDiskfullError(A)
30117 #endif
30118
30119 /*
30120 ** When testing, keep a count of the number of open files.
30121 */
30122 #ifdef SQLITE_TEST
30123 SQLITE_API int sqlite3_open_file_count = 0;
30124 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
30125 #else
30126 #define OpenCounter(X)
30127 #endif
30128
30129 #endif /* !defined(_OS_COMMON_H_) */
30130
30131 /************** End of os_common.h *******************************************/
30132 /************** Continuing where we left off in os_win.c *********************/
30133
30134 /*
30135 ** Compiling and using WAL mode requires several APIs that are only
30136 ** available in Windows platforms based on the NT kernel.
30137 */
30138 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30139 # error "WAL mode requires support from the Windows NT kernel, compile\
30140  with SQLITE_OMIT_WAL."
30141 #endif
30142
30143 /*
30144 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30145 ** based on the sub-platform)?
30146 */
30147 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30148 #  define SQLITE_WIN32_HAS_ANSI
30149 #endif
30150
30151 /*
30152 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30153 ** based on the sub-platform)?
30154 */
30155 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30156 #  define SQLITE_WIN32_HAS_WIDE
30157 #endif
30158
30159 /*
30160 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
30161 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30162 ** are not present in the header file)?
30163 */
30164 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30165 /*
30166 ** Two of the file mapping APIs are different under WinRT.  Figure out which
30167 ** set we need.
30168 */
30169 #if SQLITE_OS_WINRT
30170 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30171         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30172
30173 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30174 #else
30175 #if defined(SQLITE_WIN32_HAS_ANSI)
30176 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30177         DWORD, DWORD, DWORD, LPCSTR);
30178 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30179
30180 #if defined(SQLITE_WIN32_HAS_WIDE)
30181 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30182         DWORD, DWORD, DWORD, LPCWSTR);
30183 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30184
30185 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30186 #endif /* SQLITE_OS_WINRT */
30187
30188 /*
30189 ** This file mapping API is common to both Win32 and WinRT.
30190 */
30191 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30192 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30193
30194 /*
30195 ** Macro to find the minimum of two numeric values.
30196 */
30197 #ifndef MIN
30198 # define MIN(x,y) ((x)<(y)?(x):(y))
30199 #endif
30200
30201 /*
30202 ** Some Microsoft compilers lack this definition.
30203 */
30204 #ifndef INVALID_FILE_ATTRIBUTES
30205 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
30206 #endif
30207
30208 #ifndef FILE_FLAG_MASK
30209 # define FILE_FLAG_MASK          (0xFF3C0000)
30210 #endif
30211
30212 #ifndef FILE_ATTRIBUTE_MASK
30213 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
30214 #endif
30215
30216 #ifndef SQLITE_OMIT_WAL
30217 /* Forward references */
30218 typedef struct winShm winShm;           /* A connection to shared-memory */
30219 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
30220 #endif
30221
30222 /*
30223 ** WinCE lacks native support for file locking so we have to fake it
30224 ** with some code of our own.
30225 */
30226 #if SQLITE_OS_WINCE
30227 typedef struct winceLock {
30228   int nReaders;       /* Number of reader locks obtained */
30229   BOOL bPending;      /* Indicates a pending lock has been obtained */
30230   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
30231   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
30232 } winceLock;
30233 #endif
30234
30235 /*
30236 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
30237 ** portability layer.
30238 */
30239 typedef struct winFile winFile;
30240 struct winFile {
30241   const sqlite3_io_methods *pMethod; /*** Must be first ***/
30242   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
30243   HANDLE h;               /* Handle for accessing the file */
30244   u8 locktype;            /* Type of lock currently held on this file */
30245   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
30246   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
30247   DWORD lastErrno;        /* The Windows errno from the last I/O error */
30248 #ifndef SQLITE_OMIT_WAL
30249   winShm *pShm;           /* Instance of shared memory on this file */
30250 #endif
30251   const char *zPath;      /* Full pathname of this file */
30252   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
30253 #if SQLITE_OS_WINCE
30254   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
30255   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
30256   HANDLE hShared;         /* Shared memory segment used for locking */
30257   winceLock local;        /* Locks obtained by this instance of winFile */
30258   winceLock *shared;      /* Global shared lock memory for the file  */
30259 #endif
30260 };
30261
30262 /*
30263 ** Allowed values for winFile.ctrlFlags
30264 */
30265 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
30266 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30267
30268 /*
30269  * The size of the buffer used by sqlite3_win32_write_debug().
30270  */
30271 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
30272 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
30273 #endif
30274
30275 /*
30276  * The value used with sqlite3_win32_set_directory() to specify that
30277  * the data directory should be changed.
30278  */
30279 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30280 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30281 #endif
30282
30283 /*
30284  * The value used with sqlite3_win32_set_directory() to specify that
30285  * the temporary directory should be changed.
30286  */
30287 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30288 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30289 #endif
30290
30291 /*
30292  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30293  * various Win32 API heap functions instead of our own.
30294  */
30295 #ifdef SQLITE_WIN32_MALLOC
30296
30297 /*
30298  * If this is non-zero, an isolated heap will be created by the native Win32
30299  * allocator subsystem; otherwise, the default process heap will be used.  This
30300  * setting has no effect when compiling for WinRT.  By default, this is enabled
30301  * and an isolated heap will be created to store all allocated data.
30302  *
30303  ******************************************************************************
30304  * WARNING: It is important to note that when this setting is non-zero and the
30305  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30306  *          function), all data that was allocated using the isolated heap will
30307  *          be freed immediately and any attempt to access any of that freed
30308  *          data will almost certainly result in an immediate access violation.
30309  ******************************************************************************
30310  */
30311 #ifndef SQLITE_WIN32_HEAP_CREATE
30312 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30313 #endif
30314
30315 /*
30316  * The initial size of the Win32-specific heap.  This value may be zero.
30317  */
30318 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30319 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30320                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30321 #endif
30322
30323 /*
30324  * The maximum size of the Win32-specific heap.  This value may be zero.
30325  */
30326 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30327 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30328 #endif
30329
30330 /*
30331  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30332  * zero for the default behavior.
30333  */
30334 #ifndef SQLITE_WIN32_HEAP_FLAGS
30335 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
30336 #endif
30337
30338 /*
30339 ** The winMemData structure stores information required by the Win32-specific
30340 ** sqlite3_mem_methods implementation.
30341 */
30342 typedef struct winMemData winMemData;
30343 struct winMemData {
30344 #ifndef NDEBUG
30345   u32 magic;    /* Magic number to detect structure corruption. */
30346 #endif
30347   HANDLE hHeap; /* The handle to our heap. */
30348   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30349 };
30350
30351 #ifndef NDEBUG
30352 #define WINMEM_MAGIC     0x42b2830b
30353 #endif
30354
30355 static struct winMemData win_mem_data = {
30356 #ifndef NDEBUG
30357   WINMEM_MAGIC,
30358 #endif
30359   NULL, FALSE
30360 };
30361
30362 #ifndef NDEBUG
30363 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30364 #else
30365 #define winMemAssertMagic()
30366 #endif
30367
30368 #define winMemGetHeap() win_mem_data.hHeap
30369
30370 static void *winMemMalloc(int nBytes);
30371 static void winMemFree(void *pPrior);
30372 static void *winMemRealloc(void *pPrior, int nBytes);
30373 static int winMemSize(void *p);
30374 static int winMemRoundup(int n);
30375 static int winMemInit(void *pAppData);
30376 static void winMemShutdown(void *pAppData);
30377
30378 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30379 #endif /* SQLITE_WIN32_MALLOC */
30380
30381 /*
30382 ** The following variable is (normally) set once and never changes
30383 ** thereafter.  It records whether the operating system is Win9x
30384 ** or WinNT.
30385 **
30386 ** 0:   Operating system unknown.
30387 ** 1:   Operating system is Win9x.
30388 ** 2:   Operating system is WinNT.
30389 **
30390 ** In order to facilitate testing on a WinNT system, the test fixture
30391 ** can manually set this value to 1 to emulate Win98 behavior.
30392 */
30393 #ifdef SQLITE_TEST
30394 SQLITE_API int sqlite3_os_type = 0;
30395 #else
30396 static int sqlite3_os_type = 0;
30397 #endif
30398
30399 #ifndef SYSCALL
30400 #  define SYSCALL sqlite3_syscall_ptr
30401 #endif
30402
30403 /*
30404 ** This function is not available on Windows CE or WinRT.
30405  */
30406
30407 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30408 #  define osAreFileApisANSI()       1
30409 #endif
30410
30411 /*
30412 ** Many system calls are accessed through pointer-to-functions so that
30413 ** they may be overridden at runtime to facilitate fault injection during
30414 ** testing and sandboxing.  The following array holds the names and pointers
30415 ** to all overrideable system calls.
30416 */
30417 static struct win_syscall {
30418   const char *zName;            /* Name of the sytem call */
30419   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30420   sqlite3_syscall_ptr pDefault; /* Default value */
30421 } aSyscall[] = {
30422 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30423   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
30424 #else
30425   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
30426 #endif
30427
30428 #ifndef osAreFileApisANSI
30429 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
30430 #endif
30431
30432 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30433   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
30434 #else
30435   { "CharLowerW",              (SYSCALL)0,                       0 },
30436 #endif
30437
30438 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
30439
30440 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30441   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
30442 #else
30443   { "CharUpperW",              (SYSCALL)0,                       0 },
30444 #endif
30445
30446 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
30447
30448   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
30449
30450 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
30451
30452 #if defined(SQLITE_WIN32_HAS_ANSI)
30453   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
30454 #else
30455   { "CreateFileA",             (SYSCALL)0,                       0 },
30456 #endif
30457
30458 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
30459         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
30460
30461 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30462   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
30463 #else
30464   { "CreateFileW",             (SYSCALL)0,                       0 },
30465 #endif
30466
30467 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
30468         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
30469
30470 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
30471         !defined(SQLITE_OMIT_WAL))
30472   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
30473 #else
30474   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
30475 #endif
30476
30477 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30478         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
30479
30480 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30481         !defined(SQLITE_OMIT_WAL))
30482   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
30483 #else
30484   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
30485 #endif
30486
30487 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30488         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
30489
30490 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30491   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
30492 #else
30493   { "CreateMutexW",            (SYSCALL)0,                       0 },
30494 #endif
30495
30496 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
30497         LPCWSTR))aSyscall[8].pCurrent)
30498
30499 #if defined(SQLITE_WIN32_HAS_ANSI)
30500   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
30501 #else
30502   { "DeleteFileA",             (SYSCALL)0,                       0 },
30503 #endif
30504
30505 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
30506
30507 #if defined(SQLITE_WIN32_HAS_WIDE)
30508   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
30509 #else
30510   { "DeleteFileW",             (SYSCALL)0,                       0 },
30511 #endif
30512
30513 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
30514
30515 #if SQLITE_OS_WINCE
30516   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
30517 #else
30518   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
30519 #endif
30520
30521 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30522         LPFILETIME))aSyscall[11].pCurrent)
30523
30524 #if SQLITE_OS_WINCE
30525   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
30526 #else
30527   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
30528 #endif
30529
30530 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30531         LPSYSTEMTIME))aSyscall[12].pCurrent)
30532
30533   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
30534
30535 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
30536
30537 #if defined(SQLITE_WIN32_HAS_ANSI)
30538   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
30539 #else
30540   { "FormatMessageA",          (SYSCALL)0,                       0 },
30541 #endif
30542
30543 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
30544         DWORD,va_list*))aSyscall[14].pCurrent)
30545
30546 #if defined(SQLITE_WIN32_HAS_WIDE)
30547   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
30548 #else
30549   { "FormatMessageW",          (SYSCALL)0,                       0 },
30550 #endif
30551
30552 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
30553         DWORD,va_list*))aSyscall[15].pCurrent)
30554
30555 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30556   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
30557 #else
30558   { "FreeLibrary",             (SYSCALL)0,                       0 },
30559 #endif
30560
30561 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
30562
30563   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
30564
30565 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
30566
30567 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30568   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
30569 #else
30570   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
30571 #endif
30572
30573 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
30574         LPDWORD))aSyscall[18].pCurrent)
30575
30576 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30577   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
30578 #else
30579   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
30580 #endif
30581
30582 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
30583         LPDWORD))aSyscall[19].pCurrent)
30584
30585 #if defined(SQLITE_WIN32_HAS_ANSI)
30586   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
30587 #else
30588   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
30589 #endif
30590
30591 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
30592
30593 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30594   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
30595 #else
30596   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
30597 #endif
30598
30599 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
30600
30601 #if defined(SQLITE_WIN32_HAS_WIDE)
30602   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
30603 #else
30604   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
30605 #endif
30606
30607 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
30608         LPVOID))aSyscall[22].pCurrent)
30609
30610 #if !SQLITE_OS_WINRT
30611   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
30612 #else
30613   { "GetFileSize",             (SYSCALL)0,                       0 },
30614 #endif
30615
30616 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
30617
30618 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30619   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
30620 #else
30621   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
30622 #endif
30623
30624 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
30625         LPSTR*))aSyscall[24].pCurrent)
30626
30627 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30628   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
30629 #else
30630   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
30631 #endif
30632
30633 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
30634         LPWSTR*))aSyscall[25].pCurrent)
30635
30636   { "GetLastError",            (SYSCALL)GetLastError,            0 },
30637
30638 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
30639
30640 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30641 #if SQLITE_OS_WINCE
30642   /* The GetProcAddressA() routine is only available on Windows CE. */
30643   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
30644 #else
30645   /* All other Windows platforms expect GetProcAddress() to take
30646   ** an ANSI string regardless of the _UNICODE setting */
30647   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
30648 #endif
30649 #else
30650   { "GetProcAddressA",         (SYSCALL)0,                       0 },
30651 #endif
30652
30653 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
30654         LPCSTR))aSyscall[27].pCurrent)
30655
30656 #if !SQLITE_OS_WINRT
30657   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
30658 #else
30659   { "GetSystemInfo",           (SYSCALL)0,                       0 },
30660 #endif
30661
30662 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
30663
30664   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
30665
30666 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
30667
30668 #if !SQLITE_OS_WINCE
30669   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
30670 #else
30671   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
30672 #endif
30673
30674 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
30675         LPFILETIME))aSyscall[30].pCurrent)
30676
30677 #if defined(SQLITE_WIN32_HAS_ANSI)
30678   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
30679 #else
30680   { "GetTempPathA",            (SYSCALL)0,                       0 },
30681 #endif
30682
30683 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
30684
30685 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30686   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
30687 #else
30688   { "GetTempPathW",            (SYSCALL)0,                       0 },
30689 #endif
30690
30691 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
30692
30693 #if !SQLITE_OS_WINRT
30694   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
30695 #else
30696   { "GetTickCount",            (SYSCALL)0,                       0 },
30697 #endif
30698
30699 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
30700
30701 #if defined(SQLITE_WIN32_HAS_ANSI)
30702   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
30703 #else
30704   { "GetVersionExA",           (SYSCALL)0,                       0 },
30705 #endif
30706
30707 #define osGetVersionExA ((BOOL(WINAPI*)( \
30708         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
30709
30710   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
30711
30712 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
30713         SIZE_T))aSyscall[35].pCurrent)
30714
30715 #if !SQLITE_OS_WINRT
30716   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
30717 #else
30718   { "HeapCreate",              (SYSCALL)0,                       0 },
30719 #endif
30720
30721 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
30722         SIZE_T))aSyscall[36].pCurrent)
30723
30724 #if !SQLITE_OS_WINRT
30725   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
30726 #else
30727   { "HeapDestroy",             (SYSCALL)0,                       0 },
30728 #endif
30729
30730 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
30731
30732   { "HeapFree",                (SYSCALL)HeapFree,                0 },
30733
30734 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
30735
30736   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
30737
30738 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
30739         SIZE_T))aSyscall[39].pCurrent)
30740
30741   { "HeapSize",                (SYSCALL)HeapSize,                0 },
30742
30743 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
30744         LPCVOID))aSyscall[40].pCurrent)
30745
30746 #if !SQLITE_OS_WINRT
30747   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
30748 #else
30749   { "HeapValidate",            (SYSCALL)0,                       0 },
30750 #endif
30751
30752 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
30753         LPCVOID))aSyscall[41].pCurrent)
30754
30755 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
30756   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
30757 #else
30758   { "LoadLibraryA",            (SYSCALL)0,                       0 },
30759 #endif
30760
30761 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
30762
30763 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30764         !defined(SQLITE_OMIT_LOAD_EXTENSION)
30765   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
30766 #else
30767   { "LoadLibraryW",            (SYSCALL)0,                       0 },
30768 #endif
30769
30770 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
30771
30772 #if !SQLITE_OS_WINRT
30773   { "LocalFree",               (SYSCALL)LocalFree,               0 },
30774 #else
30775   { "LocalFree",               (SYSCALL)0,                       0 },
30776 #endif
30777
30778 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
30779
30780 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30781   { "LockFile",                (SYSCALL)LockFile,                0 },
30782 #else
30783   { "LockFile",                (SYSCALL)0,                       0 },
30784 #endif
30785
30786 #ifndef osLockFile
30787 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30788         DWORD))aSyscall[45].pCurrent)
30789 #endif
30790
30791 #if !SQLITE_OS_WINCE
30792   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
30793 #else
30794   { "LockFileEx",              (SYSCALL)0,                       0 },
30795 #endif
30796
30797 #ifndef osLockFileEx
30798 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
30799         LPOVERLAPPED))aSyscall[46].pCurrent)
30800 #endif
30801
30802 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
30803   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
30804 #else
30805   { "MapViewOfFile",           (SYSCALL)0,                       0 },
30806 #endif
30807
30808 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30809         SIZE_T))aSyscall[47].pCurrent)
30810
30811   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
30812
30813 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
30814         int))aSyscall[48].pCurrent)
30815
30816   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
30817
30818 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
30819         LARGE_INTEGER*))aSyscall[49].pCurrent)
30820
30821   { "ReadFile",                (SYSCALL)ReadFile,                0 },
30822
30823 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
30824         LPOVERLAPPED))aSyscall[50].pCurrent)
30825
30826   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
30827
30828 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
30829
30830 #if !SQLITE_OS_WINRT
30831   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
30832 #else
30833   { "SetFilePointer",          (SYSCALL)0,                       0 },
30834 #endif
30835
30836 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
30837         DWORD))aSyscall[52].pCurrent)
30838
30839 #if !SQLITE_OS_WINRT
30840   { "Sleep",                   (SYSCALL)Sleep,                   0 },
30841 #else
30842   { "Sleep",                   (SYSCALL)0,                       0 },
30843 #endif
30844
30845 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
30846
30847   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
30848
30849 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
30850         LPFILETIME))aSyscall[54].pCurrent)
30851
30852 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30853   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
30854 #else
30855   { "UnlockFile",              (SYSCALL)0,                       0 },
30856 #endif
30857
30858 #ifndef osUnlockFile
30859 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30860         DWORD))aSyscall[55].pCurrent)
30861 #endif
30862
30863 #if !SQLITE_OS_WINCE
30864   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
30865 #else
30866   { "UnlockFileEx",            (SYSCALL)0,                       0 },
30867 #endif
30868
30869 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30870         LPOVERLAPPED))aSyscall[56].pCurrent)
30871
30872 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
30873   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
30874 #else
30875   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
30876 #endif
30877
30878 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
30879
30880   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
30881
30882 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
30883         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
30884
30885   { "WriteFile",               (SYSCALL)WriteFile,               0 },
30886
30887 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
30888         LPOVERLAPPED))aSyscall[59].pCurrent)
30889
30890 #if SQLITE_OS_WINRT
30891   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
30892 #else
30893   { "CreateEventExW",          (SYSCALL)0,                       0 },
30894 #endif
30895
30896 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
30897         DWORD,DWORD))aSyscall[60].pCurrent)
30898
30899 #if !SQLITE_OS_WINRT
30900   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
30901 #else
30902   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
30903 #endif
30904
30905 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
30906         DWORD))aSyscall[61].pCurrent)
30907
30908 #if SQLITE_OS_WINRT
30909   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
30910 #else
30911   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
30912 #endif
30913
30914 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
30915         BOOL))aSyscall[62].pCurrent)
30916
30917 #if SQLITE_OS_WINRT
30918   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
30919 #else
30920   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
30921 #endif
30922
30923 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
30924         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
30925
30926 #if SQLITE_OS_WINRT
30927   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
30928 #else
30929   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
30930 #endif
30931
30932 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
30933         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
30934
30935 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
30936   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
30937 #else
30938   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
30939 #endif
30940
30941 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
30942         SIZE_T))aSyscall[65].pCurrent)
30943
30944 #if SQLITE_OS_WINRT
30945   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
30946 #else
30947   { "CreateFile2",             (SYSCALL)0,                       0 },
30948 #endif
30949
30950 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
30951         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
30952
30953 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
30954   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
30955 #else
30956   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
30957 #endif
30958
30959 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
30960         DWORD))aSyscall[67].pCurrent)
30961
30962 #if SQLITE_OS_WINRT
30963   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
30964 #else
30965   { "GetTickCount64",          (SYSCALL)0,                       0 },
30966 #endif
30967
30968 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
30969
30970 #if SQLITE_OS_WINRT
30971   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
30972 #else
30973   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
30974 #endif
30975
30976 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
30977         LPSYSTEM_INFO))aSyscall[69].pCurrent)
30978
30979 #if defined(SQLITE_WIN32_HAS_ANSI)
30980   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
30981 #else
30982   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
30983 #endif
30984
30985 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
30986
30987 #if defined(SQLITE_WIN32_HAS_WIDE)
30988   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
30989 #else
30990   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
30991 #endif
30992
30993 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
30994
30995   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
30996
30997 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
30998
30999 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31000   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31001 #else
31002   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
31003 #endif
31004
31005 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31006         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31007
31008 }; /* End of the overrideable system calls */
31009
31010 /*
31011 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31012 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
31013 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31014 ** system call named zName.
31015 */
31016 static int winSetSystemCall(
31017   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
31018   const char *zName,            /* Name of system call to override */
31019   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
31020 ){
31021   unsigned int i;
31022   int rc = SQLITE_NOTFOUND;
31023
31024   UNUSED_PARAMETER(pNotUsed);
31025   if( zName==0 ){
31026     /* If no zName is given, restore all system calls to their default
31027     ** settings and return NULL
31028     */
31029     rc = SQLITE_OK;
31030     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31031       if( aSyscall[i].pDefault ){
31032         aSyscall[i].pCurrent = aSyscall[i].pDefault;
31033       }
31034     }
31035   }else{
31036     /* If zName is specified, operate on only the one system call
31037     ** specified.
31038     */
31039     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31040       if( strcmp(zName, aSyscall[i].zName)==0 ){
31041         if( aSyscall[i].pDefault==0 ){
31042           aSyscall[i].pDefault = aSyscall[i].pCurrent;
31043         }
31044         rc = SQLITE_OK;
31045         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31046         aSyscall[i].pCurrent = pNewFunc;
31047         break;
31048       }
31049     }
31050   }
31051   return rc;
31052 }
31053
31054 /*
31055 ** Return the value of a system call.  Return NULL if zName is not a
31056 ** recognized system call name.  NULL is also returned if the system call
31057 ** is currently undefined.
31058 */
31059 static sqlite3_syscall_ptr winGetSystemCall(
31060   sqlite3_vfs *pNotUsed,
31061   const char *zName
31062 ){
31063   unsigned int i;
31064
31065   UNUSED_PARAMETER(pNotUsed);
31066   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31067     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31068   }
31069   return 0;
31070 }
31071
31072 /*
31073 ** Return the name of the first system call after zName.  If zName==NULL
31074 ** then return the name of the first system call.  Return NULL if zName
31075 ** is the last system call or if zName is not the name of a valid
31076 ** system call.
31077 */
31078 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31079   int i = -1;
31080
31081   UNUSED_PARAMETER(p);
31082   if( zName ){
31083     for(i=0; i<ArraySize(aSyscall)-1; i++){
31084       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31085     }
31086   }
31087   for(i++; i<ArraySize(aSyscall); i++){
31088     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31089   }
31090   return 0;
31091 }
31092
31093 /*
31094 ** This function outputs the specified (ANSI) string to the Win32 debugger
31095 ** (if available).
31096 */
31097
31098 SQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){
31099   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31100   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31101   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31102   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31103 #if defined(SQLITE_WIN32_HAS_ANSI)
31104   if( nMin>0 ){
31105     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31106     memcpy(zDbgBuf, zBuf, nMin);
31107     osOutputDebugStringA(zDbgBuf);
31108   }else{
31109     osOutputDebugStringA(zBuf);
31110   }
31111 #elif defined(SQLITE_WIN32_HAS_WIDE)
31112   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31113   if ( osMultiByteToWideChar(
31114           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31115           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31116     return;
31117   }
31118   osOutputDebugStringW((LPCWSTR)zDbgBuf);
31119 #else
31120   if( nMin>0 ){
31121     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31122     memcpy(zDbgBuf, zBuf, nMin);
31123     fprintf(stderr, "%s", zDbgBuf);
31124   }else{
31125     fprintf(stderr, "%s", zBuf);
31126   }
31127 #endif
31128 }
31129
31130 /*
31131 ** The following routine suspends the current thread for at least ms
31132 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
31133 */
31134 #if SQLITE_OS_WINRT
31135 static HANDLE sleepObj = NULL;
31136 #endif
31137
31138 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31139 #if SQLITE_OS_WINRT
31140   if ( sleepObj==NULL ){
31141     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31142                                 SYNCHRONIZE);
31143   }
31144   assert( sleepObj!=NULL );
31145   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31146 #else
31147   osSleep(milliseconds);
31148 #endif
31149 }
31150
31151 /*
31152 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31153 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31154 **
31155 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31156 ** the LockFileEx() API.  But we can still statically link against that
31157 ** API as long as we don't call it when running Win95/98/ME.  A call to
31158 ** this routine is used to determine if the host is Win95/98/ME or
31159 ** WinNT/2K/XP so that we will know whether or not we can safely call
31160 ** the LockFileEx() API.
31161 */
31162 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31163 # define isNT()  (1)
31164 #elif !defined(SQLITE_WIN32_HAS_WIDE)
31165 # define isNT()  (0)
31166 #else
31167   static int isNT(void){
31168     if( sqlite3_os_type==0 ){
31169       OSVERSIONINFOA sInfo;
31170       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31171       osGetVersionExA(&sInfo);
31172       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31173     }
31174     return sqlite3_os_type==2;
31175   }
31176 #endif
31177
31178 #ifdef SQLITE_WIN32_MALLOC
31179 /*
31180 ** Allocate nBytes of memory.
31181 */
31182 static void *winMemMalloc(int nBytes){
31183   HANDLE hHeap;
31184   void *p;
31185
31186   winMemAssertMagic();
31187   hHeap = winMemGetHeap();
31188   assert( hHeap!=0 );
31189   assert( hHeap!=INVALID_HANDLE_VALUE );
31190 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31191   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31192 #endif
31193   assert( nBytes>=0 );
31194   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31195   if( !p ){
31196     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31197                 nBytes, osGetLastError(), (void*)hHeap);
31198   }
31199   return p;
31200 }
31201
31202 /*
31203 ** Free memory.
31204 */
31205 static void winMemFree(void *pPrior){
31206   HANDLE hHeap;
31207
31208   winMemAssertMagic();
31209   hHeap = winMemGetHeap();
31210   assert( hHeap!=0 );
31211   assert( hHeap!=INVALID_HANDLE_VALUE );
31212 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31213   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31214 #endif
31215   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31216   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31217     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31218                 pPrior, osGetLastError(), (void*)hHeap);
31219   }
31220 }
31221
31222 /*
31223 ** Change the size of an existing memory allocation
31224 */
31225 static void *winMemRealloc(void *pPrior, int nBytes){
31226   HANDLE hHeap;
31227   void *p;
31228
31229   winMemAssertMagic();
31230   hHeap = winMemGetHeap();
31231   assert( hHeap!=0 );
31232   assert( hHeap!=INVALID_HANDLE_VALUE );
31233 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31234   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31235 #endif
31236   assert( nBytes>=0 );
31237   if( !pPrior ){
31238     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31239   }else{
31240     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31241   }
31242   if( !p ){
31243     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31244                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31245                 (void*)hHeap);
31246   }
31247   return p;
31248 }
31249
31250 /*
31251 ** Return the size of an outstanding allocation, in bytes.
31252 */
31253 static int winMemSize(void *p){
31254   HANDLE hHeap;
31255   SIZE_T n;
31256
31257   winMemAssertMagic();
31258   hHeap = winMemGetHeap();
31259   assert( hHeap!=0 );
31260   assert( hHeap!=INVALID_HANDLE_VALUE );
31261 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31262   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31263 #endif
31264   if( !p ) return 0;
31265   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31266   if( n==(SIZE_T)-1 ){
31267     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31268                 p, osGetLastError(), (void*)hHeap);
31269     return 0;
31270   }
31271   return (int)n;
31272 }
31273
31274 /*
31275 ** Round up a request size to the next valid allocation size.
31276 */
31277 static int winMemRoundup(int n){
31278   return n;
31279 }
31280
31281 /*
31282 ** Initialize this module.
31283 */
31284 static int winMemInit(void *pAppData){
31285   winMemData *pWinMemData = (winMemData *)pAppData;
31286
31287   if( !pWinMemData ) return SQLITE_ERROR;
31288   assert( pWinMemData->magic==WINMEM_MAGIC );
31289
31290 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31291   if( !pWinMemData->hHeap ){
31292     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31293                                       SQLITE_WIN32_HEAP_INIT_SIZE,
31294                                       SQLITE_WIN32_HEAP_MAX_SIZE);
31295     if( !pWinMemData->hHeap ){
31296       sqlite3_log(SQLITE_NOMEM,
31297           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31298           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31299           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31300       return SQLITE_NOMEM;
31301     }
31302     pWinMemData->bOwned = TRUE;
31303     assert( pWinMemData->bOwned );
31304   }
31305 #else
31306   pWinMemData->hHeap = osGetProcessHeap();
31307   if( !pWinMemData->hHeap ){
31308     sqlite3_log(SQLITE_NOMEM,
31309         "failed to GetProcessHeap (%d)", osGetLastError());
31310     return SQLITE_NOMEM;
31311   }
31312   pWinMemData->bOwned = FALSE;
31313   assert( !pWinMemData->bOwned );
31314 #endif
31315   assert( pWinMemData->hHeap!=0 );
31316   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31317 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31318   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31319 #endif
31320   return SQLITE_OK;
31321 }
31322
31323 /*
31324 ** Deinitialize this module.
31325 */
31326 static void winMemShutdown(void *pAppData){
31327   winMemData *pWinMemData = (winMemData *)pAppData;
31328
31329   if( !pWinMemData ) return;
31330   if( pWinMemData->hHeap ){
31331     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31332 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31333     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31334 #endif
31335     if( pWinMemData->bOwned ){
31336       if( !osHeapDestroy(pWinMemData->hHeap) ){
31337         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31338                     osGetLastError(), (void*)pWinMemData->hHeap);
31339       }
31340       pWinMemData->bOwned = FALSE;
31341     }
31342     pWinMemData->hHeap = NULL;
31343   }
31344 }
31345
31346 /*
31347 ** Populate the low-level memory allocation function pointers in
31348 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31349 ** arguments specify the block of memory to manage.
31350 **
31351 ** This routine is only called by sqlite3_config(), and therefore
31352 ** is not required to be threadsafe (it is not).
31353 */
31354 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31355   static const sqlite3_mem_methods winMemMethods = {
31356     winMemMalloc,
31357     winMemFree,
31358     winMemRealloc,
31359     winMemSize,
31360     winMemRoundup,
31361     winMemInit,
31362     winMemShutdown,
31363     &win_mem_data
31364   };
31365   return &winMemMethods;
31366 }
31367
31368 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31369   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31370 }
31371 #endif /* SQLITE_WIN32_MALLOC */
31372
31373 /*
31374 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
31375 **
31376 ** Space to hold the returned string is obtained from malloc.
31377 */
31378 static LPWSTR utf8ToUnicode(const char *zFilename){
31379   int nChar;
31380   LPWSTR zWideFilename;
31381
31382   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31383   if( nChar==0 ){
31384     return 0;
31385   }
31386   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
31387   if( zWideFilename==0 ){
31388     return 0;
31389   }
31390   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
31391                                 nChar);
31392   if( nChar==0 ){
31393     sqlite3_free(zWideFilename);
31394     zWideFilename = 0;
31395   }
31396   return zWideFilename;
31397 }
31398
31399 /*
31400 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
31401 ** obtained from sqlite3_malloc().
31402 */
31403 static char *unicodeToUtf8(LPCWSTR zWideFilename){
31404   int nByte;
31405   char *zFilename;
31406
31407   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31408   if( nByte == 0 ){
31409     return 0;
31410   }
31411   zFilename = sqlite3MallocZero( nByte );
31412   if( zFilename==0 ){
31413     return 0;
31414   }
31415   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31416                                 0, 0);
31417   if( nByte == 0 ){
31418     sqlite3_free(zFilename);
31419     zFilename = 0;
31420   }
31421   return zFilename;
31422 }
31423
31424 /*
31425 ** Convert an ANSI string to Microsoft Unicode, based on the
31426 ** current codepage settings for file apis.
31427 ** 
31428 ** Space to hold the returned string is obtained
31429 ** from sqlite3_malloc.
31430 */
31431 static LPWSTR mbcsToUnicode(const char *zFilename){
31432   int nByte;
31433   LPWSTR zMbcsFilename;
31434   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31435
31436   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
31437                                 0)*sizeof(WCHAR);
31438   if( nByte==0 ){
31439     return 0;
31440   }
31441   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
31442   if( zMbcsFilename==0 ){
31443     return 0;
31444   }
31445   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
31446                                 nByte);
31447   if( nByte==0 ){
31448     sqlite3_free(zMbcsFilename);
31449     zMbcsFilename = 0;
31450   }
31451   return zMbcsFilename;
31452 }
31453
31454 /*
31455 ** Convert Microsoft Unicode to multi-byte character string, based on the
31456 ** user's ANSI codepage.
31457 **
31458 ** Space to hold the returned string is obtained from
31459 ** sqlite3_malloc().
31460 */
31461 static char *unicodeToMbcs(LPCWSTR zWideFilename){
31462   int nByte;
31463   char *zFilename;
31464   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31465
31466   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31467   if( nByte == 0 ){
31468     return 0;
31469   }
31470   zFilename = sqlite3MallocZero( nByte );
31471   if( zFilename==0 ){
31472     return 0;
31473   }
31474   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
31475                                 nByte, 0, 0);
31476   if( nByte == 0 ){
31477     sqlite3_free(zFilename);
31478     zFilename = 0;
31479   }
31480   return zFilename;
31481 }
31482
31483 /*
31484 ** Convert multibyte character string to UTF-8.  Space to hold the
31485 ** returned string is obtained from sqlite3_malloc().
31486 */
31487 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31488   char *zFilenameUtf8;
31489   LPWSTR zTmpWide;
31490
31491   zTmpWide = mbcsToUnicode(zFilename);
31492   if( zTmpWide==0 ){
31493     return 0;
31494   }
31495   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31496   sqlite3_free(zTmpWide);
31497   return zFilenameUtf8;
31498 }
31499
31500 /*
31501 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31502 ** returned string is obtained from sqlite3_malloc().
31503 */
31504 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
31505   char *zFilenameMbcs;
31506   LPWSTR zTmpWide;
31507
31508   zTmpWide = utf8ToUnicode(zFilename);
31509   if( zTmpWide==0 ){
31510     return 0;
31511   }
31512   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31513   sqlite3_free(zTmpWide);
31514   return zFilenameMbcs;
31515 }
31516
31517 /*
31518 ** This function sets the data directory or the temporary directory based on
31519 ** the provided arguments.  The type argument must be 1 in order to set the
31520 ** data directory or 2 in order to set the temporary directory.  The zValue
31521 ** argument is the name of the directory to use.  The return value will be
31522 ** SQLITE_OK if successful.
31523 */
31524 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
31525   char **ppDirectory = 0;
31526 #ifndef SQLITE_OMIT_AUTOINIT
31527   int rc = sqlite3_initialize();
31528   if( rc ) return rc;
31529 #endif
31530   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
31531     ppDirectory = &sqlite3_data_directory;
31532   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
31533     ppDirectory = &sqlite3_temp_directory;
31534   }
31535   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
31536           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31537   );
31538   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
31539   if( ppDirectory ){
31540     char *zValueUtf8 = 0;
31541     if( zValue && zValue[0] ){
31542       zValueUtf8 = unicodeToUtf8(zValue);
31543       if ( zValueUtf8==0 ){
31544         return SQLITE_NOMEM;
31545       }
31546     }
31547     sqlite3_free(*ppDirectory);
31548     *ppDirectory = zValueUtf8;
31549     return SQLITE_OK;
31550   }
31551   return SQLITE_ERROR;
31552 }
31553
31554 /*
31555 ** The return value of getLastErrorMsg
31556 ** is zero if the error message fits in the buffer, or non-zero
31557 ** otherwise (if the message was truncated).
31558 */
31559 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
31560   /* FormatMessage returns 0 on failure.  Otherwise it
31561   ** returns the number of TCHARs written to the output
31562   ** buffer, excluding the terminating null char.
31563   */
31564   DWORD dwLen = 0;
31565   char *zOut = 0;
31566
31567   if( isNT() ){
31568 #if SQLITE_OS_WINRT
31569     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
31570     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
31571                              FORMAT_MESSAGE_IGNORE_INSERTS,
31572                              NULL,
31573                              lastErrno,
31574                              0,
31575                              zTempWide,
31576                              MAX_PATH,
31577                              0);
31578 #else
31579     LPWSTR zTempWide = NULL;
31580     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31581                              FORMAT_MESSAGE_FROM_SYSTEM |
31582                              FORMAT_MESSAGE_IGNORE_INSERTS,
31583                              NULL,
31584                              lastErrno,
31585                              0,
31586                              (LPWSTR) &zTempWide,
31587                              0,
31588                              0);
31589 #endif
31590     if( dwLen > 0 ){
31591       /* allocate a buffer and convert to UTF8 */
31592       sqlite3BeginBenignMalloc();
31593       zOut = unicodeToUtf8(zTempWide);
31594       sqlite3EndBenignMalloc();
31595 #if !SQLITE_OS_WINRT
31596       /* free the system buffer allocated by FormatMessage */
31597       osLocalFree(zTempWide);
31598 #endif
31599     }
31600   }
31601 #ifdef SQLITE_WIN32_HAS_ANSI
31602   else{
31603     char *zTemp = NULL;
31604     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31605                              FORMAT_MESSAGE_FROM_SYSTEM |
31606                              FORMAT_MESSAGE_IGNORE_INSERTS,
31607                              NULL,
31608                              lastErrno,
31609                              0,
31610                              (LPSTR) &zTemp,
31611                              0,
31612                              0);
31613     if( dwLen > 0 ){
31614       /* allocate a buffer and convert to UTF8 */
31615       sqlite3BeginBenignMalloc();
31616       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31617       sqlite3EndBenignMalloc();
31618       /* free the system buffer allocated by FormatMessage */
31619       osLocalFree(zTemp);
31620     }
31621   }
31622 #endif
31623   if( 0 == dwLen ){
31624     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
31625   }else{
31626     /* copy a maximum of nBuf chars to output buffer */
31627     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31628     /* free the UTF8 buffer */
31629     sqlite3_free(zOut);
31630   }
31631   return 0;
31632 }
31633
31634 /*
31635 **
31636 ** This function - winLogErrorAtLine() - is only ever called via the macro
31637 ** winLogError().
31638 **
31639 ** This routine is invoked after an error occurs in an OS function.
31640 ** It logs a message using sqlite3_log() containing the current value of
31641 ** error code and, if possible, the human-readable equivalent from 
31642 ** FormatMessage.
31643 **
31644 ** The first argument passed to the macro should be the error code that
31645 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
31646 ** The two subsequent arguments should be the name of the OS function that
31647 ** failed and the associated file-system path, if any.
31648 */
31649 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
31650 static int winLogErrorAtLine(
31651   int errcode,                    /* SQLite error code */
31652   DWORD lastErrno,                /* Win32 last error */
31653   const char *zFunc,              /* Name of OS function that failed */
31654   const char *zPath,              /* File path associated with error */
31655   int iLine                       /* Source line number where error occurred */
31656 ){
31657   char zMsg[500];                 /* Human readable error text */
31658   int i;                          /* Loop counter */
31659
31660   zMsg[0] = 0;
31661   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
31662   assert( errcode!=SQLITE_OK );
31663   if( zPath==0 ) zPath = "";
31664   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
31665   zMsg[i] = 0;
31666   sqlite3_log(errcode,
31667       "os_win.c:%d: (%d) %s(%s) - %s",
31668       iLine, lastErrno, zFunc, zPath, zMsg
31669   );
31670
31671   return errcode;
31672 }
31673
31674 /*
31675 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
31676 ** will be retried following a locking error - probably caused by 
31677 ** antivirus software.  Also the initial delay before the first retry.
31678 ** The delay increases linearly with each retry.
31679 */
31680 #ifndef SQLITE_WIN32_IOERR_RETRY
31681 # define SQLITE_WIN32_IOERR_RETRY 10
31682 #endif
31683 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
31684 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
31685 #endif
31686 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
31687 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
31688
31689 /*
31690 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
31691 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
31692 ** to give up with an error.
31693 */
31694 static int retryIoerr(int *pnRetry, DWORD *pError){
31695   DWORD e = osGetLastError();
31696   if( *pnRetry>=win32IoerrRetry ){
31697     if( pError ){
31698       *pError = e;
31699     }
31700     return 0;
31701   }
31702   if( e==ERROR_ACCESS_DENIED ||
31703       e==ERROR_LOCK_VIOLATION ||
31704       e==ERROR_SHARING_VIOLATION ){
31705     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
31706     ++*pnRetry;
31707     return 1;
31708   }
31709   if( pError ){
31710     *pError = e;
31711   }
31712   return 0;
31713 }
31714
31715 /*
31716 ** Log a I/O error retry episode.
31717 */
31718 static void logIoerr(int nRetry){
31719   if( nRetry ){
31720     sqlite3_log(SQLITE_IOERR, 
31721       "delayed %dms for lock/sharing conflict",
31722       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
31723     );
31724   }
31725 }
31726
31727 #if SQLITE_OS_WINCE
31728 /*************************************************************************
31729 ** This section contains code for WinCE only.
31730 */
31731 /*
31732 ** Windows CE does not have a localtime() function.  So create a
31733 ** substitute.
31734 */
31735 /* #include <time.h> */
31736 struct tm *__cdecl localtime(const time_t *t)
31737 {
31738   static struct tm y;
31739   FILETIME uTm, lTm;
31740   SYSTEMTIME pTm;
31741   sqlite3_int64 t64;
31742   t64 = *t;
31743   t64 = (t64 + 11644473600)*10000000;
31744   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31745   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31746   osFileTimeToLocalFileTime(&uTm,&lTm);
31747   osFileTimeToSystemTime(&lTm,&pTm);
31748   y.tm_year = pTm.wYear - 1900;
31749   y.tm_mon = pTm.wMonth - 1;
31750   y.tm_wday = pTm.wDayOfWeek;
31751   y.tm_mday = pTm.wDay;
31752   y.tm_hour = pTm.wHour;
31753   y.tm_min = pTm.wMinute;
31754   y.tm_sec = pTm.wSecond;
31755   return &y;
31756 }
31757
31758 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31759
31760 /*
31761 ** Acquire a lock on the handle h
31762 */
31763 static void winceMutexAcquire(HANDLE h){
31764    DWORD dwErr;
31765    do {
31766      dwErr = osWaitForSingleObject(h, INFINITE);
31767    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31768 }
31769 /*
31770 ** Release a lock acquired by winceMutexAcquire()
31771 */
31772 #define winceMutexRelease(h) ReleaseMutex(h)
31773
31774 /*
31775 ** Create the mutex and shared memory used for locking in the file
31776 ** descriptor pFile
31777 */
31778 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31779   LPWSTR zTok;
31780   LPWSTR zName;
31781   BOOL bInit = TRUE;
31782
31783   zName = utf8ToUnicode(zFilename);
31784   if( zName==0 ){
31785     /* out of memory */
31786     return FALSE;
31787   }
31788
31789   /* Initialize the local lockdata */
31790   memset(&pFile->local, 0, sizeof(pFile->local));
31791
31792   /* Replace the backslashes from the filename and lowercase it
31793   ** to derive a mutex name. */
31794   zTok = osCharLowerW(zName);
31795   for (;*zTok;zTok++){
31796     if (*zTok == '\\') *zTok = '_';
31797   }
31798
31799   /* Create/open the named mutex */
31800   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
31801   if (!pFile->hMutex){
31802     pFile->lastErrno = osGetLastError();
31803     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
31804     sqlite3_free(zName);
31805     return FALSE;
31806   }
31807
31808   /* Acquire the mutex before continuing */
31809   winceMutexAcquire(pFile->hMutex);
31810   
31811   /* Since the names of named mutexes, semaphores, file mappings etc are 
31812   ** case-sensitive, take advantage of that by uppercasing the mutex name
31813   ** and using that as the shared filemapping name.
31814   */
31815   osCharUpperW(zName);
31816   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31817                                         PAGE_READWRITE, 0, sizeof(winceLock),
31818                                         zName);  
31819
31820   /* Set a flag that indicates we're the first to create the memory so it 
31821   ** must be zero-initialized */
31822   if (osGetLastError() == ERROR_ALREADY_EXISTS){
31823     bInit = FALSE;
31824   }
31825
31826   sqlite3_free(zName);
31827
31828   /* If we succeeded in making the shared memory handle, map it. */
31829   if (pFile->hShared){
31830     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
31831              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31832     /* If mapping failed, close the shared memory handle and erase it */
31833     if (!pFile->shared){
31834       pFile->lastErrno = osGetLastError();
31835       winLogError(SQLITE_ERROR, pFile->lastErrno,
31836                "winceCreateLock2", zFilename);
31837       osCloseHandle(pFile->hShared);
31838       pFile->hShared = NULL;
31839     }
31840   }
31841
31842   /* If shared memory could not be created, then close the mutex and fail */
31843   if (pFile->hShared == NULL){
31844     winceMutexRelease(pFile->hMutex);
31845     osCloseHandle(pFile->hMutex);
31846     pFile->hMutex = NULL;
31847     return FALSE;
31848   }
31849   
31850   /* Initialize the shared memory if we're supposed to */
31851   if (bInit) {
31852     memset(pFile->shared, 0, sizeof(winceLock));
31853   }
31854
31855   winceMutexRelease(pFile->hMutex);
31856   return TRUE;
31857 }
31858
31859 /*
31860 ** Destroy the part of winFile that deals with wince locks
31861 */
31862 static void winceDestroyLock(winFile *pFile){
31863   if (pFile->hMutex){
31864     /* Acquire the mutex */
31865     winceMutexAcquire(pFile->hMutex);
31866
31867     /* The following blocks should probably assert in debug mode, but they
31868        are to cleanup in case any locks remained open */
31869     if (pFile->local.nReaders){
31870       pFile->shared->nReaders --;
31871     }
31872     if (pFile->local.bReserved){
31873       pFile->shared->bReserved = FALSE;
31874     }
31875     if (pFile->local.bPending){
31876       pFile->shared->bPending = FALSE;
31877     }
31878     if (pFile->local.bExclusive){
31879       pFile->shared->bExclusive = FALSE;
31880     }
31881
31882     /* De-reference and close our copy of the shared memory handle */
31883     osUnmapViewOfFile(pFile->shared);
31884     osCloseHandle(pFile->hShared);
31885
31886     /* Done with the mutex */
31887     winceMutexRelease(pFile->hMutex);    
31888     osCloseHandle(pFile->hMutex);
31889     pFile->hMutex = NULL;
31890   }
31891 }
31892
31893 /* 
31894 ** An implementation of the LockFile() API of Windows for CE
31895 */
31896 static BOOL winceLockFile(
31897   LPHANDLE phFile,
31898   DWORD dwFileOffsetLow,
31899   DWORD dwFileOffsetHigh,
31900   DWORD nNumberOfBytesToLockLow,
31901   DWORD nNumberOfBytesToLockHigh
31902 ){
31903   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31904   BOOL bReturn = FALSE;
31905
31906   UNUSED_PARAMETER(dwFileOffsetHigh);
31907   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31908
31909   if (!pFile->hMutex) return TRUE;
31910   winceMutexAcquire(pFile->hMutex);
31911
31912   /* Wanting an exclusive lock? */
31913   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31914        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31915     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31916        pFile->shared->bExclusive = TRUE;
31917        pFile->local.bExclusive = TRUE;
31918        bReturn = TRUE;
31919     }
31920   }
31921
31922   /* Want a read-only lock? */
31923   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31924            nNumberOfBytesToLockLow == 1){
31925     if (pFile->shared->bExclusive == 0){
31926       pFile->local.nReaders ++;
31927       if (pFile->local.nReaders == 1){
31928         pFile->shared->nReaders ++;
31929       }
31930       bReturn = TRUE;
31931     }
31932   }
31933
31934   /* Want a pending lock? */
31935   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
31936     /* If no pending lock has been acquired, then acquire it */
31937     if (pFile->shared->bPending == 0) {
31938       pFile->shared->bPending = TRUE;
31939       pFile->local.bPending = TRUE;
31940       bReturn = TRUE;
31941     }
31942   }
31943
31944   /* Want a reserved lock? */
31945   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
31946     if (pFile->shared->bReserved == 0) {
31947       pFile->shared->bReserved = TRUE;
31948       pFile->local.bReserved = TRUE;
31949       bReturn = TRUE;
31950     }
31951   }
31952
31953   winceMutexRelease(pFile->hMutex);
31954   return bReturn;
31955 }
31956
31957 /*
31958 ** An implementation of the UnlockFile API of Windows for CE
31959 */
31960 static BOOL winceUnlockFile(
31961   LPHANDLE phFile,
31962   DWORD dwFileOffsetLow,
31963   DWORD dwFileOffsetHigh,
31964   DWORD nNumberOfBytesToUnlockLow,
31965   DWORD nNumberOfBytesToUnlockHigh
31966 ){
31967   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31968   BOOL bReturn = FALSE;
31969
31970   UNUSED_PARAMETER(dwFileOffsetHigh);
31971   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
31972
31973   if (!pFile->hMutex) return TRUE;
31974   winceMutexAcquire(pFile->hMutex);
31975
31976   /* Releasing a reader lock or an exclusive lock */
31977   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
31978     /* Did we have an exclusive lock? */
31979     if (pFile->local.bExclusive){
31980       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
31981       pFile->local.bExclusive = FALSE;
31982       pFile->shared->bExclusive = FALSE;
31983       bReturn = TRUE;
31984     }
31985
31986     /* Did we just have a reader lock? */
31987     else if (pFile->local.nReaders){
31988       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
31989       pFile->local.nReaders --;
31990       if (pFile->local.nReaders == 0)
31991       {
31992         pFile->shared->nReaders --;
31993       }
31994       bReturn = TRUE;
31995     }
31996   }
31997
31998   /* Releasing a pending lock */
31999   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
32000     if (pFile->local.bPending){
32001       pFile->local.bPending = FALSE;
32002       pFile->shared->bPending = FALSE;
32003       bReturn = TRUE;
32004     }
32005   }
32006   /* Releasing a reserved lock */
32007   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
32008     if (pFile->local.bReserved) {
32009       pFile->local.bReserved = FALSE;
32010       pFile->shared->bReserved = FALSE;
32011       bReturn = TRUE;
32012     }
32013   }
32014
32015   winceMutexRelease(pFile->hMutex);
32016   return bReturn;
32017 }
32018 /*
32019 ** End of the special code for wince
32020 *****************************************************************************/
32021 #endif /* SQLITE_OS_WINCE */
32022
32023 /*
32024 ** Lock a file region.
32025 */
32026 static BOOL winLockFile(
32027   LPHANDLE phFile,
32028   DWORD flags,
32029   DWORD offsetLow,
32030   DWORD offsetHigh,
32031   DWORD numBytesLow,
32032   DWORD numBytesHigh
32033 ){
32034 #if SQLITE_OS_WINCE
32035   /*
32036   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32037   **       API LockFile.
32038   */
32039   return winceLockFile(phFile, offsetLow, offsetHigh,
32040                        numBytesLow, numBytesHigh);
32041 #else
32042   if( isNT() ){
32043     OVERLAPPED ovlp;
32044     memset(&ovlp, 0, sizeof(OVERLAPPED));
32045     ovlp.Offset = offsetLow;
32046     ovlp.OffsetHigh = offsetHigh;
32047     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32048   }else{
32049     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32050                       numBytesHigh);
32051   }
32052 #endif
32053 }
32054
32055 /*
32056 ** Unlock a file region.
32057  */
32058 static BOOL winUnlockFile(
32059   LPHANDLE phFile,
32060   DWORD offsetLow,
32061   DWORD offsetHigh,
32062   DWORD numBytesLow,
32063   DWORD numBytesHigh
32064 ){
32065 #if SQLITE_OS_WINCE
32066   /*
32067   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32068   **       API UnlockFile.
32069   */
32070   return winceUnlockFile(phFile, offsetLow, offsetHigh,
32071                          numBytesLow, numBytesHigh);
32072 #else
32073   if( isNT() ){
32074     OVERLAPPED ovlp;
32075     memset(&ovlp, 0, sizeof(OVERLAPPED));
32076     ovlp.Offset = offsetLow;
32077     ovlp.OffsetHigh = offsetHigh;
32078     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32079   }else{
32080     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32081                         numBytesHigh);
32082   }
32083 #endif
32084 }
32085
32086 /*****************************************************************************
32087 ** The next group of routines implement the I/O methods specified
32088 ** by the sqlite3_io_methods object.
32089 ******************************************************************************/
32090
32091 /*
32092 ** Some Microsoft compilers lack this definition.
32093 */
32094 #ifndef INVALID_SET_FILE_POINTER
32095 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32096 #endif
32097
32098 /*
32099 ** Move the current position of the file handle passed as the first 
32100 ** argument to offset iOffset within the file. If successful, return 0. 
32101 ** Otherwise, set pFile->lastErrno and return non-zero.
32102 */
32103 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32104 #if !SQLITE_OS_WINRT
32105   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32106   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32107   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32108   DWORD lastErrno;                /* Value returned by GetLastError() */
32109
32110   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32111   lowerBits = (LONG)(iOffset & 0xffffffff);
32112
32113   /* API oddity: If successful, SetFilePointer() returns a dword 
32114   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32115   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
32116   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
32117   ** whether an error has actually occured, it is also necessary to call 
32118   ** GetLastError().
32119   */
32120   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32121
32122   if( (dwRet==INVALID_SET_FILE_POINTER
32123       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32124     pFile->lastErrno = lastErrno;
32125     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32126              "seekWinFile", pFile->zPath);
32127     return 1;
32128   }
32129
32130   return 0;
32131 #else
32132   /*
32133   ** Same as above, except that this implementation works for WinRT.
32134   */
32135
32136   LARGE_INTEGER x;                /* The new offset */
32137   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
32138
32139   x.QuadPart = iOffset;
32140   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32141
32142   if(!bRet){
32143     pFile->lastErrno = osGetLastError();
32144     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32145              "seekWinFile", pFile->zPath);
32146     return 1;
32147   }
32148
32149   return 0;
32150 #endif
32151 }
32152
32153 /*
32154 ** Close a file.
32155 **
32156 ** It is reported that an attempt to close a handle might sometimes
32157 ** fail.  This is a very unreasonable result, but Windows is notorious
32158 ** for being unreasonable so I do not doubt that it might happen.  If
32159 ** the close fails, we pause for 100 milliseconds and try again.  As
32160 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32161 ** giving up and returning an error.
32162 */
32163 #define MX_CLOSE_ATTEMPT 3
32164 static int winClose(sqlite3_file *id){
32165   int rc, cnt = 0;
32166   winFile *pFile = (winFile*)id;
32167
32168   assert( id!=0 );
32169 #ifndef SQLITE_OMIT_WAL
32170   assert( pFile->pShm==0 );
32171 #endif
32172   OSTRACE(("CLOSE %d\n", pFile->h));
32173   do{
32174     rc = osCloseHandle(pFile->h);
32175     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32176   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32177 #if SQLITE_OS_WINCE
32178 #define WINCE_DELETION_ATTEMPTS 3
32179   winceDestroyLock(pFile);
32180   if( pFile->zDeleteOnClose ){
32181     int cnt = 0;
32182     while(
32183            osDeleteFileW(pFile->zDeleteOnClose)==0
32184         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
32185         && cnt++ < WINCE_DELETION_ATTEMPTS
32186     ){
32187        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
32188     }
32189     sqlite3_free(pFile->zDeleteOnClose);
32190   }
32191 #endif
32192   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32193   if( rc ){
32194     pFile->h = NULL;
32195   }
32196   OpenCounter(-1);
32197   return rc ? SQLITE_OK
32198             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32199                           "winClose", pFile->zPath);
32200 }
32201
32202 /*
32203 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32204 ** bytes were read successfully and SQLITE_IOERR if anything goes
32205 ** wrong.
32206 */
32207 static int winRead(
32208   sqlite3_file *id,          /* File to read from */
32209   void *pBuf,                /* Write content into this buffer */
32210   int amt,                   /* Number of bytes to read */
32211   sqlite3_int64 offset       /* Begin reading at this offset */
32212 ){
32213 #if !SQLITE_OS_WINCE
32214   OVERLAPPED overlapped;          /* The offset for ReadFile. */
32215 #endif
32216   winFile *pFile = (winFile*)id;  /* file handle */
32217   DWORD nRead;                    /* Number of bytes actually read from file */
32218   int nRetry = 0;                 /* Number of retrys */
32219
32220   assert( id!=0 );
32221   SimulateIOError(return SQLITE_IOERR_READ);
32222   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32223
32224 #if SQLITE_OS_WINCE
32225   if( seekWinFile(pFile, offset) ){
32226     return SQLITE_FULL;
32227   }
32228   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32229 #else
32230   memset(&overlapped, 0, sizeof(OVERLAPPED));
32231   overlapped.Offset = (LONG)(offset & 0xffffffff);
32232   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32233   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32234          osGetLastError()!=ERROR_HANDLE_EOF ){
32235 #endif
32236     DWORD lastErrno;
32237     if( retryIoerr(&nRetry, &lastErrno) ) continue;
32238     pFile->lastErrno = lastErrno;
32239     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32240              "winRead", pFile->zPath);
32241   }
32242   logIoerr(nRetry);
32243   if( nRead<(DWORD)amt ){
32244     /* Unread parts of the buffer must be zero-filled */
32245     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32246     return SQLITE_IOERR_SHORT_READ;
32247   }
32248
32249   return SQLITE_OK;
32250 }
32251
32252 /*
32253 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32254 ** or some other error code on failure.
32255 */
32256 static int winWrite(
32257   sqlite3_file *id,               /* File to write into */
32258   const void *pBuf,               /* The bytes to be written */
32259   int amt,                        /* Number of bytes to write */
32260   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32261 ){
32262   int rc = 0;                     /* True if error has occured, else false */
32263   winFile *pFile = (winFile*)id;  /* File handle */
32264   int nRetry = 0;                 /* Number of retries */
32265
32266   assert( amt>0 );
32267   assert( pFile );
32268   SimulateIOError(return SQLITE_IOERR_WRITE);
32269   SimulateDiskfullError(return SQLITE_FULL);
32270
32271   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32272
32273 #if SQLITE_OS_WINCE
32274   rc = seekWinFile(pFile, offset);
32275   if( rc==0 ){
32276 #else
32277   {
32278 #endif
32279 #if !SQLITE_OS_WINCE
32280     OVERLAPPED overlapped;        /* The offset for WriteFile. */
32281 #endif
32282     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32283     int nRem = amt;               /* Number of bytes yet to be written */
32284     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32285     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
32286
32287 #if !SQLITE_OS_WINCE
32288     memset(&overlapped, 0, sizeof(OVERLAPPED));
32289     overlapped.Offset = (LONG)(offset & 0xffffffff);
32290     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32291 #endif
32292
32293     while( nRem>0 ){
32294 #if SQLITE_OS_WINCE
32295       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32296 #else
32297       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
32298 #endif
32299         if( retryIoerr(&nRetry, &lastErrno) ) continue;
32300         break;
32301       }
32302       assert( nWrite==0 || nWrite<=(DWORD)nRem );
32303       if( nWrite==0 || nWrite>(DWORD)nRem ){
32304         lastErrno = osGetLastError();
32305         break;
32306       }
32307 #if !SQLITE_OS_WINCE
32308       offset += nWrite;
32309       overlapped.Offset = (LONG)(offset & 0xffffffff);
32310       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32311 #endif
32312       aRem += nWrite;
32313       nRem -= nWrite;
32314     }
32315     if( nRem>0 ){
32316       pFile->lastErrno = lastErrno;
32317       rc = 1;
32318     }
32319   }
32320
32321   if( rc ){
32322     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32323        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32324       return SQLITE_FULL;
32325     }
32326     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
32327              "winWrite", pFile->zPath);
32328   }else{
32329     logIoerr(nRetry);
32330   }
32331   return SQLITE_OK;
32332 }
32333
32334 /*
32335 ** Truncate an open file to a specified size
32336 */
32337 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32338   winFile *pFile = (winFile*)id;  /* File handle object */
32339   int rc = SQLITE_OK;             /* Return code for this function */
32340
32341   assert( pFile );
32342
32343   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32344   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32345
32346   /* If the user has configured a chunk-size for this file, truncate the
32347   ** file so that it consists of an integer number of chunks (i.e. the
32348   ** actual file size after the operation may be larger than the requested
32349   ** size).
32350   */
32351   if( pFile->szChunk>0 ){
32352     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32353   }
32354
32355   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32356   if( seekWinFile(pFile, nByte) ){
32357     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32358              "winTruncate1", pFile->zPath);
32359   }else if( 0==osSetEndOfFile(pFile->h) ){
32360     pFile->lastErrno = osGetLastError();
32361     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32362              "winTruncate2", pFile->zPath);
32363   }
32364
32365   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32366   return rc;
32367 }
32368
32369 #ifdef SQLITE_TEST
32370 /*
32371 ** Count the number of fullsyncs and normal syncs.  This is used to test
32372 ** that syncs and fullsyncs are occuring at the right times.
32373 */
32374 SQLITE_API int sqlite3_sync_count = 0;
32375 SQLITE_API int sqlite3_fullsync_count = 0;
32376 #endif
32377
32378 /*
32379 ** Make sure all writes to a particular file are committed to disk.
32380 */
32381 static int winSync(sqlite3_file *id, int flags){
32382 #ifndef SQLITE_NO_SYNC
32383   /*
32384   ** Used only when SQLITE_NO_SYNC is not defined.
32385    */
32386   BOOL rc;
32387 #endif
32388 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32389     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32390   /*
32391   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32392   ** OSTRACE() macros.
32393    */
32394   winFile *pFile = (winFile*)id;
32395 #else
32396   UNUSED_PARAMETER(id);
32397 #endif
32398
32399   assert( pFile );
32400   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32401   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32402       || (flags&0x0F)==SQLITE_SYNC_FULL
32403   );
32404
32405   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32406
32407   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32408   ** line is to test that doing so does not cause any problems.
32409   */
32410   SimulateDiskfullError( return SQLITE_FULL );
32411
32412 #ifndef SQLITE_TEST
32413   UNUSED_PARAMETER(flags);
32414 #else
32415   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32416     sqlite3_fullsync_count++;
32417   }
32418   sqlite3_sync_count++;
32419 #endif
32420
32421   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32422   ** no-op
32423   */
32424 #ifdef SQLITE_NO_SYNC
32425   return SQLITE_OK;
32426 #else
32427   rc = osFlushFileBuffers(pFile->h);
32428   SimulateIOError( rc=FALSE );
32429   if( rc ){
32430     return SQLITE_OK;
32431   }else{
32432     pFile->lastErrno = osGetLastError();
32433     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
32434              "winSync", pFile->zPath);
32435   }
32436 #endif
32437 }
32438
32439 /*
32440 ** Determine the current size of a file in bytes
32441 */
32442 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32443   winFile *pFile = (winFile*)id;
32444   int rc = SQLITE_OK;
32445
32446   assert( id!=0 );
32447   SimulateIOError(return SQLITE_IOERR_FSTAT);
32448 #if SQLITE_OS_WINRT
32449   {
32450     FILE_STANDARD_INFO info;
32451     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
32452                                      &info, sizeof(info)) ){
32453       *pSize = info.EndOfFile.QuadPart;
32454     }else{
32455       pFile->lastErrno = osGetLastError();
32456       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32457                        "winFileSize", pFile->zPath);
32458     }
32459   }
32460 #else
32461   {
32462     DWORD upperBits;
32463     DWORD lowerBits;
32464     DWORD lastErrno;
32465
32466     lowerBits = osGetFileSize(pFile->h, &upperBits);
32467     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32468     if(   (lowerBits == INVALID_FILE_SIZE)
32469        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
32470       pFile->lastErrno = lastErrno;
32471       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32472              "winFileSize", pFile->zPath);
32473     }
32474   }
32475 #endif
32476   return rc;
32477 }
32478
32479 /*
32480 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32481 */
32482 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32483 # define LOCKFILE_FAIL_IMMEDIATELY 1
32484 #endif
32485
32486 #ifndef LOCKFILE_EXCLUSIVE_LOCK
32487 # define LOCKFILE_EXCLUSIVE_LOCK 2
32488 #endif
32489
32490 /*
32491 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
32492 ** When the LockFile function was used, it was always expected to fail
32493 ** immediately if the lock could not be obtained.  Also, it always expected to
32494 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
32495 ** and reflect those expectations; therefore, they should not be changed.
32496 */
32497 #ifndef SQLITE_LOCKFILE_FLAGS
32498 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
32499                                   LOCKFILE_EXCLUSIVE_LOCK)
32500 #endif
32501
32502 /*
32503 ** Currently, SQLite never calls the LockFileEx function without wanting the
32504 ** call to fail immediately if the lock cannot be obtained.
32505 */
32506 #ifndef SQLITE_LOCKFILEEX_FLAGS
32507 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
32508 #endif
32509
32510 /*
32511 ** Acquire a reader lock.
32512 ** Different API routines are called depending on whether or not this
32513 ** is Win9x or WinNT.
32514 */
32515 static int getReadLock(winFile *pFile){
32516   int res;
32517   if( isNT() ){
32518 #if SQLITE_OS_WINCE
32519     /*
32520     ** NOTE: Windows CE is handled differently here due its lack of the Win32
32521     **       API LockFileEx.
32522     */
32523     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
32524 #else
32525     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
32526                       SHARED_SIZE, 0);
32527 #endif
32528   }
32529 #ifdef SQLITE_WIN32_HAS_ANSI
32530   else{
32531     int lk;
32532     sqlite3_randomness(sizeof(lk), &lk);
32533     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32534     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32535                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32536   }
32537 #endif
32538   if( res == 0 ){
32539     pFile->lastErrno = osGetLastError();
32540     /* No need to log a failure to lock */
32541   }
32542   return res;
32543 }
32544
32545 /*
32546 ** Undo a readlock
32547 */
32548 static int unlockReadLock(winFile *pFile){
32549   int res;
32550   DWORD lastErrno;
32551   if( isNT() ){
32552     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32553   }
32554 #ifdef SQLITE_WIN32_HAS_ANSI
32555   else{
32556     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32557   }
32558 #endif
32559   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
32560     pFile->lastErrno = lastErrno;
32561     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
32562              "unlockReadLock", pFile->zPath);
32563   }
32564   return res;
32565 }
32566
32567 /*
32568 ** Lock the file with the lock specified by parameter locktype - one
32569 ** of the following:
32570 **
32571 **     (1) SHARED_LOCK
32572 **     (2) RESERVED_LOCK
32573 **     (3) PENDING_LOCK
32574 **     (4) EXCLUSIVE_LOCK
32575 **
32576 ** Sometimes when requesting one lock state, additional lock states
32577 ** are inserted in between.  The locking might fail on one of the later
32578 ** transitions leaving the lock state different from what it started but
32579 ** still short of its goal.  The following chart shows the allowed
32580 ** transitions and the inserted intermediate states:
32581 **
32582 **    UNLOCKED -> SHARED
32583 **    SHARED -> RESERVED
32584 **    SHARED -> (PENDING) -> EXCLUSIVE
32585 **    RESERVED -> (PENDING) -> EXCLUSIVE
32586 **    PENDING -> EXCLUSIVE
32587 **
32588 ** This routine will only increase a lock.  The winUnlock() routine
32589 ** erases all locks at once and returns us immediately to locking level 0.
32590 ** It is not possible to lower the locking level one step at a time.  You
32591 ** must go straight to locking level 0.
32592 */
32593 static int winLock(sqlite3_file *id, int locktype){
32594   int rc = SQLITE_OK;    /* Return code from subroutines */
32595   int res = 1;           /* Result of a Windows lock call */
32596   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32597   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32598   winFile *pFile = (winFile*)id;
32599   DWORD lastErrno = NO_ERROR;
32600
32601   assert( id!=0 );
32602   OSTRACE(("LOCK %d %d was %d(%d)\n",
32603            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32604
32605   /* If there is already a lock of this type or more restrictive on the
32606   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32607   ** sqlite3OsEnterMutex() hasn't been called yet.
32608   */
32609   if( pFile->locktype>=locktype ){
32610     return SQLITE_OK;
32611   }
32612
32613   /* Make sure the locking sequence is correct
32614   */
32615   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32616   assert( locktype!=PENDING_LOCK );
32617   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32618
32619   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32620   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32621   ** the PENDING_LOCK byte is temporary.
32622   */
32623   newLocktype = pFile->locktype;
32624   if(   (pFile->locktype==NO_LOCK)
32625      || (   (locktype==EXCLUSIVE_LOCK)
32626          && (pFile->locktype==RESERVED_LOCK))
32627   ){
32628     int cnt = 3;
32629     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32630                                          PENDING_BYTE, 0, 1, 0))==0 ){
32631       /* Try 3 times to get the pending lock.  This is needed to work
32632       ** around problems caused by indexing and/or anti-virus software on
32633       ** Windows systems.
32634       ** If you are using this code as a model for alternative VFSes, do not
32635       ** copy this retry logic.  It is a hack intended for Windows only.
32636       */
32637       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32638       if( cnt ) sqlite3_win32_sleep(1);
32639     }
32640     gotPendingLock = res;
32641     if( !res ){
32642       lastErrno = osGetLastError();
32643     }
32644   }
32645
32646   /* Acquire a shared lock
32647   */
32648   if( locktype==SHARED_LOCK && res ){
32649     assert( pFile->locktype==NO_LOCK );
32650     res = getReadLock(pFile);
32651     if( res ){
32652       newLocktype = SHARED_LOCK;
32653     }else{
32654       lastErrno = osGetLastError();
32655     }
32656   }
32657
32658   /* Acquire a RESERVED lock
32659   */
32660   if( locktype==RESERVED_LOCK && res ){
32661     assert( pFile->locktype==SHARED_LOCK );
32662     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32663     if( res ){
32664       newLocktype = RESERVED_LOCK;
32665     }else{
32666       lastErrno = osGetLastError();
32667     }
32668   }
32669
32670   /* Acquire a PENDING lock
32671   */
32672   if( locktype==EXCLUSIVE_LOCK && res ){
32673     newLocktype = PENDING_LOCK;
32674     gotPendingLock = 0;
32675   }
32676
32677   /* Acquire an EXCLUSIVE lock
32678   */
32679   if( locktype==EXCLUSIVE_LOCK && res ){
32680     assert( pFile->locktype>=SHARED_LOCK );
32681     res = unlockReadLock(pFile);
32682     OSTRACE(("unreadlock = %d\n", res));
32683     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
32684                       SHARED_SIZE, 0);
32685     if( res ){
32686       newLocktype = EXCLUSIVE_LOCK;
32687     }else{
32688       lastErrno = osGetLastError();
32689       OSTRACE(("error-code = %d\n", lastErrno));
32690       getReadLock(pFile);
32691     }
32692   }
32693
32694   /* If we are holding a PENDING lock that ought to be released, then
32695   ** release it now.
32696   */
32697   if( gotPendingLock && locktype==SHARED_LOCK ){
32698     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32699   }
32700
32701   /* Update the state of the lock has held in the file descriptor then
32702   ** return the appropriate result code.
32703   */
32704   if( res ){
32705     rc = SQLITE_OK;
32706   }else{
32707     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32708            locktype, newLocktype));
32709     pFile->lastErrno = lastErrno;
32710     rc = SQLITE_BUSY;
32711   }
32712   pFile->locktype = (u8)newLocktype;
32713   return rc;
32714 }
32715
32716 /*
32717 ** This routine checks if there is a RESERVED lock held on the specified
32718 ** file by this or any other process. If such a lock is held, return
32719 ** non-zero, otherwise zero.
32720 */
32721 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32722   int rc;
32723   winFile *pFile = (winFile*)id;
32724
32725   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32726
32727   assert( id!=0 );
32728   if( pFile->locktype>=RESERVED_LOCK ){
32729     rc = 1;
32730     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32731   }else{
32732     rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32733     if( rc ){
32734       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32735     }
32736     rc = !rc;
32737     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32738   }
32739   *pResOut = rc;
32740   return SQLITE_OK;
32741 }
32742
32743 /*
32744 ** Lower the locking level on file descriptor id to locktype.  locktype
32745 ** must be either NO_LOCK or SHARED_LOCK.
32746 **
32747 ** If the locking level of the file descriptor is already at or below
32748 ** the requested locking level, this routine is a no-op.
32749 **
32750 ** It is not possible for this routine to fail if the second argument
32751 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32752 ** might return SQLITE_IOERR;
32753 */
32754 static int winUnlock(sqlite3_file *id, int locktype){
32755   int type;
32756   winFile *pFile = (winFile*)id;
32757   int rc = SQLITE_OK;
32758   assert( pFile!=0 );
32759   assert( locktype<=SHARED_LOCK );
32760   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32761           pFile->locktype, pFile->sharedLockByte));
32762   type = pFile->locktype;
32763   if( type>=EXCLUSIVE_LOCK ){
32764     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32765     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32766       /* This should never happen.  We should always be able to
32767       ** reacquire the read lock */
32768       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
32769                "winUnlock", pFile->zPath);
32770     }
32771   }
32772   if( type>=RESERVED_LOCK ){
32773     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32774   }
32775   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32776     unlockReadLock(pFile);
32777   }
32778   if( type>=PENDING_LOCK ){
32779     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32780   }
32781   pFile->locktype = (u8)locktype;
32782   return rc;
32783 }
32784
32785 /*
32786 ** If *pArg is inititially negative then this is a query.  Set *pArg to
32787 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
32788 **
32789 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
32790 */
32791 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
32792   if( *pArg<0 ){
32793     *pArg = (pFile->ctrlFlags & mask)!=0;
32794   }else if( (*pArg)==0 ){
32795     pFile->ctrlFlags &= ~mask;
32796   }else{
32797     pFile->ctrlFlags |= mask;
32798   }
32799 }
32800
32801 /* Forward declaration */
32802 static int getTempname(int nBuf, char *zBuf);
32803
32804 /*
32805 ** Control and query of the open file handle.
32806 */
32807 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32808   winFile *pFile = (winFile*)id;
32809   switch( op ){
32810     case SQLITE_FCNTL_LOCKSTATE: {
32811       *(int*)pArg = pFile->locktype;
32812       return SQLITE_OK;
32813     }
32814     case SQLITE_LAST_ERRNO: {
32815       *(int*)pArg = (int)pFile->lastErrno;
32816       return SQLITE_OK;
32817     }
32818     case SQLITE_FCNTL_CHUNK_SIZE: {
32819       pFile->szChunk = *(int *)pArg;
32820       return SQLITE_OK;
32821     }
32822     case SQLITE_FCNTL_SIZE_HINT: {
32823       if( pFile->szChunk>0 ){
32824         sqlite3_int64 oldSz;
32825         int rc = winFileSize(id, &oldSz);
32826         if( rc==SQLITE_OK ){
32827           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
32828           if( newSz>oldSz ){
32829             SimulateIOErrorBenign(1);
32830             rc = winTruncate(id, newSz);
32831             SimulateIOErrorBenign(0);
32832           }
32833         }
32834         return rc;
32835       }
32836       return SQLITE_OK;
32837     }
32838     case SQLITE_FCNTL_PERSIST_WAL: {
32839       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
32840       return SQLITE_OK;
32841     }
32842     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
32843       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
32844       return SQLITE_OK;
32845     }
32846     case SQLITE_FCNTL_VFSNAME: {
32847       *(char**)pArg = sqlite3_mprintf("win32");
32848       return SQLITE_OK;
32849     }
32850     case SQLITE_FCNTL_WIN32_AV_RETRY: {
32851       int *a = (int*)pArg;
32852       if( a[0]>0 ){
32853         win32IoerrRetry = a[0];
32854       }else{
32855         a[0] = win32IoerrRetry;
32856       }
32857       if( a[1]>0 ){
32858         win32IoerrRetryDelay = a[1];
32859       }else{
32860         a[1] = win32IoerrRetryDelay;
32861       }
32862       return SQLITE_OK;
32863     }
32864     case SQLITE_FCNTL_TEMPFILENAME: {
32865       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
32866       if( zTFile ){
32867         getTempname(pFile->pVfs->mxPathname, zTFile);
32868         *(char**)pArg = zTFile;
32869       }
32870       return SQLITE_OK;
32871     }
32872   }
32873   return SQLITE_NOTFOUND;
32874 }
32875
32876 /*
32877 ** Return the sector size in bytes of the underlying block device for
32878 ** the specified file. This is almost always 512 bytes, but may be
32879 ** larger for some devices.
32880 **
32881 ** SQLite code assumes this function cannot fail. It also assumes that
32882 ** if two files are created in the same file-system directory (i.e.
32883 ** a database and its journal file) that the sector size will be the
32884 ** same for both.
32885 */
32886 static int winSectorSize(sqlite3_file *id){
32887   (void)id;
32888   return SQLITE_DEFAULT_SECTOR_SIZE;
32889 }
32890
32891 /*
32892 ** Return a vector of device characteristics.
32893 */
32894 static int winDeviceCharacteristics(sqlite3_file *id){
32895   winFile *p = (winFile*)id;
32896   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
32897          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
32898 }
32899
32900 #ifndef SQLITE_OMIT_WAL
32901
32902 /* 
32903 ** Windows will only let you create file view mappings
32904 ** on allocation size granularity boundaries.
32905 ** During sqlite3_os_init() we do a GetSystemInfo()
32906 ** to get the granularity size.
32907 */
32908 SYSTEM_INFO winSysInfo;
32909
32910 /*
32911 ** Helper functions to obtain and relinquish the global mutex. The
32912 ** global mutex is used to protect the winLockInfo objects used by 
32913 ** this file, all of which may be shared by multiple threads.
32914 **
32915 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32916 ** is held when required. This function is only used as part of assert() 
32917 ** statements. e.g.
32918 **
32919 **   winShmEnterMutex()
32920 **     assert( winShmMutexHeld() );
32921 **   winShmLeaveMutex()
32922 */
32923 static void winShmEnterMutex(void){
32924   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32925 }
32926 static void winShmLeaveMutex(void){
32927   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32928 }
32929 #ifdef SQLITE_DEBUG
32930 static int winShmMutexHeld(void) {
32931   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32932 }
32933 #endif
32934
32935 /*
32936 ** Object used to represent a single file opened and mmapped to provide
32937 ** shared memory.  When multiple threads all reference the same
32938 ** log-summary, each thread has its own winFile object, but they all
32939 ** point to a single instance of this object.  In other words, each
32940 ** log-summary is opened only once per process.
32941 **
32942 ** winShmMutexHeld() must be true when creating or destroying
32943 ** this object or while reading or writing the following fields:
32944 **
32945 **      nRef
32946 **      pNext 
32947 **
32948 ** The following fields are read-only after the object is created:
32949 ** 
32950 **      fid
32951 **      zFilename
32952 **
32953 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32954 ** winShmMutexHeld() is true when reading or writing any other field
32955 ** in this structure.
32956 **
32957 */
32958 struct winShmNode {
32959   sqlite3_mutex *mutex;      /* Mutex to access this object */
32960   char *zFilename;           /* Name of the file */
32961   winFile hFile;             /* File handle from winOpen */
32962
32963   int szRegion;              /* Size of shared-memory regions */
32964   int nRegion;               /* Size of array apRegion */
32965   struct ShmRegion {
32966     HANDLE hMap;             /* File handle from CreateFileMapping */
32967     void *pMap;
32968   } *aRegion;
32969   DWORD lastErrno;           /* The Windows errno from the last I/O error */
32970
32971   int nRef;                  /* Number of winShm objects pointing to this */
32972   winShm *pFirst;            /* All winShm objects pointing to this */
32973   winShmNode *pNext;         /* Next in list of all winShmNode objects */
32974 #ifdef SQLITE_DEBUG
32975   u8 nextShmId;              /* Next available winShm.id value */
32976 #endif
32977 };
32978
32979 /*
32980 ** A global array of all winShmNode objects.
32981 **
32982 ** The winShmMutexHeld() must be true while reading or writing this list.
32983 */
32984 static winShmNode *winShmNodeList = 0;
32985
32986 /*
32987 ** Structure used internally by this VFS to record the state of an
32988 ** open shared memory connection.
32989 **
32990 ** The following fields are initialized when this object is created and
32991 ** are read-only thereafter:
32992 **
32993 **    winShm.pShmNode
32994 **    winShm.id
32995 **
32996 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32997 ** while accessing any read/write fields.
32998 */
32999 struct winShm {
33000   winShmNode *pShmNode;      /* The underlying winShmNode object */
33001   winShm *pNext;             /* Next winShm with the same winShmNode */
33002   u8 hasMutex;               /* True if holding the winShmNode mutex */
33003   u16 sharedMask;            /* Mask of shared locks held */
33004   u16 exclMask;              /* Mask of exclusive locks held */
33005 #ifdef SQLITE_DEBUG
33006   u8 id;                     /* Id of this connection with its winShmNode */
33007 #endif
33008 };
33009
33010 /*
33011 ** Constants used for locking
33012 */
33013 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33014 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33015
33016 /*
33017 ** Apply advisory locks for all n bytes beginning at ofst.
33018 */
33019 #define _SHM_UNLCK  1
33020 #define _SHM_RDLCK  2
33021 #define _SHM_WRLCK  3
33022 static int winShmSystemLock(
33023   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33024   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33025   int ofst,             /* Offset to first byte to be locked/unlocked */
33026   int nByte             /* Number of bytes to lock or unlock */
33027 ){
33028   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33029
33030   /* Access to the winShmNode object is serialized by the caller */
33031   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33032
33033   /* Release/Acquire the system-level lock */
33034   if( lockType==_SHM_UNLCK ){
33035     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33036   }else{
33037     /* Initialize the locking parameters */
33038     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33039     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33040     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33041   }
33042   
33043   if( rc!= 0 ){
33044     rc = SQLITE_OK;
33045   }else{
33046     pFile->lastErrno =  osGetLastError();
33047     rc = SQLITE_BUSY;
33048   }
33049
33050   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
33051            pFile->hFile.h,
33052            rc==SQLITE_OK ? "ok" : "failed",
33053            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
33054            pFile->lastErrno));
33055
33056   return rc;
33057 }
33058
33059 /* Forward references to VFS methods */
33060 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33061 static int winDelete(sqlite3_vfs *,const char*,int);
33062
33063 /*
33064 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33065 **
33066 ** This is not a VFS shared-memory method; it is a utility function called
33067 ** by VFS shared-memory methods.
33068 */
33069 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33070   winShmNode **pp;
33071   winShmNode *p;
33072   BOOL bRc;
33073   assert( winShmMutexHeld() );
33074   pp = &winShmNodeList;
33075   while( (p = *pp)!=0 ){
33076     if( p->nRef==0 ){
33077       int i;
33078       if( p->mutex ) sqlite3_mutex_free(p->mutex);
33079       for(i=0; i<p->nRegion; i++){
33080         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33081         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
33082                  (int)osGetCurrentProcessId(), i,
33083                  bRc ? "ok" : "failed"));
33084         bRc = osCloseHandle(p->aRegion[i].hMap);
33085         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
33086                  (int)osGetCurrentProcessId(), i,
33087                  bRc ? "ok" : "failed"));
33088       }
33089       if( p->hFile.h != INVALID_HANDLE_VALUE ){
33090         SimulateIOErrorBenign(1);
33091         winClose((sqlite3_file *)&p->hFile);
33092         SimulateIOErrorBenign(0);
33093       }
33094       if( deleteFlag ){
33095         SimulateIOErrorBenign(1);
33096         sqlite3BeginBenignMalloc();
33097         winDelete(pVfs, p->zFilename, 0);
33098         sqlite3EndBenignMalloc();
33099         SimulateIOErrorBenign(0);
33100       }
33101       *pp = p->pNext;
33102       sqlite3_free(p->aRegion);
33103       sqlite3_free(p);
33104     }else{
33105       pp = &p->pNext;
33106     }
33107   }
33108 }
33109
33110 /*
33111 ** Open the shared-memory area associated with database file pDbFd.
33112 **
33113 ** When opening a new shared-memory file, if no other instances of that
33114 ** file are currently open, in this process or in other processes, then
33115 ** the file must be truncated to zero length or have its header cleared.
33116 */
33117 static int winOpenSharedMemory(winFile *pDbFd){
33118   struct winShm *p;                  /* The connection to be opened */
33119   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33120   int rc;                            /* Result code */
33121   struct winShmNode *pNew;           /* Newly allocated winShmNode */
33122   int nName;                         /* Size of zName in bytes */
33123
33124   assert( pDbFd->pShm==0 );    /* Not previously opened */
33125
33126   /* Allocate space for the new sqlite3_shm object.  Also speculatively
33127   ** allocate space for a new winShmNode and filename.
33128   */
33129   p = sqlite3MallocZero( sizeof(*p) );
33130   if( p==0 ) return SQLITE_IOERR_NOMEM;
33131   nName = sqlite3Strlen30(pDbFd->zPath);
33132   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33133   if( pNew==0 ){
33134     sqlite3_free(p);
33135     return SQLITE_IOERR_NOMEM;
33136   }
33137   pNew->zFilename = (char*)&pNew[1];
33138   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33139   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
33140
33141   /* Look to see if there is an existing winShmNode that can be used.
33142   ** If no matching winShmNode currently exists, create a new one.
33143   */
33144   winShmEnterMutex();
33145   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33146     /* TBD need to come up with better match here.  Perhaps
33147     ** use FILE_ID_BOTH_DIR_INFO Structure.
33148     */
33149     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33150   }
33151   if( pShmNode ){
33152     sqlite3_free(pNew);
33153   }else{
33154     pShmNode = pNew;
33155     pNew = 0;
33156     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33157     pShmNode->pNext = winShmNodeList;
33158     winShmNodeList = pShmNode;
33159
33160     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33161     if( pShmNode->mutex==0 ){
33162       rc = SQLITE_IOERR_NOMEM;
33163       goto shm_open_err;
33164     }
33165
33166     rc = winOpen(pDbFd->pVfs,
33167                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33168                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33169                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
33170                  0);
33171     if( SQLITE_OK!=rc ){
33172       goto shm_open_err;
33173     }
33174
33175     /* Check to see if another process is holding the dead-man switch.
33176     ** If not, truncate the file to zero length. 
33177     */
33178     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33179       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33180       if( rc!=SQLITE_OK ){
33181         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33182                  "winOpenShm", pDbFd->zPath);
33183       }
33184     }
33185     if( rc==SQLITE_OK ){
33186       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33187       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33188     }
33189     if( rc ) goto shm_open_err;
33190   }
33191
33192   /* Make the new connection a child of the winShmNode */
33193   p->pShmNode = pShmNode;
33194 #ifdef SQLITE_DEBUG
33195   p->id = pShmNode->nextShmId++;
33196 #endif
33197   pShmNode->nRef++;
33198   pDbFd->pShm = p;
33199   winShmLeaveMutex();
33200
33201   /* The reference count on pShmNode has already been incremented under
33202   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33203   ** new (struct winShm) object to the pShmNode has been set. All that is
33204   ** left to do is to link the new object into the linked list starting
33205   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
33206   ** mutex.
33207   */
33208   sqlite3_mutex_enter(pShmNode->mutex);
33209   p->pNext = pShmNode->pFirst;
33210   pShmNode->pFirst = p;
33211   sqlite3_mutex_leave(pShmNode->mutex);
33212   return SQLITE_OK;
33213
33214   /* Jump here on any error */
33215 shm_open_err:
33216   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33217   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33218   sqlite3_free(p);
33219   sqlite3_free(pNew);
33220   winShmLeaveMutex();
33221   return rc;
33222 }
33223
33224 /*
33225 ** Close a connection to shared-memory.  Delete the underlying 
33226 ** storage if deleteFlag is true.
33227 */
33228 static int winShmUnmap(
33229   sqlite3_file *fd,          /* Database holding shared memory */
33230   int deleteFlag             /* Delete after closing if true */
33231 ){
33232   winFile *pDbFd;       /* Database holding shared-memory */
33233   winShm *p;            /* The connection to be closed */
33234   winShmNode *pShmNode; /* The underlying shared-memory file */
33235   winShm **pp;          /* For looping over sibling connections */
33236
33237   pDbFd = (winFile*)fd;
33238   p = pDbFd->pShm;
33239   if( p==0 ) return SQLITE_OK;
33240   pShmNode = p->pShmNode;
33241
33242   /* Remove connection p from the set of connections associated
33243   ** with pShmNode */
33244   sqlite3_mutex_enter(pShmNode->mutex);
33245   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33246   *pp = p->pNext;
33247
33248   /* Free the connection p */
33249   sqlite3_free(p);
33250   pDbFd->pShm = 0;
33251   sqlite3_mutex_leave(pShmNode->mutex);
33252
33253   /* If pShmNode->nRef has reached 0, then close the underlying
33254   ** shared-memory file, too */
33255   winShmEnterMutex();
33256   assert( pShmNode->nRef>0 );
33257   pShmNode->nRef--;
33258   if( pShmNode->nRef==0 ){
33259     winShmPurge(pDbFd->pVfs, deleteFlag);
33260   }
33261   winShmLeaveMutex();
33262
33263   return SQLITE_OK;
33264 }
33265
33266 /*
33267 ** Change the lock state for a shared-memory segment.
33268 */
33269 static int winShmLock(
33270   sqlite3_file *fd,          /* Database file holding the shared memory */
33271   int ofst,                  /* First lock to acquire or release */
33272   int n,                     /* Number of locks to acquire or release */
33273   int flags                  /* What to do with the lock */
33274 ){
33275   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
33276   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
33277   winShm *pX;                           /* For looping over all siblings */
33278   winShmNode *pShmNode = p->pShmNode;
33279   int rc = SQLITE_OK;                   /* Result code */
33280   u16 mask;                             /* Mask of locks to take or release */
33281
33282   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33283   assert( n>=1 );
33284   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33285        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33286        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33287        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33288   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33289
33290   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33291   assert( n>1 || mask==(1<<ofst) );
33292   sqlite3_mutex_enter(pShmNode->mutex);
33293   if( flags & SQLITE_SHM_UNLOCK ){
33294     u16 allMask = 0; /* Mask of locks held by siblings */
33295
33296     /* See if any siblings hold this same lock */
33297     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33298       if( pX==p ) continue;
33299       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33300       allMask |= pX->sharedMask;
33301     }
33302
33303     /* Unlock the system-level locks */
33304     if( (mask & allMask)==0 ){
33305       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33306     }else{
33307       rc = SQLITE_OK;
33308     }
33309
33310     /* Undo the local locks */
33311     if( rc==SQLITE_OK ){
33312       p->exclMask &= ~mask;
33313       p->sharedMask &= ~mask;
33314     } 
33315   }else if( flags & SQLITE_SHM_SHARED ){
33316     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33317
33318     /* Find out which shared locks are already held by sibling connections.
33319     ** If any sibling already holds an exclusive lock, go ahead and return
33320     ** SQLITE_BUSY.
33321     */
33322     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33323       if( (pX->exclMask & mask)!=0 ){
33324         rc = SQLITE_BUSY;
33325         break;
33326       }
33327       allShared |= pX->sharedMask;
33328     }
33329
33330     /* Get shared locks at the system level, if necessary */
33331     if( rc==SQLITE_OK ){
33332       if( (allShared & mask)==0 ){
33333         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33334       }else{
33335         rc = SQLITE_OK;
33336       }
33337     }
33338
33339     /* Get the local shared locks */
33340     if( rc==SQLITE_OK ){
33341       p->sharedMask |= mask;
33342     }
33343   }else{
33344     /* Make sure no sibling connections hold locks that will block this
33345     ** lock.  If any do, return SQLITE_BUSY right away.
33346     */
33347     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33348       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33349         rc = SQLITE_BUSY;
33350         break;
33351       }
33352     }
33353   
33354     /* Get the exclusive locks at the system level.  Then if successful
33355     ** also mark the local connection as being locked.
33356     */
33357     if( rc==SQLITE_OK ){
33358       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33359       if( rc==SQLITE_OK ){
33360         assert( (p->sharedMask & mask)==0 );
33361         p->exclMask |= mask;
33362       }
33363     }
33364   }
33365   sqlite3_mutex_leave(pShmNode->mutex);
33366   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33367            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
33368            rc ? "failed" : "ok"));
33369   return rc;
33370 }
33371
33372 /*
33373 ** Implement a memory barrier or memory fence on shared memory.  
33374 **
33375 ** All loads and stores begun before the barrier must complete before
33376 ** any load or store begun after the barrier.
33377 */
33378 static void winShmBarrier(
33379   sqlite3_file *fd          /* Database holding the shared memory */
33380 ){
33381   UNUSED_PARAMETER(fd);
33382   /* MemoryBarrier(); // does not work -- do not know why not */
33383   winShmEnterMutex();
33384   winShmLeaveMutex();
33385 }
33386
33387 /*
33388 ** This function is called to obtain a pointer to region iRegion of the 
33389 ** shared-memory associated with the database file fd. Shared-memory regions 
33390 ** are numbered starting from zero. Each shared-memory region is szRegion 
33391 ** bytes in size.
33392 **
33393 ** If an error occurs, an error code is returned and *pp is set to NULL.
33394 **
33395 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33396 ** region has not been allocated (by any client, including one running in a
33397 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
33398 ** isWrite is non-zero and the requested shared-memory region has not yet 
33399 ** been allocated, it is allocated by this function.
33400 **
33401 ** If the shared-memory region has already been allocated or is allocated by
33402 ** this call as described above, then it is mapped into this processes 
33403 ** address space (if it is not already), *pp is set to point to the mapped 
33404 ** memory and SQLITE_OK returned.
33405 */
33406 static int winShmMap(
33407   sqlite3_file *fd,               /* Handle open on database file */
33408   int iRegion,                    /* Region to retrieve */
33409   int szRegion,                   /* Size of regions */
33410   int isWrite,                    /* True to extend file if necessary */
33411   void volatile **pp              /* OUT: Mapped memory */
33412 ){
33413   winFile *pDbFd = (winFile*)fd;
33414   winShm *p = pDbFd->pShm;
33415   winShmNode *pShmNode;
33416   int rc = SQLITE_OK;
33417
33418   if( !p ){
33419     rc = winOpenSharedMemory(pDbFd);
33420     if( rc!=SQLITE_OK ) return rc;
33421     p = pDbFd->pShm;
33422   }
33423   pShmNode = p->pShmNode;
33424
33425   sqlite3_mutex_enter(pShmNode->mutex);
33426   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33427
33428   if( pShmNode->nRegion<=iRegion ){
33429     struct ShmRegion *apNew;           /* New aRegion[] array */
33430     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33431     sqlite3_int64 sz;                  /* Current size of wal-index file */
33432
33433     pShmNode->szRegion = szRegion;
33434
33435     /* The requested region is not mapped into this processes address space.
33436     ** Check to see if it has been allocated (i.e. if the wal-index file is
33437     ** large enough to contain the requested region).
33438     */
33439     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33440     if( rc!=SQLITE_OK ){
33441       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33442                "winShmMap1", pDbFd->zPath);
33443       goto shmpage_out;
33444     }
33445
33446     if( sz<nByte ){
33447       /* The requested memory region does not exist. If isWrite is set to
33448       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33449       **
33450       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33451       ** the requested memory region.
33452       */
33453       if( !isWrite ) goto shmpage_out;
33454       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33455       if( rc!=SQLITE_OK ){
33456         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33457                  "winShmMap2", pDbFd->zPath);
33458         goto shmpage_out;
33459       }
33460     }
33461
33462     /* Map the requested memory region into this processes address space. */
33463     apNew = (struct ShmRegion *)sqlite3_realloc(
33464         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33465     );
33466     if( !apNew ){
33467       rc = SQLITE_IOERR_NOMEM;
33468       goto shmpage_out;
33469     }
33470     pShmNode->aRegion = apNew;
33471
33472     while( pShmNode->nRegion<=iRegion ){
33473       HANDLE hMap = NULL;         /* file-mapping handle */
33474       void *pMap = 0;             /* Mapped memory region */
33475      
33476 #if SQLITE_OS_WINRT
33477       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
33478           NULL, PAGE_READWRITE, nByte, NULL
33479       );
33480 #elif defined(SQLITE_WIN32_HAS_WIDE)
33481       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
33482           NULL, PAGE_READWRITE, 0, nByte, NULL
33483       );
33484 #elif defined(SQLITE_WIN32_HAS_ANSI)
33485       hMap = osCreateFileMappingA(pShmNode->hFile.h, 
33486           NULL, PAGE_READWRITE, 0, nByte, NULL
33487       );
33488 #endif
33489       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33490                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
33491                hMap ? "ok" : "failed"));
33492       if( hMap ){
33493         int iOffset = pShmNode->nRegion*szRegion;
33494         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33495 #if SQLITE_OS_WINRT
33496         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33497             iOffset - iOffsetShift, szRegion + iOffsetShift
33498         );
33499 #else
33500         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33501             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33502         );
33503 #endif
33504         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33505                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
33506                  szRegion, pMap ? "ok" : "failed"));
33507       }
33508       if( !pMap ){
33509         pShmNode->lastErrno = osGetLastError();
33510         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
33511                  "winShmMap3", pDbFd->zPath);
33512         if( hMap ) osCloseHandle(hMap);
33513         goto shmpage_out;
33514       }
33515
33516       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33517       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33518       pShmNode->nRegion++;
33519     }
33520   }
33521
33522 shmpage_out:
33523   if( pShmNode->nRegion>iRegion ){
33524     int iOffset = iRegion*szRegion;
33525     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33526     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33527     *pp = (void *)&p[iOffsetShift];
33528   }else{
33529     *pp = 0;
33530   }
33531   sqlite3_mutex_leave(pShmNode->mutex);
33532   return rc;
33533 }
33534
33535 #else
33536 # define winShmMap     0
33537 # define winShmLock    0
33538 # define winShmBarrier 0
33539 # define winShmUnmap   0
33540 #endif /* #ifndef SQLITE_OMIT_WAL */
33541
33542 /*
33543 ** Here ends the implementation of all sqlite3_file methods.
33544 **
33545 ********************** End sqlite3_file Methods *******************************
33546 ******************************************************************************/
33547
33548 /*
33549 ** This vector defines all the methods that can operate on an
33550 ** sqlite3_file for win32.
33551 */
33552 static const sqlite3_io_methods winIoMethod = {
33553   2,                              /* iVersion */
33554   winClose,                       /* xClose */
33555   winRead,                        /* xRead */
33556   winWrite,                       /* xWrite */
33557   winTruncate,                    /* xTruncate */
33558   winSync,                        /* xSync */
33559   winFileSize,                    /* xFileSize */
33560   winLock,                        /* xLock */
33561   winUnlock,                      /* xUnlock */
33562   winCheckReservedLock,           /* xCheckReservedLock */
33563   winFileControl,                 /* xFileControl */
33564   winSectorSize,                  /* xSectorSize */
33565   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33566   winShmMap,                      /* xShmMap */
33567   winShmLock,                     /* xShmLock */
33568   winShmBarrier,                  /* xShmBarrier */
33569   winShmUnmap                     /* xShmUnmap */
33570 };
33571
33572 /****************************************************************************
33573 **************************** sqlite3_vfs methods ****************************
33574 **
33575 ** This division contains the implementation of methods on the
33576 ** sqlite3_vfs object.
33577 */
33578
33579 /*
33580 ** Convert a UTF-8 filename into whatever form the underlying
33581 ** operating system wants filenames in.  Space to hold the result
33582 ** is obtained from malloc and must be freed by the calling
33583 ** function.
33584 */
33585 static void *convertUtf8Filename(const char *zFilename){
33586   void *zConverted = 0;
33587   if( isNT() ){
33588     zConverted = utf8ToUnicode(zFilename);
33589   }
33590 #ifdef SQLITE_WIN32_HAS_ANSI
33591   else{
33592     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33593   }
33594 #endif
33595   /* caller will handle out of memory */
33596   return zConverted;
33597 }
33598
33599 /*
33600 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33601 ** hold at pVfs->mxPathname characters.
33602 */
33603 static int getTempname(int nBuf, char *zBuf){
33604   static char zChars[] =
33605     "abcdefghijklmnopqrstuvwxyz"
33606     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33607     "0123456789";
33608   size_t i, j;
33609   int nTempPath;
33610   char zTempPath[MAX_PATH+2];
33611
33612   /* It's odd to simulate an io-error here, but really this is just
33613   ** using the io-error infrastructure to test that SQLite handles this
33614   ** function failing. 
33615   */
33616   SimulateIOError( return SQLITE_IOERR );
33617
33618   memset(zTempPath, 0, MAX_PATH+2);
33619
33620   if( sqlite3_temp_directory ){
33621     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33622   }
33623 #if !SQLITE_OS_WINRT
33624   else if( isNT() ){
33625     char *zMulti;
33626     WCHAR zWidePath[MAX_PATH];
33627     osGetTempPathW(MAX_PATH-30, zWidePath);
33628     zMulti = unicodeToUtf8(zWidePath);
33629     if( zMulti ){
33630       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33631       sqlite3_free(zMulti);
33632     }else{
33633       return SQLITE_IOERR_NOMEM;
33634     }
33635   }
33636 #ifdef SQLITE_WIN32_HAS_ANSI
33637   else{
33638     char *zUtf8;
33639     char zMbcsPath[MAX_PATH];
33640     osGetTempPathA(MAX_PATH-30, zMbcsPath);
33641     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33642     if( zUtf8 ){
33643       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33644       sqlite3_free(zUtf8);
33645     }else{
33646       return SQLITE_IOERR_NOMEM;
33647     }
33648   }
33649 #endif
33650 #endif
33651
33652   /* Check that the output buffer is large enough for the temporary file 
33653   ** name. If it is not, return SQLITE_ERROR.
33654   */
33655   nTempPath = sqlite3Strlen30(zTempPath);
33656
33657   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
33658     return SQLITE_ERROR;
33659   }
33660
33661   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
33662   zTempPath[i] = 0;
33663
33664   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
33665                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
33666                    zTempPath);
33667   j = sqlite3Strlen30(zBuf);
33668   sqlite3_randomness(15, &zBuf[j]);
33669   for(i=0; i<15; i++, j++){
33670     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33671   }
33672   zBuf[j] = 0;
33673   zBuf[j+1] = 0;
33674
33675   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33676   return SQLITE_OK; 
33677 }
33678
33679 /*
33680 ** Return TRUE if the named file is really a directory.  Return false if
33681 ** it is something other than a directory, or if there is any kind of memory
33682 ** allocation failure.
33683 */
33684 static int winIsDir(const void *zConverted){
33685   DWORD attr;
33686   int rc = 0;
33687   DWORD lastErrno;
33688
33689   if( isNT() ){
33690     int cnt = 0;
33691     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33692     memset(&sAttrData, 0, sizeof(sAttrData));
33693     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
33694                              GetFileExInfoStandard,
33695                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
33696     if( !rc ){
33697       return 0; /* Invalid name? */
33698     }
33699     attr = sAttrData.dwFileAttributes;
33700 #if SQLITE_OS_WINCE==0
33701   }else{
33702     attr = osGetFileAttributesA((char*)zConverted);
33703 #endif
33704   }
33705   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
33706 }
33707
33708 /*
33709 ** Open a file.
33710 */
33711 static int winOpen(
33712   sqlite3_vfs *pVfs,        /* Not used */
33713   const char *zName,        /* Name of the file (UTF-8) */
33714   sqlite3_file *id,         /* Write the SQLite file handle here */
33715   int flags,                /* Open mode flags */
33716   int *pOutFlags            /* Status return flags */
33717 ){
33718   HANDLE h;
33719   DWORD lastErrno;
33720   DWORD dwDesiredAccess;
33721   DWORD dwShareMode;
33722   DWORD dwCreationDisposition;
33723   DWORD dwFlagsAndAttributes = 0;
33724 #if SQLITE_OS_WINCE
33725   int isTemp = 0;
33726 #endif
33727   winFile *pFile = (winFile*)id;
33728   void *zConverted;              /* Filename in OS encoding */
33729   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33730   int cnt = 0;
33731
33732   /* If argument zPath is a NULL pointer, this function is required to open
33733   ** a temporary file. Use this buffer to store the file name in.
33734   */
33735   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
33736
33737   int rc = SQLITE_OK;            /* Function Return Code */
33738 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33739   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33740 #endif
33741
33742   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33743   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33744   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33745 #ifndef NDEBUG
33746   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33747 #endif
33748   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33749
33750 #ifndef NDEBUG
33751   int isOpenJournal = (isCreate && (
33752         eType==SQLITE_OPEN_MASTER_JOURNAL 
33753      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33754      || eType==SQLITE_OPEN_WAL
33755   ));
33756 #endif
33757
33758   /* Check the following statements are true: 
33759   **
33760   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33761   **   (b) if CREATE is set, then READWRITE must also be set, and
33762   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33763   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33764   */
33765   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33766   assert(isCreate==0 || isReadWrite);
33767   assert(isExclusive==0 || isCreate);
33768   assert(isDelete==0 || isCreate);
33769
33770   /* The main DB, main journal, WAL file and master journal are never 
33771   ** automatically deleted. Nor are they ever temporary files.  */
33772   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33773   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33774   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33775   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33776
33777   /* Assert that the upper layer has set one of the "file-type" flags. */
33778   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33779        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33780        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33781        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33782   );
33783
33784   assert( id!=0 );
33785   UNUSED_PARAMETER(pVfs);
33786
33787 #if SQLITE_OS_WINRT
33788   if( !sqlite3_temp_directory ){
33789     sqlite3_log(SQLITE_ERROR,
33790         "sqlite3_temp_directory variable should be set for WinRT");
33791   }
33792 #endif
33793
33794   pFile->h = INVALID_HANDLE_VALUE;
33795
33796   /* If the second argument to this function is NULL, generate a 
33797   ** temporary file name to use 
33798   */
33799   if( !zUtf8Name ){
33800     assert(isDelete && !isOpenJournal);
33801     rc = getTempname(MAX_PATH+2, zTmpname);
33802     if( rc!=SQLITE_OK ){
33803       return rc;
33804     }
33805     zUtf8Name = zTmpname;
33806   }
33807
33808   /* Database filenames are double-zero terminated if they are not
33809   ** URIs with parameters.  Hence, they can always be passed into
33810   ** sqlite3_uri_parameter().
33811   */
33812   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
33813         zUtf8Name[strlen(zUtf8Name)+1]==0 );
33814
33815   /* Convert the filename to the system encoding. */
33816   zConverted = convertUtf8Filename(zUtf8Name);
33817   if( zConverted==0 ){
33818     return SQLITE_IOERR_NOMEM;
33819   }
33820
33821   if( winIsDir(zConverted) ){
33822     sqlite3_free(zConverted);
33823     return SQLITE_CANTOPEN_ISDIR;
33824   }
33825
33826   if( isReadWrite ){
33827     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33828   }else{
33829     dwDesiredAccess = GENERIC_READ;
33830   }
33831
33832   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33833   ** created. SQLite doesn't use it to indicate "exclusive access" 
33834   ** as it is usually understood.
33835   */
33836   if( isExclusive ){
33837     /* Creates a new file, only if it does not already exist. */
33838     /* If the file exists, it fails. */
33839     dwCreationDisposition = CREATE_NEW;
33840   }else if( isCreate ){
33841     /* Open existing file, or create if it doesn't exist */
33842     dwCreationDisposition = OPEN_ALWAYS;
33843   }else{
33844     /* Opens a file, only if it exists. */
33845     dwCreationDisposition = OPEN_EXISTING;
33846   }
33847
33848   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33849
33850   if( isDelete ){
33851 #if SQLITE_OS_WINCE
33852     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33853     isTemp = 1;
33854 #else
33855     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33856                                | FILE_ATTRIBUTE_HIDDEN
33857                                | FILE_FLAG_DELETE_ON_CLOSE;
33858 #endif
33859   }else{
33860     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33861   }
33862   /* Reports from the internet are that performance is always
33863   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33864 #if SQLITE_OS_WINCE
33865   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33866 #endif
33867
33868   if( isNT() ){
33869 #if SQLITE_OS_WINRT
33870     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
33871     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
33872     extendedParameters.dwFileAttributes =
33873             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
33874     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
33875     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
33876     extendedParameters.lpSecurityAttributes = NULL;
33877     extendedParameters.hTemplateFile = NULL;
33878     while( (h = osCreateFile2((LPCWSTR)zConverted,
33879                               dwDesiredAccess,
33880                               dwShareMode,
33881                               dwCreationDisposition,
33882                               &extendedParameters))==INVALID_HANDLE_VALUE &&
33883                               retryIoerr(&cnt, &lastErrno) ){
33884                /* Noop */
33885     }
33886 #else
33887     while( (h = osCreateFileW((LPCWSTR)zConverted,
33888                               dwDesiredAccess,
33889                               dwShareMode, NULL,
33890                               dwCreationDisposition,
33891                               dwFlagsAndAttributes,
33892                               NULL))==INVALID_HANDLE_VALUE &&
33893                               retryIoerr(&cnt, &lastErrno) ){
33894                /* Noop */
33895     }
33896 #endif
33897   }
33898 #ifdef SQLITE_WIN32_HAS_ANSI
33899   else{
33900     while( (h = osCreateFileA((LPCSTR)zConverted,
33901                               dwDesiredAccess,
33902                               dwShareMode, NULL,
33903                               dwCreationDisposition,
33904                               dwFlagsAndAttributes,
33905                               NULL))==INVALID_HANDLE_VALUE &&
33906                               retryIoerr(&cnt, &lastErrno) ){
33907                /* Noop */
33908     }
33909   }
33910 #endif
33911   logIoerr(cnt);
33912
33913   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33914            h, zName, dwDesiredAccess, 
33915            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33916
33917   if( h==INVALID_HANDLE_VALUE ){
33918     pFile->lastErrno = lastErrno;
33919     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
33920     sqlite3_free(zConverted);
33921     if( isReadWrite && !isExclusive ){
33922       return winOpen(pVfs, zName, id, 
33923              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33924     }else{
33925       return SQLITE_CANTOPEN_BKPT;
33926     }
33927   }
33928
33929   if( pOutFlags ){
33930     if( isReadWrite ){
33931       *pOutFlags = SQLITE_OPEN_READWRITE;
33932     }else{
33933       *pOutFlags = SQLITE_OPEN_READONLY;
33934     }
33935   }
33936
33937   memset(pFile, 0, sizeof(*pFile));
33938   pFile->pMethod = &winIoMethod;
33939   pFile->h = h;
33940   pFile->lastErrno = NO_ERROR;
33941   pFile->pVfs = pVfs;
33942 #ifndef SQLITE_OMIT_WAL
33943   pFile->pShm = 0;
33944 #endif
33945   pFile->zPath = zName;
33946   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
33947     pFile->ctrlFlags |= WINFILE_PSOW;
33948   }
33949
33950 #if SQLITE_OS_WINCE
33951   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33952        && !winceCreateLock(zName, pFile)
33953   ){
33954     osCloseHandle(h);
33955     sqlite3_free(zConverted);
33956     return SQLITE_CANTOPEN_BKPT;
33957   }
33958   if( isTemp ){
33959     pFile->zDeleteOnClose = zConverted;
33960   }else
33961 #endif
33962   {
33963     sqlite3_free(zConverted);
33964   }
33965
33966   OpenCounter(+1);
33967   return rc;
33968 }
33969
33970 /*
33971 ** Delete the named file.
33972 **
33973 ** Note that Windows does not allow a file to be deleted if some other
33974 ** process has it open.  Sometimes a virus scanner or indexing program
33975 ** will open a journal file shortly after it is created in order to do
33976 ** whatever it does.  While this other process is holding the
33977 ** file open, we will be unable to delete it.  To work around this
33978 ** problem, we delay 100 milliseconds and try to delete again.  Up
33979 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33980 ** up and returning an error.
33981 */
33982 static int winDelete(
33983   sqlite3_vfs *pVfs,          /* Not used on win32 */
33984   const char *zFilename,      /* Name of file to delete */
33985   int syncDir                 /* Not used on win32 */
33986 ){
33987   int cnt = 0;
33988   int rc;
33989   DWORD attr;
33990   DWORD lastErrno;
33991   void *zConverted;
33992   UNUSED_PARAMETER(pVfs);
33993   UNUSED_PARAMETER(syncDir);
33994
33995   SimulateIOError(return SQLITE_IOERR_DELETE);
33996   zConverted = convertUtf8Filename(zFilename);
33997   if( zConverted==0 ){
33998     return SQLITE_IOERR_NOMEM;
33999   }
34000   if( isNT() ){
34001     do {
34002 #if SQLITE_OS_WINRT
34003       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34004       memset(&sAttrData, 0, sizeof(sAttrData));
34005       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
34006                                   &sAttrData) ){
34007         attr = sAttrData.dwFileAttributes;
34008       }else{
34009         lastErrno = osGetLastError();
34010         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
34011           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34012         }else{
34013           rc = SQLITE_ERROR;
34014         }
34015         break;
34016       }
34017 #else
34018       attr = osGetFileAttributesW(zConverted);
34019 #endif
34020       if ( attr==INVALID_FILE_ATTRIBUTES ){
34021         lastErrno = osGetLastError();
34022         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
34023           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34024         }else{
34025           rc = SQLITE_ERROR;
34026         }
34027         break;
34028       }
34029       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34030         rc = SQLITE_ERROR; /* Files only. */
34031         break;
34032       }
34033       if ( osDeleteFileW(zConverted) ){
34034         rc = SQLITE_OK; /* Deleted OK. */
34035         break;
34036       }
34037       if ( !retryIoerr(&cnt, &lastErrno) ){
34038         rc = SQLITE_ERROR; /* No more retries. */
34039         break;
34040       }
34041     } while(1);
34042   }
34043 #ifdef SQLITE_WIN32_HAS_ANSI
34044   else{
34045     do {
34046       attr = osGetFileAttributesA(zConverted);
34047       if ( attr==INVALID_FILE_ATTRIBUTES ){
34048         lastErrno = osGetLastError();
34049         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
34050           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34051         }else{
34052           rc = SQLITE_ERROR;
34053         }
34054         break;
34055       }
34056       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34057         rc = SQLITE_ERROR; /* Files only. */
34058         break;
34059       }
34060       if ( osDeleteFileA(zConverted) ){
34061         rc = SQLITE_OK; /* Deleted OK. */
34062         break;
34063       }
34064       if ( !retryIoerr(&cnt, &lastErrno) ){
34065         rc = SQLITE_ERROR; /* No more retries. */
34066         break;
34067       }
34068     } while(1);
34069   }
34070 #endif
34071   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
34072     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
34073              "winDelete", zFilename);
34074   }else{
34075     logIoerr(cnt);
34076   }
34077   sqlite3_free(zConverted);
34078   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
34079   return rc;
34080 }
34081
34082 /*
34083 ** Check the existance and status of a file.
34084 */
34085 static int winAccess(
34086   sqlite3_vfs *pVfs,         /* Not used on win32 */
34087   const char *zFilename,     /* Name of file to check */
34088   int flags,                 /* Type of test to make on this file */
34089   int *pResOut               /* OUT: Result */
34090 ){
34091   DWORD attr;
34092   int rc = 0;
34093   DWORD lastErrno;
34094   void *zConverted;
34095   UNUSED_PARAMETER(pVfs);
34096
34097   SimulateIOError( return SQLITE_IOERR_ACCESS; );
34098   zConverted = convertUtf8Filename(zFilename);
34099   if( zConverted==0 ){
34100     return SQLITE_IOERR_NOMEM;
34101   }
34102   if( isNT() ){
34103     int cnt = 0;
34104     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34105     memset(&sAttrData, 0, sizeof(sAttrData));
34106     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34107                              GetFileExInfoStandard, 
34108                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34109     if( rc ){
34110       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
34111       ** as if it does not exist.
34112       */
34113       if(    flags==SQLITE_ACCESS_EXISTS
34114           && sAttrData.nFileSizeHigh==0 
34115           && sAttrData.nFileSizeLow==0 ){
34116         attr = INVALID_FILE_ATTRIBUTES;
34117       }else{
34118         attr = sAttrData.dwFileAttributes;
34119       }
34120     }else{
34121       logIoerr(cnt);
34122       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
34123         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
34124         sqlite3_free(zConverted);
34125         return SQLITE_IOERR_ACCESS;
34126       }else{
34127         attr = INVALID_FILE_ATTRIBUTES;
34128       }
34129     }
34130   }
34131 #ifdef SQLITE_WIN32_HAS_ANSI
34132   else{
34133     attr = osGetFileAttributesA((char*)zConverted);
34134   }
34135 #endif
34136   sqlite3_free(zConverted);
34137   switch( flags ){
34138     case SQLITE_ACCESS_READ:
34139     case SQLITE_ACCESS_EXISTS:
34140       rc = attr!=INVALID_FILE_ATTRIBUTES;
34141       break;
34142     case SQLITE_ACCESS_READWRITE:
34143       rc = attr!=INVALID_FILE_ATTRIBUTES &&
34144              (attr & FILE_ATTRIBUTE_READONLY)==0;
34145       break;
34146     default:
34147       assert(!"Invalid flags argument");
34148   }
34149   *pResOut = rc;
34150   return SQLITE_OK;
34151 }
34152
34153
34154 /*
34155 ** Returns non-zero if the specified path name should be used verbatim.  If
34156 ** non-zero is returned from this function, the calling function must simply
34157 ** use the provided path name verbatim -OR- resolve it into a full path name
34158 ** using the GetFullPathName Win32 API function (if available).
34159 */
34160 static BOOL winIsVerbatimPathname(
34161   const char *zPathname
34162 ){
34163   /*
34164   ** If the path name starts with a forward slash or a backslash, it is either
34165   ** a legal UNC name, a volume relative path, or an absolute path name in the
34166   ** "Unix" format on Windows.  There is no easy way to differentiate between
34167   ** the final two cases; therefore, we return the safer return value of TRUE
34168   ** so that callers of this function will simply use it verbatim.
34169   */
34170   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
34171     return TRUE;
34172   }
34173
34174   /*
34175   ** If the path name starts with a letter and a colon it is either a volume
34176   ** relative path or an absolute path.  Callers of this function must not
34177   ** attempt to treat it as a relative path name (i.e. they should simply use
34178   ** it verbatim).
34179   */
34180   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
34181     return TRUE;
34182   }
34183
34184   /*
34185   ** If we get to this point, the path name should almost certainly be a purely
34186   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
34187   */
34188   return FALSE;
34189 }
34190
34191 /*
34192 ** Turn a relative pathname into a full pathname.  Write the full
34193 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
34194 ** bytes in size.
34195 */
34196 static int winFullPathname(
34197   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
34198   const char *zRelative,        /* Possibly relative input path */
34199   int nFull,                    /* Size of output buffer in bytes */
34200   char *zFull                   /* Output buffer */
34201 ){
34202   
34203 #if defined(__CYGWIN__)
34204   SimulateIOError( return SQLITE_ERROR );
34205   UNUSED_PARAMETER(nFull);
34206   assert( pVfs->mxPathname>=MAX_PATH );
34207   assert( nFull>=pVfs->mxPathname );
34208   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34209     /*
34210     ** NOTE: We are dealing with a relative path name and the data
34211     **       directory has been set.  Therefore, use it as the basis
34212     **       for converting the relative path name to an absolute
34213     **       one by prepending the data directory and a slash.
34214     */
34215     char zOut[MAX_PATH+1];
34216     memset(zOut, 0, MAX_PATH+1);
34217     cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */
34218     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34219                      sqlite3_data_directory, zOut);
34220   }else{
34221     /*
34222     ** NOTE: The Cygwin docs state that the maximum length needed
34223     **       for the buffer passed to cygwin_conv_to_full_win32_path
34224     **       is MAX_PATH.
34225     */
34226     cygwin_conv_to_full_win32_path(zRelative, zFull);
34227   }
34228   return SQLITE_OK;
34229 #endif
34230
34231 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
34232   SimulateIOError( return SQLITE_ERROR );
34233   /* WinCE has no concept of a relative pathname, or so I am told. */
34234   /* WinRT has no way to convert a relative path to an absolute one. */
34235   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34236     /*
34237     ** NOTE: We are dealing with a relative path name and the data
34238     **       directory has been set.  Therefore, use it as the basis
34239     **       for converting the relative path name to an absolute
34240     **       one by prepending the data directory and a backslash.
34241     */
34242     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34243                      sqlite3_data_directory, zRelative);
34244   }else{
34245     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
34246   }
34247   return SQLITE_OK;
34248 #endif
34249
34250 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
34251   DWORD nByte;
34252   void *zConverted;
34253   char *zOut;
34254
34255   /* If this path name begins with "/X:", where "X" is any alphabetic
34256   ** character, discard the initial "/" from the pathname.
34257   */
34258   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
34259     zRelative++;
34260   }
34261
34262   /* It's odd to simulate an io-error here, but really this is just
34263   ** using the io-error infrastructure to test that SQLite handles this
34264   ** function failing. This function could fail if, for example, the
34265   ** current working directory has been unlinked.
34266   */
34267   SimulateIOError( return SQLITE_ERROR );
34268   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34269     /*
34270     ** NOTE: We are dealing with a relative path name and the data
34271     **       directory has been set.  Therefore, use it as the basis
34272     **       for converting the relative path name to an absolute
34273     **       one by prepending the data directory and a backslash.
34274     */
34275     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34276                      sqlite3_data_directory, zRelative);
34277     return SQLITE_OK;
34278   }
34279   zConverted = convertUtf8Filename(zRelative);
34280   if( zConverted==0 ){
34281     return SQLITE_IOERR_NOMEM;
34282   }
34283   if( isNT() ){
34284     LPWSTR zTemp;
34285     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
34286     if( nByte==0 ){
34287       winLogError(SQLITE_ERROR, osGetLastError(),
34288                   "GetFullPathNameW1", zConverted);
34289       sqlite3_free(zConverted);
34290       return SQLITE_CANTOPEN_FULLPATH;
34291     }
34292     nByte += 3;
34293     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34294     if( zTemp==0 ){
34295       sqlite3_free(zConverted);
34296       return SQLITE_IOERR_NOMEM;
34297     }
34298     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
34299     if( nByte==0 ){
34300       winLogError(SQLITE_ERROR, osGetLastError(),
34301                   "GetFullPathNameW2", zConverted);
34302       sqlite3_free(zConverted);
34303       sqlite3_free(zTemp);
34304       return SQLITE_CANTOPEN_FULLPATH;
34305     }
34306     sqlite3_free(zConverted);
34307     zOut = unicodeToUtf8(zTemp);
34308     sqlite3_free(zTemp);
34309   }
34310 #ifdef SQLITE_WIN32_HAS_ANSI
34311   else{
34312     char *zTemp;
34313     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
34314     if( nByte==0 ){
34315       winLogError(SQLITE_ERROR, osGetLastError(),
34316                   "GetFullPathNameA1", zConverted);
34317       sqlite3_free(zConverted);
34318       return SQLITE_CANTOPEN_FULLPATH;
34319     }
34320     nByte += 3;
34321     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34322     if( zTemp==0 ){
34323       sqlite3_free(zConverted);
34324       return SQLITE_IOERR_NOMEM;
34325     }
34326     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
34327     if( nByte==0 ){
34328       winLogError(SQLITE_ERROR, osGetLastError(),
34329                   "GetFullPathNameA2", zConverted);
34330       sqlite3_free(zConverted);
34331       sqlite3_free(zTemp);
34332       return SQLITE_CANTOPEN_FULLPATH;
34333     }
34334     sqlite3_free(zConverted);
34335     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34336     sqlite3_free(zTemp);
34337   }
34338 #endif
34339   if( zOut ){
34340     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
34341     sqlite3_free(zOut);
34342     return SQLITE_OK;
34343   }else{
34344     return SQLITE_IOERR_NOMEM;
34345   }
34346 #endif
34347 }
34348
34349 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34350 /*
34351 ** Interfaces for opening a shared library, finding entry points
34352 ** within the shared library, and closing the shared library.
34353 */
34354 /*
34355 ** Interfaces for opening a shared library, finding entry points
34356 ** within the shared library, and closing the shared library.
34357 */
34358 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34359   HANDLE h;
34360   void *zConverted = convertUtf8Filename(zFilename);
34361   UNUSED_PARAMETER(pVfs);
34362   if( zConverted==0 ){
34363     return 0;
34364   }
34365   if( isNT() ){
34366 #if SQLITE_OS_WINRT
34367     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
34368 #else
34369     h = osLoadLibraryW((LPCWSTR)zConverted);
34370 #endif
34371   }
34372 #ifdef SQLITE_WIN32_HAS_ANSI
34373   else{
34374     h = osLoadLibraryA((char*)zConverted);
34375   }
34376 #endif
34377   sqlite3_free(zConverted);
34378   return (void*)h;
34379 }
34380 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34381   UNUSED_PARAMETER(pVfs);
34382   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
34383 }
34384 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
34385   UNUSED_PARAMETER(pVfs);
34386   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
34387 }
34388 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34389   UNUSED_PARAMETER(pVfs);
34390   osFreeLibrary((HANDLE)pHandle);
34391 }
34392 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34393   #define winDlOpen  0
34394   #define winDlError 0
34395   #define winDlSym   0
34396   #define winDlClose 0
34397 #endif
34398
34399
34400 /*
34401 ** Write up to nBuf bytes of randomness into zBuf.
34402 */
34403 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34404   int n = 0;
34405   UNUSED_PARAMETER(pVfs);
34406 #if defined(SQLITE_TEST)
34407   n = nBuf;
34408   memset(zBuf, 0, nBuf);
34409 #else
34410   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34411     SYSTEMTIME x;
34412     osGetSystemTime(&x);
34413     memcpy(&zBuf[n], &x, sizeof(x));
34414     n += sizeof(x);
34415   }
34416   if( sizeof(DWORD)<=nBuf-n ){
34417     DWORD pid = osGetCurrentProcessId();
34418     memcpy(&zBuf[n], &pid, sizeof(pid));
34419     n += sizeof(pid);
34420   }
34421 #if SQLITE_OS_WINRT
34422   if( sizeof(ULONGLONG)<=nBuf-n ){
34423     ULONGLONG cnt = osGetTickCount64();
34424     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34425     n += sizeof(cnt);
34426   }
34427 #else
34428   if( sizeof(DWORD)<=nBuf-n ){
34429     DWORD cnt = osGetTickCount();
34430     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34431     n += sizeof(cnt);
34432   }
34433 #endif
34434   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34435     LARGE_INTEGER i;
34436     osQueryPerformanceCounter(&i);
34437     memcpy(&zBuf[n], &i, sizeof(i));
34438     n += sizeof(i);
34439   }
34440 #endif
34441   return n;
34442 }
34443
34444
34445 /*
34446 ** Sleep for a little while.  Return the amount of time slept.
34447 */
34448 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34449   sqlite3_win32_sleep((microsec+999)/1000);
34450   UNUSED_PARAMETER(pVfs);
34451   return ((microsec+999)/1000)*1000;
34452 }
34453
34454 /*
34455 ** The following variable, if set to a non-zero value, is interpreted as
34456 ** the number of seconds since 1970 and is used to set the result of
34457 ** sqlite3OsCurrentTime() during testing.
34458 */
34459 #ifdef SQLITE_TEST
34460 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34461 #endif
34462
34463 /*
34464 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34465 ** the current time and date as a Julian Day number times 86_400_000.  In
34466 ** other words, write into *piNow the number of milliseconds since the Julian
34467 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34468 ** proleptic Gregorian calendar.
34469 **
34470 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
34471 ** cannot be found.
34472 */
34473 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34474   /* FILETIME structure is a 64-bit value representing the number of 
34475      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
34476   */
34477   FILETIME ft;
34478   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34479 #ifdef SQLITE_TEST
34480   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34481 #endif
34482   /* 2^32 - to avoid use of LL and warnings in gcc */
34483   static const sqlite3_int64 max32BitValue = 
34484       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
34485
34486 #if SQLITE_OS_WINCE
34487   SYSTEMTIME time;
34488   osGetSystemTime(&time);
34489   /* if SystemTimeToFileTime() fails, it returns zero. */
34490   if (!osSystemTimeToFileTime(&time,&ft)){
34491     return SQLITE_ERROR;
34492   }
34493 #else
34494   osGetSystemTimeAsFileTime( &ft );
34495 #endif
34496
34497   *piNow = winFiletimeEpoch +
34498             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
34499                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34500
34501 #ifdef SQLITE_TEST
34502   if( sqlite3_current_time ){
34503     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34504   }
34505 #endif
34506   UNUSED_PARAMETER(pVfs);
34507   return SQLITE_OK;
34508 }
34509
34510 /*
34511 ** Find the current time (in Universal Coordinated Time).  Write the
34512 ** current time and date as a Julian Day number into *prNow and
34513 ** return 0.  Return 1 if the time and date cannot be found.
34514 */
34515 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34516   int rc;
34517   sqlite3_int64 i;
34518   rc = winCurrentTimeInt64(pVfs, &i);
34519   if( !rc ){
34520     *prNow = i/86400000.0;
34521   }
34522   return rc;
34523 }
34524
34525 /*
34526 ** The idea is that this function works like a combination of
34527 ** GetLastError() and FormatMessage() on Windows (or errno and
34528 ** strerror_r() on Unix). After an error is returned by an OS
34529 ** function, SQLite calls this function with zBuf pointing to
34530 ** a buffer of nBuf bytes. The OS layer should populate the
34531 ** buffer with a nul-terminated UTF-8 encoded error message
34532 ** describing the last IO error to have occurred within the calling
34533 ** thread.
34534 **
34535 ** If the error message is too large for the supplied buffer,
34536 ** it should be truncated. The return value of xGetLastError
34537 ** is zero if the error message fits in the buffer, or non-zero
34538 ** otherwise (if the message was truncated). If non-zero is returned,
34539 ** then it is not necessary to include the nul-terminator character
34540 ** in the output buffer.
34541 **
34542 ** Not supplying an error message will have no adverse effect
34543 ** on SQLite. It is fine to have an implementation that never
34544 ** returns an error message:
34545 **
34546 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34547 **     assert(zBuf[0]=='\0');
34548 **     return 0;
34549 **   }
34550 **
34551 ** However if an error message is supplied, it will be incorporated
34552 ** by sqlite into the error message available to the user using
34553 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34554 */
34555 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34556   UNUSED_PARAMETER(pVfs);
34557   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
34558 }
34559
34560 /*
34561 ** Initialize and deinitialize the operating system interface.
34562 */
34563 SQLITE_API int sqlite3_os_init(void){
34564   static sqlite3_vfs winVfs = {
34565     3,                   /* iVersion */
34566     sizeof(winFile),     /* szOsFile */
34567     MAX_PATH,            /* mxPathname */
34568     0,                   /* pNext */
34569     "win32",             /* zName */
34570     0,                   /* pAppData */
34571     winOpen,             /* xOpen */
34572     winDelete,           /* xDelete */
34573     winAccess,           /* xAccess */
34574     winFullPathname,     /* xFullPathname */
34575     winDlOpen,           /* xDlOpen */
34576     winDlError,          /* xDlError */
34577     winDlSym,            /* xDlSym */
34578     winDlClose,          /* xDlClose */
34579     winRandomness,       /* xRandomness */
34580     winSleep,            /* xSleep */
34581     winCurrentTime,      /* xCurrentTime */
34582     winGetLastError,     /* xGetLastError */
34583     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34584     winSetSystemCall,    /* xSetSystemCall */
34585     winGetSystemCall,    /* xGetSystemCall */
34586     winNextSystemCall,   /* xNextSystemCall */
34587   };
34588
34589   /* Double-check that the aSyscall[] array has been constructed
34590   ** correctly.  See ticket [bb3a86e890c8e96ab] */
34591   assert( ArraySize(aSyscall)==74 );
34592
34593 #ifndef SQLITE_OMIT_WAL
34594   /* get memory map allocation granularity */
34595   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34596 #if SQLITE_OS_WINRT
34597   osGetNativeSystemInfo(&winSysInfo);
34598 #else
34599   osGetSystemInfo(&winSysInfo);
34600 #endif
34601   assert(winSysInfo.dwAllocationGranularity > 0);
34602 #endif
34603
34604   sqlite3_vfs_register(&winVfs, 1);
34605   return SQLITE_OK; 
34606 }
34607
34608 SQLITE_API int sqlite3_os_end(void){ 
34609 #if SQLITE_OS_WINRT
34610   if( sleepObj!=NULL ){
34611     osCloseHandle(sleepObj);
34612     sleepObj = NULL;
34613   }
34614 #endif
34615   return SQLITE_OK;
34616 }
34617
34618 #endif /* SQLITE_OS_WIN */
34619
34620 /************** End of os_win.c **********************************************/
34621 /************** Begin file bitvec.c ******************************************/
34622 /*
34623 ** 2008 February 16
34624 **
34625 ** The author disclaims copyright to this source code.  In place of
34626 ** a legal notice, here is a blessing:
34627 **
34628 **    May you do good and not evil.
34629 **    May you find forgiveness for yourself and forgive others.
34630 **    May you share freely, never taking more than you give.
34631 **
34632 *************************************************************************
34633 ** This file implements an object that represents a fixed-length
34634 ** bitmap.  Bits are numbered starting with 1.
34635 **
34636 ** A bitmap is used to record which pages of a database file have been
34637 ** journalled during a transaction, or which pages have the "dont-write"
34638 ** property.  Usually only a few pages are meet either condition.
34639 ** So the bitmap is usually sparse and has low cardinality.
34640 ** But sometimes (for example when during a DROP of a large table) most
34641 ** or all of the pages in a database can get journalled.  In those cases, 
34642 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
34643 ** to handle both cases well.
34644 **
34645 ** The size of the bitmap is fixed when the object is created.
34646 **
34647 ** All bits are clear when the bitmap is created.  Individual bits
34648 ** may be set or cleared one at a time.
34649 **
34650 ** Test operations are about 100 times more common that set operations.
34651 ** Clear operations are exceedingly rare.  There are usually between
34652 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34653 ** sometimes grow into tens of thousands or larger.  The size of the
34654 ** Bitvec object is the number of pages in the database file at the
34655 ** start of a transaction, and is thus usually less than a few thousand,
34656 ** but can be as large as 2 billion for a really big database.
34657 */
34658
34659 /* Size of the Bitvec structure in bytes. */
34660 #define BITVEC_SZ        512
34661
34662 /* Round the union size down to the nearest pointer boundary, since that's how 
34663 ** it will be aligned within the Bitvec struct. */
34664 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34665
34666 /* Type of the array "element" for the bitmap representation. 
34667 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
34668 ** Setting this to the "natural word" size of your CPU may improve
34669 ** performance. */
34670 #define BITVEC_TELEM     u8
34671 /* Size, in bits, of the bitmap element. */
34672 #define BITVEC_SZELEM    8
34673 /* Number of elements in a bitmap array. */
34674 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34675 /* Number of bits in the bitmap array. */
34676 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34677
34678 /* Number of u32 values in hash table. */
34679 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34680 /* Maximum number of entries in hash table before 
34681 ** sub-dividing and re-hashing. */
34682 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34683 /* Hashing function for the aHash representation.
34684 ** Empirical testing showed that the *37 multiplier 
34685 ** (an arbitrary prime)in the hash function provided 
34686 ** no fewer collisions than the no-op *1. */
34687 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34688
34689 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34690
34691
34692 /*
34693 ** A bitmap is an instance of the following structure.
34694 **
34695 ** This bitmap records the existance of zero or more bits
34696 ** with values between 1 and iSize, inclusive.
34697 **
34698 ** There are three possible representations of the bitmap.
34699 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34700 ** bitmap.  The least significant bit is bit 1.
34701 **
34702 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34703 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34704 **
34705 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34706 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34707 ** handles up to iDivisor separate values of i.  apSub[0] holds
34708 ** values between 1 and iDivisor.  apSub[1] holds values between
34709 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34710 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34711 ** to hold deal with values between 1 and iDivisor.
34712 */
34713 struct Bitvec {
34714   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34715   u32 nSet;       /* Number of bits that are set - only valid for aHash
34716                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34717                   ** this would be 125. */
34718   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34719                   /* Should >=0 for apSub element. */
34720                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34721                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34722   union {
34723     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34724     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34725     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34726   } u;
34727 };
34728
34729 /*
34730 ** Create a new bitmap object able to handle bits between 0 and iSize,
34731 ** inclusive.  Return a pointer to the new object.  Return NULL if 
34732 ** malloc fails.
34733 */
34734 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34735   Bitvec *p;
34736   assert( sizeof(*p)==BITVEC_SZ );
34737   p = sqlite3MallocZero( sizeof(*p) );
34738   if( p ){
34739     p->iSize = iSize;
34740   }
34741   return p;
34742 }
34743
34744 /*
34745 ** Check to see if the i-th bit is set.  Return true or false.
34746 ** If p is NULL (if the bitmap has not been created) or if
34747 ** i is out of range, then return false.
34748 */
34749 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34750   if( p==0 ) return 0;
34751   if( i>p->iSize || i==0 ) return 0;
34752   i--;
34753   while( p->iDivisor ){
34754     u32 bin = i/p->iDivisor;
34755     i = i%p->iDivisor;
34756     p = p->u.apSub[bin];
34757     if (!p) {
34758       return 0;
34759     }
34760   }
34761   if( p->iSize<=BITVEC_NBIT ){
34762     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34763   } else{
34764     u32 h = BITVEC_HASH(i++);
34765     while( p->u.aHash[h] ){
34766       if( p->u.aHash[h]==i ) return 1;
34767       h = (h+1) % BITVEC_NINT;
34768     }
34769     return 0;
34770   }
34771 }
34772
34773 /*
34774 ** Set the i-th bit.  Return 0 on success and an error code if
34775 ** anything goes wrong.
34776 **
34777 ** This routine might cause sub-bitmaps to be allocated.  Failing
34778 ** to get the memory needed to hold the sub-bitmap is the only
34779 ** that can go wrong with an insert, assuming p and i are valid.
34780 **
34781 ** The calling function must ensure that p is a valid Bitvec object
34782 ** and that the value for "i" is within range of the Bitvec object.
34783 ** Otherwise the behavior is undefined.
34784 */
34785 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34786   u32 h;
34787   if( p==0 ) return SQLITE_OK;
34788   assert( i>0 );
34789   assert( i<=p->iSize );
34790   i--;
34791   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34792     u32 bin = i/p->iDivisor;
34793     i = i%p->iDivisor;
34794     if( p->u.apSub[bin]==0 ){
34795       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34796       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34797     }
34798     p = p->u.apSub[bin];
34799   }
34800   if( p->iSize<=BITVEC_NBIT ){
34801     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34802     return SQLITE_OK;
34803   }
34804   h = BITVEC_HASH(i++);
34805   /* if there wasn't a hash collision, and this doesn't */
34806   /* completely fill the hash, then just add it without */
34807   /* worring about sub-dividing and re-hashing. */
34808   if( !p->u.aHash[h] ){
34809     if (p->nSet<(BITVEC_NINT-1)) {
34810       goto bitvec_set_end;
34811     } else {
34812       goto bitvec_set_rehash;
34813     }
34814   }
34815   /* there was a collision, check to see if it's already */
34816   /* in hash, if not, try to find a spot for it */
34817   do {
34818     if( p->u.aHash[h]==i ) return SQLITE_OK;
34819     h++;
34820     if( h>=BITVEC_NINT ) h = 0;
34821   } while( p->u.aHash[h] );
34822   /* we didn't find it in the hash.  h points to the first */
34823   /* available free spot. check to see if this is going to */
34824   /* make our hash too "full".  */
34825 bitvec_set_rehash:
34826   if( p->nSet>=BITVEC_MXHASH ){
34827     unsigned int j;
34828     int rc;
34829     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34830     if( aiValues==0 ){
34831       return SQLITE_NOMEM;
34832     }else{
34833       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34834       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34835       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34836       rc = sqlite3BitvecSet(p, i);
34837       for(j=0; j<BITVEC_NINT; j++){
34838         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34839       }
34840       sqlite3StackFree(0, aiValues);
34841       return rc;
34842     }
34843   }
34844 bitvec_set_end:
34845   p->nSet++;
34846   p->u.aHash[h] = i;
34847   return SQLITE_OK;
34848 }
34849
34850 /*
34851 ** Clear the i-th bit.
34852 **
34853 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34854 ** that BitvecClear can use to rebuilt its hash table.
34855 */
34856 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34857   if( p==0 ) return;
34858   assert( i>0 );
34859   i--;
34860   while( p->iDivisor ){
34861     u32 bin = i/p->iDivisor;
34862     i = i%p->iDivisor;
34863     p = p->u.apSub[bin];
34864     if (!p) {
34865       return;
34866     }
34867   }
34868   if( p->iSize<=BITVEC_NBIT ){
34869     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34870   }else{
34871     unsigned int j;
34872     u32 *aiValues = pBuf;
34873     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34874     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34875     p->nSet = 0;
34876     for(j=0; j<BITVEC_NINT; j++){
34877       if( aiValues[j] && aiValues[j]!=(i+1) ){
34878         u32 h = BITVEC_HASH(aiValues[j]-1);
34879         p->nSet++;
34880         while( p->u.aHash[h] ){
34881           h++;
34882           if( h>=BITVEC_NINT ) h = 0;
34883         }
34884         p->u.aHash[h] = aiValues[j];
34885       }
34886     }
34887   }
34888 }
34889
34890 /*
34891 ** Destroy a bitmap object.  Reclaim all memory used.
34892 */
34893 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34894   if( p==0 ) return;
34895   if( p->iDivisor ){
34896     unsigned int i;
34897     for(i=0; i<BITVEC_NPTR; i++){
34898       sqlite3BitvecDestroy(p->u.apSub[i]);
34899     }
34900   }
34901   sqlite3_free(p);
34902 }
34903
34904 /*
34905 ** Return the value of the iSize parameter specified when Bitvec *p
34906 ** was created.
34907 */
34908 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34909   return p->iSize;
34910 }
34911
34912 #ifndef SQLITE_OMIT_BUILTIN_TEST
34913 /*
34914 ** Let V[] be an array of unsigned characters sufficient to hold
34915 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34916 ** Then the following macros can be used to set, clear, or test
34917 ** individual bits within V.
34918 */
34919 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34920 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34921 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34922
34923 /*
34924 ** This routine runs an extensive test of the Bitvec code.
34925 **
34926 ** The input is an array of integers that acts as a program
34927 ** to test the Bitvec.  The integers are opcodes followed
34928 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34929 ** opcode follows immediately after the last operand.
34930 **
34931 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34932 ** "halt" opcode and causes the test to end.
34933 **
34934 **    0          Halt and return the number of errors
34935 **    1 N S X    Set N bits beginning with S and incrementing by X
34936 **    2 N S X    Clear N bits beginning with S and incrementing by X
34937 **    3 N        Set N randomly chosen bits
34938 **    4 N        Clear N randomly chosen bits
34939 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
34940 **
34941 ** The opcodes 1 through 4 perform set and clear operations are performed
34942 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34943 ** Opcode 5 works on the linear array only, not on the Bitvec.
34944 ** Opcode 5 is used to deliberately induce a fault in order to
34945 ** confirm that error detection works.
34946 **
34947 ** At the conclusion of the test the linear array is compared
34948 ** against the Bitvec object.  If there are any differences,
34949 ** an error is returned.  If they are the same, zero is returned.
34950 **
34951 ** If a memory allocation error occurs, return -1.
34952 */
34953 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34954   Bitvec *pBitvec = 0;
34955   unsigned char *pV = 0;
34956   int rc = -1;
34957   int i, nx, pc, op;
34958   void *pTmpSpace;
34959
34960   /* Allocate the Bitvec to be tested and a linear array of
34961   ** bits to act as the reference */
34962   pBitvec = sqlite3BitvecCreate( sz );
34963   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
34964   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34965   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34966
34967   /* NULL pBitvec tests */
34968   sqlite3BitvecSet(0, 1);
34969   sqlite3BitvecClear(0, 1, pTmpSpace);
34970
34971   /* Run the program */
34972   pc = 0;
34973   while( (op = aOp[pc])!=0 ){
34974     switch( op ){
34975       case 1:
34976       case 2:
34977       case 5: {
34978         nx = 4;
34979         i = aOp[pc+2] - 1;
34980         aOp[pc+2] += aOp[pc+3];
34981         break;
34982       }
34983       case 3:
34984       case 4: 
34985       default: {
34986         nx = 2;
34987         sqlite3_randomness(sizeof(i), &i);
34988         break;
34989       }
34990     }
34991     if( (--aOp[pc+1]) > 0 ) nx = 0;
34992     pc += nx;
34993     i = (i & 0x7fffffff)%sz;
34994     if( (op & 1)!=0 ){
34995       SETBIT(pV, (i+1));
34996       if( op!=5 ){
34997         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34998       }
34999     }else{
35000       CLEARBIT(pV, (i+1));
35001       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
35002     }
35003   }
35004
35005   /* Test to make sure the linear array exactly matches the
35006   ** Bitvec object.  Start with the assumption that they do
35007   ** match (rc==0).  Change rc to non-zero if a discrepancy
35008   ** is found.
35009   */
35010   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
35011           + sqlite3BitvecTest(pBitvec, 0)
35012           + (sqlite3BitvecSize(pBitvec) - sz);
35013   for(i=1; i<=sz; i++){
35014     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
35015       rc = i;
35016       break;
35017     }
35018   }
35019
35020   /* Free allocated structure */
35021 bitvec_end:
35022   sqlite3_free(pTmpSpace);
35023   sqlite3_free(pV);
35024   sqlite3BitvecDestroy(pBitvec);
35025   return rc;
35026 }
35027 #endif /* SQLITE_OMIT_BUILTIN_TEST */
35028
35029 /************** End of bitvec.c **********************************************/
35030 /************** Begin file pcache.c ******************************************/
35031 /*
35032 ** 2008 August 05
35033 **
35034 ** The author disclaims copyright to this source code.  In place of
35035 ** a legal notice, here is a blessing:
35036 **
35037 **    May you do good and not evil.
35038 **    May you find forgiveness for yourself and forgive others.
35039 **    May you share freely, never taking more than you give.
35040 **
35041 *************************************************************************
35042 ** This file implements that page cache.
35043 */
35044
35045 /*
35046 ** A complete page cache is an instance of this structure.
35047 */
35048 struct PCache {
35049   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
35050   PgHdr *pSynced;                     /* Last synced page in dirty page list */
35051   int nRef;                           /* Number of referenced pages */
35052   int szCache;                        /* Configured cache size */
35053   int szPage;                         /* Size of every page in this cache */
35054   int szExtra;                        /* Size of extra space for each page */
35055   int bPurgeable;                     /* True if pages are on backing store */
35056   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
35057   void *pStress;                      /* Argument to xStress */
35058   sqlite3_pcache *pCache;             /* Pluggable cache module */
35059   PgHdr *pPage1;                      /* Reference to page 1 */
35060 };
35061
35062 /*
35063 ** Some of the assert() macros in this code are too expensive to run
35064 ** even during normal debugging.  Use them only rarely on long-running
35065 ** tests.  Enable the expensive asserts using the
35066 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
35067 */
35068 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
35069 # define expensive_assert(X)  assert(X)
35070 #else
35071 # define expensive_assert(X)
35072 #endif
35073
35074 /********************************** Linked List Management ********************/
35075
35076 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
35077 /*
35078 ** Check that the pCache->pSynced variable is set correctly. If it
35079 ** is not, either fail an assert or return zero. Otherwise, return
35080 ** non-zero. This is only used in debugging builds, as follows:
35081 **
35082 **   expensive_assert( pcacheCheckSynced(pCache) );
35083 */
35084 static int pcacheCheckSynced(PCache *pCache){
35085   PgHdr *p;
35086   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
35087     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
35088   }
35089   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
35090 }
35091 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
35092
35093 /*
35094 ** Remove page pPage from the list of dirty pages.
35095 */
35096 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
35097   PCache *p = pPage->pCache;
35098
35099   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
35100   assert( pPage->pDirtyPrev || pPage==p->pDirty );
35101
35102   /* Update the PCache1.pSynced variable if necessary. */
35103   if( p->pSynced==pPage ){
35104     PgHdr *pSynced = pPage->pDirtyPrev;
35105     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
35106       pSynced = pSynced->pDirtyPrev;
35107     }
35108     p->pSynced = pSynced;
35109   }
35110
35111   if( pPage->pDirtyNext ){
35112     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
35113   }else{
35114     assert( pPage==p->pDirtyTail );
35115     p->pDirtyTail = pPage->pDirtyPrev;
35116   }
35117   if( pPage->pDirtyPrev ){
35118     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
35119   }else{
35120     assert( pPage==p->pDirty );
35121     p->pDirty = pPage->pDirtyNext;
35122   }
35123   pPage->pDirtyNext = 0;
35124   pPage->pDirtyPrev = 0;
35125
35126   expensive_assert( pcacheCheckSynced(p) );
35127 }
35128
35129 /*
35130 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
35131 ** pPage).
35132 */
35133 static void pcacheAddToDirtyList(PgHdr *pPage){
35134   PCache *p = pPage->pCache;
35135
35136   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
35137
35138   pPage->pDirtyNext = p->pDirty;
35139   if( pPage->pDirtyNext ){
35140     assert( pPage->pDirtyNext->pDirtyPrev==0 );
35141     pPage->pDirtyNext->pDirtyPrev = pPage;
35142   }
35143   p->pDirty = pPage;
35144   if( !p->pDirtyTail ){
35145     p->pDirtyTail = pPage;
35146   }
35147   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
35148     p->pSynced = pPage;
35149   }
35150   expensive_assert( pcacheCheckSynced(p) );
35151 }
35152
35153 /*
35154 ** Wrapper around the pluggable caches xUnpin method. If the cache is
35155 ** being used for an in-memory database, this function is a no-op.
35156 */
35157 static void pcacheUnpin(PgHdr *p){
35158   PCache *pCache = p->pCache;
35159   if( pCache->bPurgeable ){
35160     if( p->pgno==1 ){
35161       pCache->pPage1 = 0;
35162     }
35163     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
35164   }
35165 }
35166
35167 /*************************************************** General Interfaces ******
35168 **
35169 ** Initialize and shutdown the page cache subsystem. Neither of these 
35170 ** functions are threadsafe.
35171 */
35172 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
35173   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
35174     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
35175     ** built-in default page cache is used instead of the application defined
35176     ** page cache. */
35177     sqlite3PCacheSetDefault();
35178   }
35179   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
35180 }
35181 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
35182   if( sqlite3GlobalConfig.pcache2.xShutdown ){
35183     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
35184     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
35185   }
35186 }
35187
35188 /*
35189 ** Return the size in bytes of a PCache object.
35190 */
35191 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
35192
35193 /*
35194 ** Create a new PCache object. Storage space to hold the object
35195 ** has already been allocated and is passed in as the p pointer. 
35196 ** The caller discovers how much space needs to be allocated by 
35197 ** calling sqlite3PcacheSize().
35198 */
35199 SQLITE_PRIVATE void sqlite3PcacheOpen(
35200   int szPage,                  /* Size of every page */
35201   int szExtra,                 /* Extra space associated with each page */
35202   int bPurgeable,              /* True if pages are on backing store */
35203   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
35204   void *pStress,               /* Argument to xStress */
35205   PCache *p                    /* Preallocated space for the PCache */
35206 ){
35207   memset(p, 0, sizeof(PCache));
35208   p->szPage = szPage;
35209   p->szExtra = szExtra;
35210   p->bPurgeable = bPurgeable;
35211   p->xStress = xStress;
35212   p->pStress = pStress;
35213   p->szCache = 100;
35214 }
35215
35216 /*
35217 ** Change the page size for PCache object. The caller must ensure that there
35218 ** are no outstanding page references when this function is called.
35219 */
35220 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
35221   assert( pCache->nRef==0 && pCache->pDirty==0 );
35222   if( pCache->pCache ){
35223     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35224     pCache->pCache = 0;
35225     pCache->pPage1 = 0;
35226   }
35227   pCache->szPage = szPage;
35228 }
35229
35230 /*
35231 ** Compute the number of pages of cache requested.
35232 */
35233 static int numberOfCachePages(PCache *p){
35234   if( p->szCache>=0 ){
35235     return p->szCache;
35236   }else{
35237     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
35238   }
35239 }
35240
35241 /*
35242 ** Try to obtain a page from the cache.
35243 */
35244 SQLITE_PRIVATE int sqlite3PcacheFetch(
35245   PCache *pCache,       /* Obtain the page from this cache */
35246   Pgno pgno,            /* Page number to obtain */
35247   int createFlag,       /* If true, create page if it does not exist already */
35248   PgHdr **ppPage        /* Write the page here */
35249 ){
35250   sqlite3_pcache_page *pPage = 0;
35251   PgHdr *pPgHdr = 0;
35252   int eCreate;
35253
35254   assert( pCache!=0 );
35255   assert( createFlag==1 || createFlag==0 );
35256   assert( pgno>0 );
35257
35258   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
35259   ** allocate it now.
35260   */
35261   if( !pCache->pCache && createFlag ){
35262     sqlite3_pcache *p;
35263     p = sqlite3GlobalConfig.pcache2.xCreate(
35264         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
35265     );
35266     if( !p ){
35267       return SQLITE_NOMEM;
35268     }
35269     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
35270     pCache->pCache = p;
35271   }
35272
35273   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
35274   if( pCache->pCache ){
35275     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
35276   }
35277
35278   if( !pPage && eCreate==1 ){
35279     PgHdr *pPg;
35280
35281     /* Find a dirty page to write-out and recycle. First try to find a 
35282     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
35283     ** cleared), but if that is not possible settle for any other 
35284     ** unreferenced dirty page.
35285     */
35286     expensive_assert( pcacheCheckSynced(pCache) );
35287     for(pPg=pCache->pSynced; 
35288         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
35289         pPg=pPg->pDirtyPrev
35290     );
35291     pCache->pSynced = pPg;
35292     if( !pPg ){
35293       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
35294     }
35295     if( pPg ){
35296       int rc;
35297 #ifdef SQLITE_LOG_CACHE_SPILL
35298       sqlite3_log(SQLITE_FULL, 
35299                   "spill page %d making room for %d - cache used: %d/%d",
35300                   pPg->pgno, pgno,
35301                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
35302                   numberOfCachePages(pCache));
35303 #endif
35304       rc = pCache->xStress(pCache->pStress, pPg);
35305       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
35306         return rc;
35307       }
35308     }
35309
35310     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
35311   }
35312
35313   if( pPage ){
35314     pPgHdr = (PgHdr *)pPage->pExtra;
35315
35316     if( !pPgHdr->pPage ){
35317       memset(pPgHdr, 0, sizeof(PgHdr));
35318       pPgHdr->pPage = pPage;
35319       pPgHdr->pData = pPage->pBuf;
35320       pPgHdr->pExtra = (void *)&pPgHdr[1];
35321       memset(pPgHdr->pExtra, 0, pCache->szExtra);
35322       pPgHdr->pCache = pCache;
35323       pPgHdr->pgno = pgno;
35324     }
35325     assert( pPgHdr->pCache==pCache );
35326     assert( pPgHdr->pgno==pgno );
35327     assert( pPgHdr->pData==pPage->pBuf );
35328     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
35329
35330     if( 0==pPgHdr->nRef ){
35331       pCache->nRef++;
35332     }
35333     pPgHdr->nRef++;
35334     if( pgno==1 ){
35335       pCache->pPage1 = pPgHdr;
35336     }
35337   }
35338   *ppPage = pPgHdr;
35339   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
35340 }
35341
35342 /*
35343 ** Decrement the reference count on a page. If the page is clean and the
35344 ** reference count drops to 0, then it is made elible for recycling.
35345 */
35346 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
35347   assert( p->nRef>0 );
35348   p->nRef--;
35349   if( p->nRef==0 ){
35350     PCache *pCache = p->pCache;
35351     pCache->nRef--;
35352     if( (p->flags&PGHDR_DIRTY)==0 ){
35353       pcacheUnpin(p);
35354     }else{
35355       /* Move the page to the head of the dirty list. */
35356       pcacheRemoveFromDirtyList(p);
35357       pcacheAddToDirtyList(p);
35358     }
35359   }
35360 }
35361
35362 /*
35363 ** Increase the reference count of a supplied page by 1.
35364 */
35365 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35366   assert(p->nRef>0);
35367   p->nRef++;
35368 }
35369
35370 /*
35371 ** Drop a page from the cache. There must be exactly one reference to the
35372 ** page. This function deletes that reference, so after it returns the
35373 ** page pointed to by p is invalid.
35374 */
35375 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35376   PCache *pCache;
35377   assert( p->nRef==1 );
35378   if( p->flags&PGHDR_DIRTY ){
35379     pcacheRemoveFromDirtyList(p);
35380   }
35381   pCache = p->pCache;
35382   pCache->nRef--;
35383   if( p->pgno==1 ){
35384     pCache->pPage1 = 0;
35385   }
35386   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
35387 }
35388
35389 /*
35390 ** Make sure the page is marked as dirty. If it isn't dirty already,
35391 ** make it so.
35392 */
35393 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35394   p->flags &= ~PGHDR_DONT_WRITE;
35395   assert( p->nRef>0 );
35396   if( 0==(p->flags & PGHDR_DIRTY) ){
35397     p->flags |= PGHDR_DIRTY;
35398     pcacheAddToDirtyList( p);
35399   }
35400 }
35401
35402 /*
35403 ** Make sure the page is marked as clean. If it isn't clean already,
35404 ** make it so.
35405 */
35406 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35407   if( (p->flags & PGHDR_DIRTY) ){
35408     pcacheRemoveFromDirtyList(p);
35409     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35410     if( p->nRef==0 ){
35411       pcacheUnpin(p);
35412     }
35413   }
35414 }
35415
35416 /*
35417 ** Make every page in the cache clean.
35418 */
35419 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35420   PgHdr *p;
35421   while( (p = pCache->pDirty)!=0 ){
35422     sqlite3PcacheMakeClean(p);
35423   }
35424 }
35425
35426 /*
35427 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35428 */
35429 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35430   PgHdr *p;
35431   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35432     p->flags &= ~PGHDR_NEED_SYNC;
35433   }
35434   pCache->pSynced = pCache->pDirtyTail;
35435 }
35436
35437 /*
35438 ** Change the page number of page p to newPgno. 
35439 */
35440 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35441   PCache *pCache = p->pCache;
35442   assert( p->nRef>0 );
35443   assert( newPgno>0 );
35444   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
35445   p->pgno = newPgno;
35446   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35447     pcacheRemoveFromDirtyList(p);
35448     pcacheAddToDirtyList(p);
35449   }
35450 }
35451
35452 /*
35453 ** Drop every cache entry whose page number is greater than "pgno". The
35454 ** caller must ensure that there are no outstanding references to any pages
35455 ** other than page 1 with a page number greater than pgno.
35456 **
35457 ** If there is a reference to page 1 and the pgno parameter passed to this
35458 ** function is 0, then the data area associated with page 1 is zeroed, but
35459 ** the page object is not dropped.
35460 */
35461 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35462   if( pCache->pCache ){
35463     PgHdr *p;
35464     PgHdr *pNext;
35465     for(p=pCache->pDirty; p; p=pNext){
35466       pNext = p->pDirtyNext;
35467       /* This routine never gets call with a positive pgno except right
35468       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35469       ** it must be that pgno==0.
35470       */
35471       assert( p->pgno>0 );
35472       if( ALWAYS(p->pgno>pgno) ){
35473         assert( p->flags&PGHDR_DIRTY );
35474         sqlite3PcacheMakeClean(p);
35475       }
35476     }
35477     if( pgno==0 && pCache->pPage1 ){
35478       memset(pCache->pPage1->pData, 0, pCache->szPage);
35479       pgno = 1;
35480     }
35481     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
35482   }
35483 }
35484
35485 /*
35486 ** Close a cache.
35487 */
35488 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35489   if( pCache->pCache ){
35490     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35491   }
35492 }
35493
35494 /* 
35495 ** Discard the contents of the cache.
35496 */
35497 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35498   sqlite3PcacheTruncate(pCache, 0);
35499 }
35500
35501 /*
35502 ** Merge two lists of pages connected by pDirty and in pgno order.
35503 ** Do not both fixing the pDirtyPrev pointers.
35504 */
35505 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35506   PgHdr result, *pTail;
35507   pTail = &result;
35508   while( pA && pB ){
35509     if( pA->pgno<pB->pgno ){
35510       pTail->pDirty = pA;
35511       pTail = pA;
35512       pA = pA->pDirty;
35513     }else{
35514       pTail->pDirty = pB;
35515       pTail = pB;
35516       pB = pB->pDirty;
35517     }
35518   }
35519   if( pA ){
35520     pTail->pDirty = pA;
35521   }else if( pB ){
35522     pTail->pDirty = pB;
35523   }else{
35524     pTail->pDirty = 0;
35525   }
35526   return result.pDirty;
35527 }
35528
35529 /*
35530 ** Sort the list of pages in accending order by pgno.  Pages are
35531 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35532 ** corrupted by this sort.
35533 **
35534 ** Since there cannot be more than 2^31 distinct pages in a database,
35535 ** there cannot be more than 31 buckets required by the merge sorter.
35536 ** One extra bucket is added to catch overflow in case something
35537 ** ever changes to make the previous sentence incorrect.
35538 */
35539 #define N_SORT_BUCKET  32
35540 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35541   PgHdr *a[N_SORT_BUCKET], *p;
35542   int i;
35543   memset(a, 0, sizeof(a));
35544   while( pIn ){
35545     p = pIn;
35546     pIn = p->pDirty;
35547     p->pDirty = 0;
35548     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35549       if( a[i]==0 ){
35550         a[i] = p;
35551         break;
35552       }else{
35553         p = pcacheMergeDirtyList(a[i], p);
35554         a[i] = 0;
35555       }
35556     }
35557     if( NEVER(i==N_SORT_BUCKET-1) ){
35558       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35559       ** the input list.  But that is impossible.
35560       */
35561       a[i] = pcacheMergeDirtyList(a[i], p);
35562     }
35563   }
35564   p = a[0];
35565   for(i=1; i<N_SORT_BUCKET; i++){
35566     p = pcacheMergeDirtyList(p, a[i]);
35567   }
35568   return p;
35569 }
35570
35571 /*
35572 ** Return a list of all dirty pages in the cache, sorted by page number.
35573 */
35574 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35575   PgHdr *p;
35576   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35577     p->pDirty = p->pDirtyNext;
35578   }
35579   return pcacheSortDirtyList(pCache->pDirty);
35580 }
35581
35582 /* 
35583 ** Return the total number of referenced pages held by the cache.
35584 */
35585 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35586   return pCache->nRef;
35587 }
35588
35589 /*
35590 ** Return the number of references to the page supplied as an argument.
35591 */
35592 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35593   return p->nRef;
35594 }
35595
35596 /* 
35597 ** Return the total number of pages in the cache.
35598 */
35599 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35600   int nPage = 0;
35601   if( pCache->pCache ){
35602     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
35603   }
35604   return nPage;
35605 }
35606
35607 #ifdef SQLITE_TEST
35608 /*
35609 ** Get the suggested cache-size value.
35610 */
35611 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35612   return numberOfCachePages(pCache);
35613 }
35614 #endif
35615
35616 /*
35617 ** Set the suggested cache-size value.
35618 */
35619 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35620   pCache->szCache = mxPage;
35621   if( pCache->pCache ){
35622     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
35623                                            numberOfCachePages(pCache));
35624   }
35625 }
35626
35627 /*
35628 ** Free up as much memory as possible from the page cache.
35629 */
35630 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
35631   if( pCache->pCache ){
35632     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
35633   }
35634 }
35635
35636 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35637 /*
35638 ** For all dirty pages currently in the cache, invoke the specified
35639 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35640 ** defined.
35641 */
35642 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35643   PgHdr *pDirty;
35644   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35645     xIter(pDirty);
35646   }
35647 }
35648 #endif
35649
35650 /************** End of pcache.c **********************************************/
35651 /************** Begin file pcache1.c *****************************************/
35652 /*
35653 ** 2008 November 05
35654 **
35655 ** The author disclaims copyright to this source code.  In place of
35656 ** a legal notice, here is a blessing:
35657 **
35658 **    May you do good and not evil.
35659 **    May you find forgiveness for yourself and forgive others.
35660 **    May you share freely, never taking more than you give.
35661 **
35662 *************************************************************************
35663 **
35664 ** This file implements the default page cache implementation (the
35665 ** sqlite3_pcache interface). It also contains part of the implementation
35666 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35667 ** If the default page cache implementation is overriden, then neither of
35668 ** these two features are available.
35669 */
35670
35671
35672 typedef struct PCache1 PCache1;
35673 typedef struct PgHdr1 PgHdr1;
35674 typedef struct PgFreeslot PgFreeslot;
35675 typedef struct PGroup PGroup;
35676
35677 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
35678 ** of one or more PCaches that are able to recycle each others unpinned
35679 ** pages when they are under memory pressure.  A PGroup is an instance of
35680 ** the following object.
35681 **
35682 ** This page cache implementation works in one of two modes:
35683 **
35684 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35685 **        one PGroup per PCache.
35686 **
35687 **   (2)  There is a single global PGroup that all PCaches are a member
35688 **        of.
35689 **
35690 ** Mode 1 uses more memory (since PCache instances are not able to rob
35691 ** unused pages from other PCaches) but it also operates without a mutex,
35692 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35693 ** threadsafe, but recycles pages more efficiently.
35694 **
35695 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35696 ** PGroup which is the pcache1.grp global variable and its mutex is
35697 ** SQLITE_MUTEX_STATIC_LRU.
35698 */
35699 struct PGroup {
35700   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35701   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
35702   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
35703   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
35704   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
35705   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35706 };
35707
35708 /* Each page cache is an instance of the following object.  Every
35709 ** open database file (including each in-memory database and each
35710 ** temporary or transient database) has a single page cache which
35711 ** is an instance of this object.
35712 **
35713 ** Pointers to structures of this type are cast and returned as 
35714 ** opaque sqlite3_pcache* handles.
35715 */
35716 struct PCache1 {
35717   /* Cache configuration parameters. Page size (szPage) and the purgeable
35718   ** flag (bPurgeable) are set when the cache is created. nMax may be 
35719   ** modified at any time by a call to the pcache1Cachesize() method.
35720   ** The PGroup mutex must be held when accessing nMax.
35721   */
35722   PGroup *pGroup;                     /* PGroup this cache belongs to */
35723   int szPage;                         /* Size of allocated pages in bytes */
35724   int szExtra;                        /* Size of extra space in bytes */
35725   int bPurgeable;                     /* True if cache is purgeable */
35726   unsigned int nMin;                  /* Minimum number of pages reserved */
35727   unsigned int nMax;                  /* Configured "cache_size" value */
35728   unsigned int n90pct;                /* nMax*9/10 */
35729   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35730
35731   /* Hash table of all pages. The following variables may only be accessed
35732   ** when the accessor is holding the PGroup mutex.
35733   */
35734   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35735   unsigned int nPage;                 /* Total number of pages in apHash */
35736   unsigned int nHash;                 /* Number of slots in apHash[] */
35737   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35738 };
35739
35740 /*
35741 ** Each cache entry is represented by an instance of the following 
35742 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
35743 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
35744 ** in memory.
35745 */
35746 struct PgHdr1 {
35747   sqlite3_pcache_page page;
35748   unsigned int iKey;             /* Key value (page number) */
35749   PgHdr1 *pNext;                 /* Next in hash table chain */
35750   PCache1 *pCache;               /* Cache that currently owns this page */
35751   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35752   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35753 };
35754
35755 /*
35756 ** Free slots in the allocator used to divide up the buffer provided using
35757 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35758 */
35759 struct PgFreeslot {
35760   PgFreeslot *pNext;  /* Next free slot */
35761 };
35762
35763 /*
35764 ** Global data used by this cache.
35765 */
35766 static SQLITE_WSD struct PCacheGlobal {
35767   PGroup grp;                    /* The global PGroup for mode (2) */
35768
35769   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35770   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35771   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35772   ** The nFreeSlot and pFree values do require mutex protection.
35773   */
35774   int isInit;                    /* True if initialized */
35775   int szSlot;                    /* Size of each free slot */
35776   int nSlot;                     /* The number of pcache slots */
35777   int nReserve;                  /* Try to keep nFreeSlot above this */
35778   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35779   /* Above requires no mutex.  Use mutex below for variable that follow. */
35780   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35781   PgFreeslot *pFree;             /* Free page blocks */
35782   int nFreeSlot;                 /* Number of unused pcache slots */
35783   /* The following value requires a mutex to change.  We skip the mutex on
35784   ** reading because (1) most platforms read a 32-bit integer atomically and
35785   ** (2) even if an incorrect value is read, no great harm is done since this
35786   ** is really just an optimization. */
35787   int bUnderPressure;            /* True if low on PAGECACHE memory */
35788 } pcache1_g;
35789
35790 /*
35791 ** All code in this file should access the global structure above via the
35792 ** alias "pcache1". This ensures that the WSD emulation is used when
35793 ** compiling for systems that do not support real WSD.
35794 */
35795 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35796
35797 /*
35798 ** Macros to enter and leave the PCache LRU mutex.
35799 */
35800 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35801 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35802
35803 /******************************************************************************/
35804 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35805
35806 /*
35807 ** This function is called during initialization if a static buffer is 
35808 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35809 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35810 ** enough to contain 'n' buffers of 'sz' bytes each.
35811 **
35812 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35813 ** to be serialized already.  There is no need for further mutexing.
35814 */
35815 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35816   if( pcache1.isInit ){
35817     PgFreeslot *p;
35818     sz = ROUNDDOWN8(sz);
35819     pcache1.szSlot = sz;
35820     pcache1.nSlot = pcache1.nFreeSlot = n;
35821     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35822     pcache1.pStart = pBuf;
35823     pcache1.pFree = 0;
35824     pcache1.bUnderPressure = 0;
35825     while( n-- ){
35826       p = (PgFreeslot*)pBuf;
35827       p->pNext = pcache1.pFree;
35828       pcache1.pFree = p;
35829       pBuf = (void*)&((char*)pBuf)[sz];
35830     }
35831     pcache1.pEnd = pBuf;
35832   }
35833 }
35834
35835 /*
35836 ** Malloc function used within this file to allocate space from the buffer
35837 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35838 ** such buffer exists or there is no space left in it, this function falls 
35839 ** back to sqlite3Malloc().
35840 **
35841 ** Multiple threads can run this routine at the same time.  Global variables
35842 ** in pcache1 need to be protected via mutex.
35843 */
35844 static void *pcache1Alloc(int nByte){
35845   void *p = 0;
35846   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35847   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35848   if( nByte<=pcache1.szSlot ){
35849     sqlite3_mutex_enter(pcache1.mutex);
35850     p = (PgHdr1 *)pcache1.pFree;
35851     if( p ){
35852       pcache1.pFree = pcache1.pFree->pNext;
35853       pcache1.nFreeSlot--;
35854       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35855       assert( pcache1.nFreeSlot>=0 );
35856       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35857     }
35858     sqlite3_mutex_leave(pcache1.mutex);
35859   }
35860   if( p==0 ){
35861     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35862     ** it from sqlite3Malloc instead.
35863     */
35864     p = sqlite3Malloc(nByte);
35865 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35866     if( p ){
35867       int sz = sqlite3MallocSize(p);
35868       sqlite3_mutex_enter(pcache1.mutex);
35869       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35870       sqlite3_mutex_leave(pcache1.mutex);
35871     }
35872 #endif
35873     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35874   }
35875   return p;
35876 }
35877
35878 /*
35879 ** Free an allocated buffer obtained from pcache1Alloc().
35880 */
35881 static int pcache1Free(void *p){
35882   int nFreed = 0;
35883   if( p==0 ) return 0;
35884   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35885     PgFreeslot *pSlot;
35886     sqlite3_mutex_enter(pcache1.mutex);
35887     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35888     pSlot = (PgFreeslot*)p;
35889     pSlot->pNext = pcache1.pFree;
35890     pcache1.pFree = pSlot;
35891     pcache1.nFreeSlot++;
35892     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35893     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35894     sqlite3_mutex_leave(pcache1.mutex);
35895   }else{
35896     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35897     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35898     nFreed = sqlite3MallocSize(p);
35899 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35900     sqlite3_mutex_enter(pcache1.mutex);
35901     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
35902     sqlite3_mutex_leave(pcache1.mutex);
35903 #endif
35904     sqlite3_free(p);
35905   }
35906   return nFreed;
35907 }
35908
35909 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35910 /*
35911 ** Return the size of a pcache allocation
35912 */
35913 static int pcache1MemSize(void *p){
35914   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35915     return pcache1.szSlot;
35916   }else{
35917     int iSize;
35918     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35919     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35920     iSize = sqlite3MallocSize(p);
35921     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35922     return iSize;
35923   }
35924 }
35925 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35926
35927 /*
35928 ** Allocate a new page object initially associated with cache pCache.
35929 */
35930 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35931   PgHdr1 *p = 0;
35932   void *pPg;
35933
35934   /* The group mutex must be released before pcache1Alloc() is called. This
35935   ** is because it may call sqlite3_release_memory(), which assumes that 
35936   ** this mutex is not held. */
35937   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35938   pcache1LeaveMutex(pCache->pGroup);
35939 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
35940   pPg = pcache1Alloc(pCache->szPage);
35941   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
35942   if( !pPg || !p ){
35943     pcache1Free(pPg);
35944     sqlite3_free(p);
35945     pPg = 0;
35946   }
35947 #else
35948   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
35949   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
35950 #endif
35951   pcache1EnterMutex(pCache->pGroup);
35952
35953   if( pPg ){
35954     p->page.pBuf = pPg;
35955     p->page.pExtra = &p[1];
35956     if( pCache->bPurgeable ){
35957       pCache->pGroup->nCurrentPage++;
35958     }
35959     return p;
35960   }
35961   return 0;
35962 }
35963
35964 /*
35965 ** Free a page object allocated by pcache1AllocPage().
35966 **
35967 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
35968 ** that the current implementation happens to never call this routine
35969 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35970 */
35971 static void pcache1FreePage(PgHdr1 *p){
35972   if( ALWAYS(p) ){
35973     PCache1 *pCache = p->pCache;
35974     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
35975     pcache1Free(p->page.pBuf);
35976 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
35977     sqlite3_free(p);
35978 #endif
35979     if( pCache->bPurgeable ){
35980       pCache->pGroup->nCurrentPage--;
35981     }
35982   }
35983 }
35984
35985 /*
35986 ** Malloc function used by SQLite to obtain space from the buffer configured
35987 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35988 ** exists, this function falls back to sqlite3Malloc().
35989 */
35990 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35991   return pcache1Alloc(sz);
35992 }
35993
35994 /*
35995 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35996 */
35997 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35998   pcache1Free(p);
35999 }
36000
36001
36002 /*
36003 ** Return true if it desirable to avoid allocating a new page cache
36004 ** entry.
36005 **
36006 ** If memory was allocated specifically to the page cache using
36007 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
36008 ** it is desirable to avoid allocating a new page cache entry because
36009 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
36010 ** for all page cache needs and we should not need to spill the
36011 ** allocation onto the heap.
36012 **
36013 ** Or, the heap is used for all page cache memory but the heap is
36014 ** under memory pressure, then again it is desirable to avoid
36015 ** allocating a new page cache entry in order to avoid stressing
36016 ** the heap even further.
36017 */
36018 static int pcache1UnderMemoryPressure(PCache1 *pCache){
36019   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
36020     return pcache1.bUnderPressure;
36021   }else{
36022     return sqlite3HeapNearlyFull();
36023   }
36024 }
36025
36026 /******************************************************************************/
36027 /******** General Implementation Functions ************************************/
36028
36029 /*
36030 ** This function is used to resize the hash table used by the cache passed
36031 ** as the first argument.
36032 **
36033 ** The PCache mutex must be held when this function is called.
36034 */
36035 static int pcache1ResizeHash(PCache1 *p){
36036   PgHdr1 **apNew;
36037   unsigned int nNew;
36038   unsigned int i;
36039
36040   assert( sqlite3_mutex_held(p->pGroup->mutex) );
36041
36042   nNew = p->nHash*2;
36043   if( nNew<256 ){
36044     nNew = 256;
36045   }
36046
36047   pcache1LeaveMutex(p->pGroup);
36048   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
36049   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
36050   if( p->nHash ){ sqlite3EndBenignMalloc(); }
36051   pcache1EnterMutex(p->pGroup);
36052   if( apNew ){
36053     for(i=0; i<p->nHash; i++){
36054       PgHdr1 *pPage;
36055       PgHdr1 *pNext = p->apHash[i];
36056       while( (pPage = pNext)!=0 ){
36057         unsigned int h = pPage->iKey % nNew;
36058         pNext = pPage->pNext;
36059         pPage->pNext = apNew[h];
36060         apNew[h] = pPage;
36061       }
36062     }
36063     sqlite3_free(p->apHash);
36064     p->apHash = apNew;
36065     p->nHash = nNew;
36066   }
36067
36068   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
36069 }
36070
36071 /*
36072 ** This function is used internally to remove the page pPage from the 
36073 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
36074 ** LRU list, then this function is a no-op.
36075 **
36076 ** The PGroup mutex must be held when this function is called.
36077 **
36078 ** If pPage is NULL then this routine is a no-op.
36079 */
36080 static void pcache1PinPage(PgHdr1 *pPage){
36081   PCache1 *pCache;
36082   PGroup *pGroup;
36083
36084   if( pPage==0 ) return;
36085   pCache = pPage->pCache;
36086   pGroup = pCache->pGroup;
36087   assert( sqlite3_mutex_held(pGroup->mutex) );
36088   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
36089     if( pPage->pLruPrev ){
36090       pPage->pLruPrev->pLruNext = pPage->pLruNext;
36091     }
36092     if( pPage->pLruNext ){
36093       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
36094     }
36095     if( pGroup->pLruHead==pPage ){
36096       pGroup->pLruHead = pPage->pLruNext;
36097     }
36098     if( pGroup->pLruTail==pPage ){
36099       pGroup->pLruTail = pPage->pLruPrev;
36100     }
36101     pPage->pLruNext = 0;
36102     pPage->pLruPrev = 0;
36103     pPage->pCache->nRecyclable--;
36104   }
36105 }
36106
36107
36108 /*
36109 ** Remove the page supplied as an argument from the hash table 
36110 ** (PCache1.apHash structure) that it is currently stored in.
36111 **
36112 ** The PGroup mutex must be held when this function is called.
36113 */
36114 static void pcache1RemoveFromHash(PgHdr1 *pPage){
36115   unsigned int h;
36116   PCache1 *pCache = pPage->pCache;
36117   PgHdr1 **pp;
36118
36119   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36120   h = pPage->iKey % pCache->nHash;
36121   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
36122   *pp = (*pp)->pNext;
36123
36124   pCache->nPage--;
36125 }
36126
36127 /*
36128 ** If there are currently more than nMaxPage pages allocated, try
36129 ** to recycle pages to reduce the number allocated to nMaxPage.
36130 */
36131 static void pcache1EnforceMaxPage(PGroup *pGroup){
36132   assert( sqlite3_mutex_held(pGroup->mutex) );
36133   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
36134     PgHdr1 *p = pGroup->pLruTail;
36135     assert( p->pCache->pGroup==pGroup );
36136     pcache1PinPage(p);
36137     pcache1RemoveFromHash(p);
36138     pcache1FreePage(p);
36139   }
36140 }
36141
36142 /*
36143 ** Discard all pages from cache pCache with a page number (key value) 
36144 ** greater than or equal to iLimit. Any pinned pages that meet this 
36145 ** criteria are unpinned before they are discarded.
36146 **
36147 ** The PCache mutex must be held when this function is called.
36148 */
36149 static void pcache1TruncateUnsafe(
36150   PCache1 *pCache,             /* The cache to truncate */
36151   unsigned int iLimit          /* Drop pages with this pgno or larger */
36152 ){
36153   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
36154   unsigned int h;
36155   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36156   for(h=0; h<pCache->nHash; h++){
36157     PgHdr1 **pp = &pCache->apHash[h]; 
36158     PgHdr1 *pPage;
36159     while( (pPage = *pp)!=0 ){
36160       if( pPage->iKey>=iLimit ){
36161         pCache->nPage--;
36162         *pp = pPage->pNext;
36163         pcache1PinPage(pPage);
36164         pcache1FreePage(pPage);
36165       }else{
36166         pp = &pPage->pNext;
36167         TESTONLY( nPage++; )
36168       }
36169     }
36170   }
36171   assert( pCache->nPage==nPage );
36172 }
36173
36174 /******************************************************************************/
36175 /******** sqlite3_pcache Methods **********************************************/
36176
36177 /*
36178 ** Implementation of the sqlite3_pcache.xInit method.
36179 */
36180 static int pcache1Init(void *NotUsed){
36181   UNUSED_PARAMETER(NotUsed);
36182   assert( pcache1.isInit==0 );
36183   memset(&pcache1, 0, sizeof(pcache1));
36184   if( sqlite3GlobalConfig.bCoreMutex ){
36185     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
36186     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
36187   }
36188   pcache1.grp.mxPinned = 10;
36189   pcache1.isInit = 1;
36190   return SQLITE_OK;
36191 }
36192
36193 /*
36194 ** Implementation of the sqlite3_pcache.xShutdown method.
36195 ** Note that the static mutex allocated in xInit does 
36196 ** not need to be freed.
36197 */
36198 static void pcache1Shutdown(void *NotUsed){
36199   UNUSED_PARAMETER(NotUsed);
36200   assert( pcache1.isInit!=0 );
36201   memset(&pcache1, 0, sizeof(pcache1));
36202 }
36203
36204 /*
36205 ** Implementation of the sqlite3_pcache.xCreate method.
36206 **
36207 ** Allocate a new cache.
36208 */
36209 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
36210   PCache1 *pCache;      /* The newly created page cache */
36211   PGroup *pGroup;       /* The group the new page cache will belong to */
36212   int sz;               /* Bytes of memory required to allocate the new cache */
36213
36214   /*
36215   ** The seperateCache variable is true if each PCache has its own private
36216   ** PGroup.  In other words, separateCache is true for mode (1) where no
36217   ** mutexing is required.
36218   **
36219   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
36220   **
36221   **   *  Always use a unified cache in single-threaded applications
36222   **
36223   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
36224   **      use separate caches (mode-1)
36225   */
36226 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
36227   const int separateCache = 0;
36228 #else
36229   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
36230 #endif
36231
36232   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
36233   assert( szExtra < 300 );
36234
36235   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
36236   pCache = (PCache1 *)sqlite3MallocZero(sz);
36237   if( pCache ){
36238     if( separateCache ){
36239       pGroup = (PGroup*)&pCache[1];
36240       pGroup->mxPinned = 10;
36241     }else{
36242       pGroup = &pcache1.grp;
36243     }
36244     pCache->pGroup = pGroup;
36245     pCache->szPage = szPage;
36246     pCache->szExtra = szExtra;
36247     pCache->bPurgeable = (bPurgeable ? 1 : 0);
36248     if( bPurgeable ){
36249       pCache->nMin = 10;
36250       pcache1EnterMutex(pGroup);
36251       pGroup->nMinPage += pCache->nMin;
36252       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36253       pcache1LeaveMutex(pGroup);
36254     }
36255   }
36256   return (sqlite3_pcache *)pCache;
36257 }
36258
36259 /*
36260 ** Implementation of the sqlite3_pcache.xCachesize method. 
36261 **
36262 ** Configure the cache_size limit for a cache.
36263 */
36264 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
36265   PCache1 *pCache = (PCache1 *)p;
36266   if( pCache->bPurgeable ){
36267     PGroup *pGroup = pCache->pGroup;
36268     pcache1EnterMutex(pGroup);
36269     pGroup->nMaxPage += (nMax - pCache->nMax);
36270     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36271     pCache->nMax = nMax;
36272     pCache->n90pct = pCache->nMax*9/10;
36273     pcache1EnforceMaxPage(pGroup);
36274     pcache1LeaveMutex(pGroup);
36275   }
36276 }
36277
36278 /*
36279 ** Implementation of the sqlite3_pcache.xShrink method. 
36280 **
36281 ** Free up as much memory as possible.
36282 */
36283 static void pcache1Shrink(sqlite3_pcache *p){
36284   PCache1 *pCache = (PCache1*)p;
36285   if( pCache->bPurgeable ){
36286     PGroup *pGroup = pCache->pGroup;
36287     int savedMaxPage;
36288     pcache1EnterMutex(pGroup);
36289     savedMaxPage = pGroup->nMaxPage;
36290     pGroup->nMaxPage = 0;
36291     pcache1EnforceMaxPage(pGroup);
36292     pGroup->nMaxPage = savedMaxPage;
36293     pcache1LeaveMutex(pGroup);
36294   }
36295 }
36296
36297 /*
36298 ** Implementation of the sqlite3_pcache.xPagecount method. 
36299 */
36300 static int pcache1Pagecount(sqlite3_pcache *p){
36301   int n;
36302   PCache1 *pCache = (PCache1*)p;
36303   pcache1EnterMutex(pCache->pGroup);
36304   n = pCache->nPage;
36305   pcache1LeaveMutex(pCache->pGroup);
36306   return n;
36307 }
36308
36309 /*
36310 ** Implementation of the sqlite3_pcache.xFetch method. 
36311 **
36312 ** Fetch a page by key value.
36313 **
36314 ** Whether or not a new page may be allocated by this function depends on
36315 ** the value of the createFlag argument.  0 means do not allocate a new
36316 ** page.  1 means allocate a new page if space is easily available.  2 
36317 ** means to try really hard to allocate a new page.
36318 **
36319 ** For a non-purgeable cache (a cache used as the storage for an in-memory
36320 ** database) there is really no difference between createFlag 1 and 2.  So
36321 ** the calling function (pcache.c) will never have a createFlag of 1 on
36322 ** a non-purgeable cache.
36323 **
36324 ** There are three different approaches to obtaining space for a page,
36325 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
36326 **
36327 **   1. Regardless of the value of createFlag, the cache is searched for a 
36328 **      copy of the requested page. If one is found, it is returned.
36329 **
36330 **   2. If createFlag==0 and the page is not already in the cache, NULL is
36331 **      returned.
36332 **
36333 **   3. If createFlag is 1, and the page is not already in the cache, then
36334 **      return NULL (do not allocate a new page) if any of the following
36335 **      conditions are true:
36336 **
36337 **       (a) the number of pages pinned by the cache is greater than
36338 **           PCache1.nMax, or
36339 **
36340 **       (b) the number of pages pinned by the cache is greater than
36341 **           the sum of nMax for all purgeable caches, less the sum of 
36342 **           nMin for all other purgeable caches, or
36343 **
36344 **   4. If none of the first three conditions apply and the cache is marked
36345 **      as purgeable, and if one of the following is true:
36346 **
36347 **       (a) The number of pages allocated for the cache is already 
36348 **           PCache1.nMax, or
36349 **
36350 **       (b) The number of pages allocated for all purgeable caches is
36351 **           already equal to or greater than the sum of nMax for all
36352 **           purgeable caches,
36353 **
36354 **       (c) The system is under memory pressure and wants to avoid
36355 **           unnecessary pages cache entry allocations
36356 **
36357 **      then attempt to recycle a page from the LRU list. If it is the right
36358 **      size, return the recycled buffer. Otherwise, free the buffer and
36359 **      proceed to step 5. 
36360 **
36361 **   5. Otherwise, allocate and return a new page buffer.
36362 */
36363 static sqlite3_pcache_page *pcache1Fetch(
36364   sqlite3_pcache *p, 
36365   unsigned int iKey, 
36366   int createFlag
36367 ){
36368   unsigned int nPinned;
36369   PCache1 *pCache = (PCache1 *)p;
36370   PGroup *pGroup;
36371   PgHdr1 *pPage = 0;
36372
36373   assert( pCache->bPurgeable || createFlag!=1 );
36374   assert( pCache->bPurgeable || pCache->nMin==0 );
36375   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36376   assert( pCache->nMin==0 || pCache->bPurgeable );
36377   pcache1EnterMutex(pGroup = pCache->pGroup);
36378
36379   /* Step 1: Search the hash table for an existing entry. */
36380   if( pCache->nHash>0 ){
36381     unsigned int h = iKey % pCache->nHash;
36382     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36383   }
36384
36385   /* Step 2: Abort if no existing page is found and createFlag is 0 */
36386   if( pPage || createFlag==0 ){
36387     pcache1PinPage(pPage);
36388     goto fetch_out;
36389   }
36390
36391   /* The pGroup local variable will normally be initialized by the
36392   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
36393   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36394   ** local variable here.  Delaying the initialization of pGroup is an
36395   ** optimization:  The common case is to exit the module before reaching
36396   ** this point.
36397   */
36398 #ifdef SQLITE_MUTEX_OMIT
36399   pGroup = pCache->pGroup;
36400 #endif
36401
36402   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36403   assert( pCache->nPage >= pCache->nRecyclable );
36404   nPinned = pCache->nPage - pCache->nRecyclable;
36405   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36406   assert( pCache->n90pct == pCache->nMax*9/10 );
36407   if( createFlag==1 && (
36408         nPinned>=pGroup->mxPinned
36409      || nPinned>=pCache->n90pct
36410      || pcache1UnderMemoryPressure(pCache)
36411   )){
36412     goto fetch_out;
36413   }
36414
36415   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36416     goto fetch_out;
36417   }
36418
36419   /* Step 4. Try to recycle a page. */
36420   if( pCache->bPurgeable && pGroup->pLruTail && (
36421          (pCache->nPage+1>=pCache->nMax)
36422       || pGroup->nCurrentPage>=pGroup->nMaxPage
36423       || pcache1UnderMemoryPressure(pCache)
36424   )){
36425     PCache1 *pOther;
36426     pPage = pGroup->pLruTail;
36427     pcache1RemoveFromHash(pPage);
36428     pcache1PinPage(pPage);
36429     pOther = pPage->pCache;
36430
36431     /* We want to verify that szPage and szExtra are the same for pOther
36432     ** and pCache.  Assert that we can verify this by comparing sums. */
36433     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
36434     assert( pCache->szExtra<512 );
36435     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
36436     assert( pOther->szExtra<512 );
36437
36438     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
36439       pcache1FreePage(pPage);
36440       pPage = 0;
36441     }else{
36442       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
36443     }
36444   }
36445
36446   /* Step 5. If a usable page buffer has still not been found, 
36447   ** attempt to allocate a new one. 
36448   */
36449   if( !pPage ){
36450     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36451     pPage = pcache1AllocPage(pCache);
36452     if( createFlag==1 ) sqlite3EndBenignMalloc();
36453   }
36454
36455   if( pPage ){
36456     unsigned int h = iKey % pCache->nHash;
36457     pCache->nPage++;
36458     pPage->iKey = iKey;
36459     pPage->pNext = pCache->apHash[h];
36460     pPage->pCache = pCache;
36461     pPage->pLruPrev = 0;
36462     pPage->pLruNext = 0;
36463     *(void **)pPage->page.pExtra = 0;
36464     pCache->apHash[h] = pPage;
36465   }
36466
36467 fetch_out:
36468   if( pPage && iKey>pCache->iMaxKey ){
36469     pCache->iMaxKey = iKey;
36470   }
36471   pcache1LeaveMutex(pGroup);
36472   return &pPage->page;
36473 }
36474
36475
36476 /*
36477 ** Implementation of the sqlite3_pcache.xUnpin method.
36478 **
36479 ** Mark a page as unpinned (eligible for asynchronous recycling).
36480 */
36481 static void pcache1Unpin(
36482   sqlite3_pcache *p, 
36483   sqlite3_pcache_page *pPg, 
36484   int reuseUnlikely
36485 ){
36486   PCache1 *pCache = (PCache1 *)p;
36487   PgHdr1 *pPage = (PgHdr1 *)pPg;
36488   PGroup *pGroup = pCache->pGroup;
36489  
36490   assert( pPage->pCache==pCache );
36491   pcache1EnterMutex(pGroup);
36492
36493   /* It is an error to call this function if the page is already 
36494   ** part of the PGroup LRU list.
36495   */
36496   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36497   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36498
36499   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36500     pcache1RemoveFromHash(pPage);
36501     pcache1FreePage(pPage);
36502   }else{
36503     /* Add the page to the PGroup LRU list. */
36504     if( pGroup->pLruHead ){
36505       pGroup->pLruHead->pLruPrev = pPage;
36506       pPage->pLruNext = pGroup->pLruHead;
36507       pGroup->pLruHead = pPage;
36508     }else{
36509       pGroup->pLruTail = pPage;
36510       pGroup->pLruHead = pPage;
36511     }
36512     pCache->nRecyclable++;
36513   }
36514
36515   pcache1LeaveMutex(pCache->pGroup);
36516 }
36517
36518 /*
36519 ** Implementation of the sqlite3_pcache.xRekey method. 
36520 */
36521 static void pcache1Rekey(
36522   sqlite3_pcache *p,
36523   sqlite3_pcache_page *pPg,
36524   unsigned int iOld,
36525   unsigned int iNew
36526 ){
36527   PCache1 *pCache = (PCache1 *)p;
36528   PgHdr1 *pPage = (PgHdr1 *)pPg;
36529   PgHdr1 **pp;
36530   unsigned int h; 
36531   assert( pPage->iKey==iOld );
36532   assert( pPage->pCache==pCache );
36533
36534   pcache1EnterMutex(pCache->pGroup);
36535
36536   h = iOld%pCache->nHash;
36537   pp = &pCache->apHash[h];
36538   while( (*pp)!=pPage ){
36539     pp = &(*pp)->pNext;
36540   }
36541   *pp = pPage->pNext;
36542
36543   h = iNew%pCache->nHash;
36544   pPage->iKey = iNew;
36545   pPage->pNext = pCache->apHash[h];
36546   pCache->apHash[h] = pPage;
36547   if( iNew>pCache->iMaxKey ){
36548     pCache->iMaxKey = iNew;
36549   }
36550
36551   pcache1LeaveMutex(pCache->pGroup);
36552 }
36553
36554 /*
36555 ** Implementation of the sqlite3_pcache.xTruncate method. 
36556 **
36557 ** Discard all unpinned pages in the cache with a page number equal to
36558 ** or greater than parameter iLimit. Any pinned pages with a page number
36559 ** equal to or greater than iLimit are implicitly unpinned.
36560 */
36561 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36562   PCache1 *pCache = (PCache1 *)p;
36563   pcache1EnterMutex(pCache->pGroup);
36564   if( iLimit<=pCache->iMaxKey ){
36565     pcache1TruncateUnsafe(pCache, iLimit);
36566     pCache->iMaxKey = iLimit-1;
36567   }
36568   pcache1LeaveMutex(pCache->pGroup);
36569 }
36570
36571 /*
36572 ** Implementation of the sqlite3_pcache.xDestroy method. 
36573 **
36574 ** Destroy a cache allocated using pcache1Create().
36575 */
36576 static void pcache1Destroy(sqlite3_pcache *p){
36577   PCache1 *pCache = (PCache1 *)p;
36578   PGroup *pGroup = pCache->pGroup;
36579   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36580   pcache1EnterMutex(pGroup);
36581   pcache1TruncateUnsafe(pCache, 0);
36582   assert( pGroup->nMaxPage >= pCache->nMax );
36583   pGroup->nMaxPage -= pCache->nMax;
36584   assert( pGroup->nMinPage >= pCache->nMin );
36585   pGroup->nMinPage -= pCache->nMin;
36586   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36587   pcache1EnforceMaxPage(pGroup);
36588   pcache1LeaveMutex(pGroup);
36589   sqlite3_free(pCache->apHash);
36590   sqlite3_free(pCache);
36591 }
36592
36593 /*
36594 ** This function is called during initialization (sqlite3_initialize()) to
36595 ** install the default pluggable cache module, assuming the user has not
36596 ** already provided an alternative.
36597 */
36598 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36599   static const sqlite3_pcache_methods2 defaultMethods = {
36600     1,                       /* iVersion */
36601     0,                       /* pArg */
36602     pcache1Init,             /* xInit */
36603     pcache1Shutdown,         /* xShutdown */
36604     pcache1Create,           /* xCreate */
36605     pcache1Cachesize,        /* xCachesize */
36606     pcache1Pagecount,        /* xPagecount */
36607     pcache1Fetch,            /* xFetch */
36608     pcache1Unpin,            /* xUnpin */
36609     pcache1Rekey,            /* xRekey */
36610     pcache1Truncate,         /* xTruncate */
36611     pcache1Destroy,          /* xDestroy */
36612     pcache1Shrink            /* xShrink */
36613   };
36614   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
36615 }
36616
36617 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36618 /*
36619 ** This function is called to free superfluous dynamically allocated memory
36620 ** held by the pager system. Memory in use by any SQLite pager allocated
36621 ** by the current thread may be sqlite3_free()ed.
36622 **
36623 ** nReq is the number of bytes of memory required. Once this much has
36624 ** been released, the function returns. The return value is the total number 
36625 ** of bytes of memory released.
36626 */
36627 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36628   int nFree = 0;
36629   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36630   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36631   if( pcache1.pStart==0 ){
36632     PgHdr1 *p;
36633     pcache1EnterMutex(&pcache1.grp);
36634     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36635       nFree += pcache1MemSize(p->page.pBuf);
36636 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36637       nFree += sqlite3MemSize(p);
36638 #endif
36639       pcache1PinPage(p);
36640       pcache1RemoveFromHash(p);
36641       pcache1FreePage(p);
36642     }
36643     pcache1LeaveMutex(&pcache1.grp);
36644   }
36645   return nFree;
36646 }
36647 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36648
36649 #ifdef SQLITE_TEST
36650 /*
36651 ** This function is used by test procedures to inspect the internal state
36652 ** of the global cache.
36653 */
36654 SQLITE_PRIVATE void sqlite3PcacheStats(
36655   int *pnCurrent,      /* OUT: Total number of pages cached */
36656   int *pnMax,          /* OUT: Global maximum cache size */
36657   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36658   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36659 ){
36660   PgHdr1 *p;
36661   int nRecyclable = 0;
36662   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36663     nRecyclable++;
36664   }
36665   *pnCurrent = pcache1.grp.nCurrentPage;
36666   *pnMax = (int)pcache1.grp.nMaxPage;
36667   *pnMin = (int)pcache1.grp.nMinPage;
36668   *pnRecyclable = nRecyclable;
36669 }
36670 #endif
36671
36672 /************** End of pcache1.c *********************************************/
36673 /************** Begin file rowset.c ******************************************/
36674 /*
36675 ** 2008 December 3
36676 **
36677 ** The author disclaims copyright to this source code.  In place of
36678 ** a legal notice, here is a blessing:
36679 **
36680 **    May you do good and not evil.
36681 **    May you find forgiveness for yourself and forgive others.
36682 **    May you share freely, never taking more than you give.
36683 **
36684 *************************************************************************
36685 **
36686 ** This module implements an object we call a "RowSet".
36687 **
36688 ** The RowSet object is a collection of rowids.  Rowids
36689 ** are inserted into the RowSet in an arbitrary order.  Inserts
36690 ** can be intermixed with tests to see if a given rowid has been
36691 ** previously inserted into the RowSet.
36692 **
36693 ** After all inserts are finished, it is possible to extract the
36694 ** elements of the RowSet in sorted order.  Once this extraction
36695 ** process has started, no new elements may be inserted.
36696 **
36697 ** Hence, the primitive operations for a RowSet are:
36698 **
36699 **    CREATE
36700 **    INSERT
36701 **    TEST
36702 **    SMALLEST
36703 **    DESTROY
36704 **
36705 ** The CREATE and DESTROY primitives are the constructor and destructor,
36706 ** obviously.  The INSERT primitive adds a new element to the RowSet.
36707 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
36708 ** extracts the least value from the RowSet.
36709 **
36710 ** The INSERT primitive might allocate additional memory.  Memory is
36711 ** allocated in chunks so most INSERTs do no allocation.  There is an 
36712 ** upper bound on the size of allocated memory.  No memory is freed
36713 ** until DESTROY.
36714 **
36715 ** The TEST primitive includes a "batch" number.  The TEST primitive
36716 ** will only see elements that were inserted before the last change
36717 ** in the batch number.  In other words, if an INSERT occurs between
36718 ** two TESTs where the TESTs have the same batch nubmer, then the
36719 ** value added by the INSERT will not be visible to the second TEST.
36720 ** The initial batch number is zero, so if the very first TEST contains
36721 ** a non-zero batch number, it will see all prior INSERTs.
36722 **
36723 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
36724 ** that is attempted.
36725 **
36726 ** The cost of an INSERT is roughly constant.  (Sometime new memory
36727 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
36728 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36729 ** The cost of a TEST using the same batch number is O(logN).  The cost
36730 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
36731 ** primitives are constant time.  The cost of DESTROY is O(N).
36732 **
36733 ** There is an added cost of O(N) when switching between TEST and
36734 ** SMALLEST primitives.
36735 */
36736
36737
36738 /*
36739 ** Target size for allocation chunks.
36740 */
36741 #define ROWSET_ALLOCATION_SIZE 1024
36742
36743 /*
36744 ** The number of rowset entries per allocation chunk.
36745 */
36746 #define ROWSET_ENTRY_PER_CHUNK  \
36747                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36748
36749 /*
36750 ** Each entry in a RowSet is an instance of the following object.
36751 **
36752 ** This same object is reused to store a linked list of trees of RowSetEntry
36753 ** objects.  In that alternative use, pRight points to the next entry
36754 ** in the list, pLeft points to the tree, and v is unused.  The
36755 ** RowSet.pForest value points to the head of this forest list.
36756 */
36757 struct RowSetEntry {            
36758   i64 v;                        /* ROWID value for this entry */
36759   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
36760   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
36761 };
36762
36763 /*
36764 ** RowSetEntry objects are allocated in large chunks (instances of the
36765 ** following structure) to reduce memory allocation overhead.  The
36766 ** chunks are kept on a linked list so that they can be deallocated
36767 ** when the RowSet is destroyed.
36768 */
36769 struct RowSetChunk {
36770   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
36771   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36772 };
36773
36774 /*
36775 ** A RowSet in an instance of the following structure.
36776 **
36777 ** A typedef of this structure if found in sqliteInt.h.
36778 */
36779 struct RowSet {
36780   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
36781   sqlite3 *db;                   /* The database connection */
36782   struct RowSetEntry *pEntry;    /* List of entries using pRight */
36783   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
36784   struct RowSetEntry *pFresh;    /* Source of new entry objects */
36785   struct RowSetEntry *pForest;   /* List of binary trees of entries */
36786   u16 nFresh;                    /* Number of objects on pFresh */
36787   u8 rsFlags;                    /* Various flags */
36788   u8 iBatch;                     /* Current insert batch */
36789 };
36790
36791 /*
36792 ** Allowed values for RowSet.rsFlags
36793 */
36794 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
36795 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
36796
36797 /*
36798 ** Turn bulk memory into a RowSet object.  N bytes of memory
36799 ** are available at pSpace.  The db pointer is used as a memory context
36800 ** for any subsequent allocations that need to occur.
36801 ** Return a pointer to the new RowSet object.
36802 **
36803 ** It must be the case that N is sufficient to make a Rowset.  If not
36804 ** an assertion fault occurs.
36805 ** 
36806 ** If N is larger than the minimum, use the surplus as an initial
36807 ** allocation of entries available to be filled.
36808 */
36809 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36810   RowSet *p;
36811   assert( N >= ROUND8(sizeof(*p)) );
36812   p = pSpace;
36813   p->pChunk = 0;
36814   p->db = db;
36815   p->pEntry = 0;
36816   p->pLast = 0;
36817   p->pForest = 0;
36818   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36819   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36820   p->rsFlags = ROWSET_SORTED;
36821   p->iBatch = 0;
36822   return p;
36823 }
36824
36825 /*
36826 ** Deallocate all chunks from a RowSet.  This frees all memory that
36827 ** the RowSet has allocated over its lifetime.  This routine is
36828 ** the destructor for the RowSet.
36829 */
36830 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36831   struct RowSetChunk *pChunk, *pNextChunk;
36832   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36833     pNextChunk = pChunk->pNextChunk;
36834     sqlite3DbFree(p->db, pChunk);
36835   }
36836   p->pChunk = 0;
36837   p->nFresh = 0;
36838   p->pEntry = 0;
36839   p->pLast = 0;
36840   p->pForest = 0;
36841   p->rsFlags = ROWSET_SORTED;
36842 }
36843
36844 /*
36845 ** Allocate a new RowSetEntry object that is associated with the
36846 ** given RowSet.  Return a pointer to the new and completely uninitialized
36847 ** objected.
36848 **
36849 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
36850 ** routine returns NULL.
36851 */
36852 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
36853   assert( p!=0 );
36854   if( p->nFresh==0 ){
36855     struct RowSetChunk *pNew;
36856     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36857     if( pNew==0 ){
36858       return 0;
36859     }
36860     pNew->pNextChunk = p->pChunk;
36861     p->pChunk = pNew;
36862     p->pFresh = pNew->aEntry;
36863     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36864   }
36865   p->nFresh--;
36866   return p->pFresh++;
36867 }
36868
36869 /*
36870 ** Insert a new value into a RowSet.
36871 **
36872 ** The mallocFailed flag of the database connection is set if a
36873 ** memory allocation fails.
36874 */
36875 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36876   struct RowSetEntry *pEntry;  /* The new entry */
36877   struct RowSetEntry *pLast;   /* The last prior entry */
36878
36879   /* This routine is never called after sqlite3RowSetNext() */
36880   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
36881
36882   pEntry = rowSetEntryAlloc(p);
36883   if( pEntry==0 ) return;
36884   pEntry->v = rowid;
36885   pEntry->pRight = 0;
36886   pLast = p->pLast;
36887   if( pLast ){
36888     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
36889       p->rsFlags &= ~ROWSET_SORTED;
36890     }
36891     pLast->pRight = pEntry;
36892   }else{
36893     p->pEntry = pEntry;
36894   }
36895   p->pLast = pEntry;
36896 }
36897
36898 /*
36899 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
36900 **
36901 ** The input lists are connected via pRight pointers and are 
36902 ** assumed to each already be in sorted order.
36903 */
36904 static struct RowSetEntry *rowSetEntryMerge(
36905   struct RowSetEntry *pA,    /* First sorted list to be merged */
36906   struct RowSetEntry *pB     /* Second sorted list to be merged */
36907 ){
36908   struct RowSetEntry head;
36909   struct RowSetEntry *pTail;
36910
36911   pTail = &head;
36912   while( pA && pB ){
36913     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36914     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36915     if( pA->v<pB->v ){
36916       pTail->pRight = pA;
36917       pA = pA->pRight;
36918       pTail = pTail->pRight;
36919     }else if( pB->v<pA->v ){
36920       pTail->pRight = pB;
36921       pB = pB->pRight;
36922       pTail = pTail->pRight;
36923     }else{
36924       pA = pA->pRight;
36925     }
36926   }
36927   if( pA ){
36928     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36929     pTail->pRight = pA;
36930   }else{
36931     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36932     pTail->pRight = pB;
36933   }
36934   return head.pRight;
36935 }
36936
36937 /*
36938 ** Sort all elements on the list of RowSetEntry objects into order of
36939 ** increasing v.
36940 */ 
36941 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
36942   unsigned int i;
36943   struct RowSetEntry *pNext, *aBucket[40];
36944
36945   memset(aBucket, 0, sizeof(aBucket));
36946   while( pIn ){
36947     pNext = pIn->pRight;
36948     pIn->pRight = 0;
36949     for(i=0; aBucket[i]; i++){
36950       pIn = rowSetEntryMerge(aBucket[i], pIn);
36951       aBucket[i] = 0;
36952     }
36953     aBucket[i] = pIn;
36954     pIn = pNext;
36955   }
36956   pIn = 0;
36957   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36958     pIn = rowSetEntryMerge(pIn, aBucket[i]);
36959   }
36960   return pIn;
36961 }
36962
36963
36964 /*
36965 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36966 ** Convert this tree into a linked list connected by the pRight pointers
36967 ** and return pointers to the first and last elements of the new list.
36968 */
36969 static void rowSetTreeToList(
36970   struct RowSetEntry *pIn,         /* Root of the input tree */
36971   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36972   struct RowSetEntry **ppLast      /* Write tail of the output list here */
36973 ){
36974   assert( pIn!=0 );
36975   if( pIn->pLeft ){
36976     struct RowSetEntry *p;
36977     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36978     p->pRight = pIn;
36979   }else{
36980     *ppFirst = pIn;
36981   }
36982   if( pIn->pRight ){
36983     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36984   }else{
36985     *ppLast = pIn;
36986   }
36987   assert( (*ppLast)->pRight==0 );
36988 }
36989
36990
36991 /*
36992 ** Convert a sorted list of elements (connected by pRight) into a binary
36993 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36994 ** node taken from the head of *ppList.  A depth of 2 means a tree with
36995 ** three nodes.  And so forth.
36996 **
36997 ** Use as many entries from the input list as required and update the
36998 ** *ppList to point to the unused elements of the list.  If the input
36999 ** list contains too few elements, then construct an incomplete tree
37000 ** and leave *ppList set to NULL.
37001 **
37002 ** Return a pointer to the root of the constructed binary tree.
37003 */
37004 static struct RowSetEntry *rowSetNDeepTree(
37005   struct RowSetEntry **ppList,
37006   int iDepth
37007 ){
37008   struct RowSetEntry *p;         /* Root of the new tree */
37009   struct RowSetEntry *pLeft;     /* Left subtree */
37010   if( *ppList==0 ){
37011     return 0;
37012   }
37013   if( iDepth==1 ){
37014     p = *ppList;
37015     *ppList = p->pRight;
37016     p->pLeft = p->pRight = 0;
37017     return p;
37018   }
37019   pLeft = rowSetNDeepTree(ppList, iDepth-1);
37020   p = *ppList;
37021   if( p==0 ){
37022     return pLeft;
37023   }
37024   p->pLeft = pLeft;
37025   *ppList = p->pRight;
37026   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
37027   return p;
37028 }
37029
37030 /*
37031 ** Convert a sorted list of elements into a binary tree. Make the tree
37032 ** as deep as it needs to be in order to contain the entire list.
37033 */
37034 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
37035   int iDepth;           /* Depth of the tree so far */
37036   struct RowSetEntry *p;       /* Current tree root */
37037   struct RowSetEntry *pLeft;   /* Left subtree */
37038
37039   assert( pList!=0 );
37040   p = pList;
37041   pList = p->pRight;
37042   p->pLeft = p->pRight = 0;
37043   for(iDepth=1; pList; iDepth++){
37044     pLeft = p;
37045     p = pList;
37046     pList = p->pRight;
37047     p->pLeft = pLeft;
37048     p->pRight = rowSetNDeepTree(&pList, iDepth);
37049   }
37050   return p;
37051 }
37052
37053 /*
37054 ** Take all the entries on p->pEntry and on the trees in p->pForest and
37055 ** sort them all together into one big ordered list on p->pEntry.
37056 **
37057 ** This routine should only be called once in the life of a RowSet.
37058 */
37059 static void rowSetToList(RowSet *p){
37060
37061   /* This routine is called only once */
37062   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37063
37064   if( (p->rsFlags & ROWSET_SORTED)==0 ){
37065     p->pEntry = rowSetEntrySort(p->pEntry);
37066   }
37067
37068   /* While this module could theoretically support it, sqlite3RowSetNext()
37069   ** is never called after sqlite3RowSetText() for the same RowSet.  So
37070   ** there is never a forest to deal with.  Should this change, simply
37071   ** remove the assert() and the #if 0. */
37072   assert( p->pForest==0 );
37073 #if 0
37074   while( p->pForest ){
37075     struct RowSetEntry *pTree = p->pForest->pLeft;
37076     if( pTree ){
37077       struct RowSetEntry *pHead, *pTail;
37078       rowSetTreeToList(pTree, &pHead, &pTail);
37079       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
37080     }
37081     p->pForest = p->pForest->pRight;
37082   }
37083 #endif
37084   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
37085 }
37086
37087 /*
37088 ** Extract the smallest element from the RowSet.
37089 ** Write the element into *pRowid.  Return 1 on success.  Return
37090 ** 0 if the RowSet is already empty.
37091 **
37092 ** After this routine has been called, the sqlite3RowSetInsert()
37093 ** routine may not be called again.  
37094 */
37095 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
37096   assert( p!=0 );
37097
37098   /* Merge the forest into a single sorted list on first call */
37099   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
37100
37101   /* Return the next entry on the list */
37102   if( p->pEntry ){
37103     *pRowid = p->pEntry->v;
37104     p->pEntry = p->pEntry->pRight;
37105     if( p->pEntry==0 ){
37106       sqlite3RowSetClear(p);
37107     }
37108     return 1;
37109   }else{
37110     return 0;
37111   }
37112 }
37113
37114 /*
37115 ** Check to see if element iRowid was inserted into the rowset as
37116 ** part of any insert batch prior to iBatch.  Return 1 or 0.
37117 **
37118 ** If this is the first test of a new batch and if there exist entires
37119 ** on pRowSet->pEntry, then sort those entires into the forest at
37120 ** pRowSet->pForest so that they can be tested.
37121 */
37122 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
37123   struct RowSetEntry *p, *pTree;
37124
37125   /* This routine is never called after sqlite3RowSetNext() */
37126   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
37127
37128   /* Sort entries into the forest on the first test of a new batch 
37129   */
37130   if( iBatch!=pRowSet->iBatch ){
37131     p = pRowSet->pEntry;
37132     if( p ){
37133       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
37134       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
37135         p = rowSetEntrySort(p);
37136       }
37137       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37138         ppPrevTree = &pTree->pRight;
37139         if( pTree->pLeft==0 ){
37140           pTree->pLeft = rowSetListToTree(p);
37141           break;
37142         }else{
37143           struct RowSetEntry *pAux, *pTail;
37144           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
37145           pTree->pLeft = 0;
37146           p = rowSetEntryMerge(pAux, p);
37147         }
37148       }
37149       if( pTree==0 ){
37150         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
37151         if( pTree ){
37152           pTree->v = 0;
37153           pTree->pRight = 0;
37154           pTree->pLeft = rowSetListToTree(p);
37155         }
37156       }
37157       pRowSet->pEntry = 0;
37158       pRowSet->pLast = 0;
37159       pRowSet->rsFlags |= ROWSET_SORTED;
37160     }
37161     pRowSet->iBatch = iBatch;
37162   }
37163
37164   /* Test to see if the iRowid value appears anywhere in the forest.
37165   ** Return 1 if it does and 0 if not.
37166   */
37167   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37168     p = pTree->pLeft;
37169     while( p ){
37170       if( p->v<iRowid ){
37171         p = p->pRight;
37172       }else if( p->v>iRowid ){
37173         p = p->pLeft;
37174       }else{
37175         return 1;
37176       }
37177     }
37178   }
37179   return 0;
37180 }
37181
37182 /************** End of rowset.c **********************************************/
37183 /************** Begin file pager.c *******************************************/
37184 /*
37185 ** 2001 September 15
37186 **
37187 ** The author disclaims copyright to this source code.  In place of
37188 ** a legal notice, here is a blessing:
37189 **
37190 **    May you do good and not evil.
37191 **    May you find forgiveness for yourself and forgive others.
37192 **    May you share freely, never taking more than you give.
37193 **
37194 *************************************************************************
37195 ** This is the implementation of the page cache subsystem or "pager".
37196 ** 
37197 ** The pager is used to access a database disk file.  It implements
37198 ** atomic commit and rollback through the use of a journal file that
37199 ** is separate from the database file.  The pager also implements file
37200 ** locking to prevent two processes from writing the same database
37201 ** file simultaneously, or one process from reading the database while
37202 ** another is writing.
37203 */
37204 #ifndef SQLITE_OMIT_DISKIO
37205 /************** Include wal.h in the middle of pager.c ***********************/
37206 /************** Begin file wal.h *********************************************/
37207 /*
37208 ** 2010 February 1
37209 **
37210 ** The author disclaims copyright to this source code.  In place of
37211 ** a legal notice, here is a blessing:
37212 **
37213 **    May you do good and not evil.
37214 **    May you find forgiveness for yourself and forgive others.
37215 **    May you share freely, never taking more than you give.
37216 **
37217 *************************************************************************
37218 ** This header file defines the interface to the write-ahead logging 
37219 ** system. Refer to the comments below and the header comment attached to 
37220 ** the implementation of each function in log.c for further details.
37221 */
37222
37223 #ifndef _WAL_H_
37224 #define _WAL_H_
37225
37226
37227 /* Additional values that can be added to the sync_flags argument of
37228 ** sqlite3WalFrames():
37229 */
37230 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
37231 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
37232
37233 #ifdef SQLITE_OMIT_WAL
37234 # define sqlite3WalOpen(x,y,z)                   0
37235 # define sqlite3WalLimit(x,y)
37236 # define sqlite3WalClose(w,x,y,z)                0
37237 # define sqlite3WalBeginReadTransaction(y,z)     0
37238 # define sqlite3WalEndReadTransaction(z)
37239 # define sqlite3WalRead(v,w,x,y,z)               0
37240 # define sqlite3WalDbsize(y)                     0
37241 # define sqlite3WalBeginWriteTransaction(y)      0
37242 # define sqlite3WalEndWriteTransaction(x)        0
37243 # define sqlite3WalUndo(x,y,z)                   0
37244 # define sqlite3WalSavepoint(y,z)
37245 # define sqlite3WalSavepointUndo(y,z)            0
37246 # define sqlite3WalFrames(u,v,w,x,y,z)           0
37247 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
37248 # define sqlite3WalCallback(z)                   0
37249 # define sqlite3WalExclusiveMode(y,z)            0
37250 # define sqlite3WalHeapMemory(z)                 0
37251 # define sqlite3WalFramesize(z)                  0
37252 #else
37253
37254 #define WAL_SAVEPOINT_NDATA 4
37255
37256 /* Connection to a write-ahead log (WAL) file. 
37257 ** There is one object of this type for each pager. 
37258 */
37259 typedef struct Wal Wal;
37260
37261 /* Open and close a connection to a write-ahead log. */
37262 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
37263 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
37264
37265 /* Set the limiting size of a WAL file. */
37266 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
37267
37268 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
37269 ** snapshot is like a read-transaction.  It is the state of the database
37270 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
37271 ** preserves the current state even if the other threads or processes
37272 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
37273 ** transaction and releases the lock.
37274 */
37275 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
37276 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
37277
37278 /* Read a page from the write-ahead log, if it is present. */
37279 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
37280
37281 /* If the WAL is not empty, return the size of the database. */
37282 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
37283
37284 /* Obtain or release the WRITER lock. */
37285 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
37286 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
37287
37288 /* Undo any frames written (but not committed) to the log */
37289 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
37290
37291 /* Return an integer that records the current (uncommitted) write
37292 ** position in the WAL */
37293 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
37294
37295 /* Move the write position of the WAL back to iFrame.  Called in
37296 ** response to a ROLLBACK TO command. */
37297 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
37298
37299 /* Write a frame or frames to the log. */
37300 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
37301
37302 /* Copy pages from the log to the database file */ 
37303 SQLITE_PRIVATE int sqlite3WalCheckpoint(
37304   Wal *pWal,                      /* Write-ahead log connection */
37305   int eMode,                      /* One of PASSIVE, FULL and RESTART */
37306   int (*xBusy)(void*),            /* Function to call when busy */
37307   void *pBusyArg,                 /* Context argument for xBusyHandler */
37308   int sync_flags,                 /* Flags to sync db file with (or 0) */
37309   int nBuf,                       /* Size of buffer nBuf */
37310   u8 *zBuf,                       /* Temporary buffer to use */
37311   int *pnLog,                     /* OUT: Number of frames in WAL */
37312   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
37313 );
37314
37315 /* Return the value to pass to a sqlite3_wal_hook callback, the
37316 ** number of frames in the WAL at the point of the last commit since
37317 ** sqlite3WalCallback() was called.  If no commits have occurred since
37318 ** the last call, then return 0.
37319 */
37320 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
37321
37322 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
37323 ** by the pager layer on the database file.
37324 */
37325 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
37326
37327 /* Return true if the argument is non-NULL and the WAL module is using
37328 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
37329 ** WAL module is using shared-memory, return false. 
37330 */
37331 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
37332
37333 #ifdef SQLITE_ENABLE_ZIPVFS
37334 /* If the WAL file is not empty, return the number of bytes of content
37335 ** stored in each frame (i.e. the db page-size when the WAL was created).
37336 */
37337 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
37338 #endif
37339
37340 #endif /* ifndef SQLITE_OMIT_WAL */
37341 #endif /* _WAL_H_ */
37342
37343 /************** End of wal.h *************************************************/
37344 /************** Continuing where we left off in pager.c **********************/
37345
37346
37347 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
37348 **
37349 ** This comment block describes invariants that hold when using a rollback
37350 ** journal.  These invariants do not apply for journal_mode=WAL,
37351 ** journal_mode=MEMORY, or journal_mode=OFF.
37352 **
37353 ** Within this comment block, a page is deemed to have been synced
37354 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
37355 ** Otherwise, the page is not synced until the xSync method of the VFS
37356 ** is called successfully on the file containing the page.
37357 **
37358 ** Definition:  A page of the database file is said to be "overwriteable" if
37359 ** one or more of the following are true about the page:
37360 ** 
37361 **     (a)  The original content of the page as it was at the beginning of
37362 **          the transaction has been written into the rollback journal and
37363 **          synced.
37364 ** 
37365 **     (b)  The page was a freelist leaf page at the start of the transaction.
37366 ** 
37367 **     (c)  The page number is greater than the largest page that existed in
37368 **          the database file at the start of the transaction.
37369 ** 
37370 ** (1) A page of the database file is never overwritten unless one of the
37371 **     following are true:
37372 ** 
37373 **     (a) The page and all other pages on the same sector are overwriteable.
37374 ** 
37375 **     (b) The atomic page write optimization is enabled, and the entire
37376 **         transaction other than the update of the transaction sequence
37377 **         number consists of a single page change.
37378 ** 
37379 ** (2) The content of a page written into the rollback journal exactly matches
37380 **     both the content in the database when the rollback journal was written
37381 **     and the content in the database at the beginning of the current
37382 **     transaction.
37383 ** 
37384 ** (3) Writes to the database file are an integer multiple of the page size
37385 **     in length and are aligned on a page boundary.
37386 ** 
37387 ** (4) Reads from the database file are either aligned on a page boundary and
37388 **     an integer multiple of the page size in length or are taken from the
37389 **     first 100 bytes of the database file.
37390 ** 
37391 ** (5) All writes to the database file are synced prior to the rollback journal
37392 **     being deleted, truncated, or zeroed.
37393 ** 
37394 ** (6) If a master journal file is used, then all writes to the database file
37395 **     are synced prior to the master journal being deleted.
37396 ** 
37397 ** Definition: Two databases (or the same database at two points it time)
37398 ** are said to be "logically equivalent" if they give the same answer to
37399 ** all queries.  Note in particular the content of freelist leaf
37400 ** pages can be changed arbitarily without effecting the logical equivalence
37401 ** of the database.
37402 ** 
37403 ** (7) At any time, if any subset, including the empty set and the total set,
37404 **     of the unsynced changes to a rollback journal are removed and the 
37405 **     journal is rolled back, the resulting database file will be logical
37406 **     equivalent to the database file at the beginning of the transaction.
37407 ** 
37408 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37409 **     is called to restore the database file to the same size it was at
37410 **     the beginning of the transaction.  (In some VFSes, the xTruncate
37411 **     method is a no-op, but that does not change the fact the SQLite will
37412 **     invoke it.)
37413 ** 
37414 ** (9) Whenever the database file is modified, at least one bit in the range
37415 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
37416 **     the EXCLUSIVE lock, thus signaling other connections on the same
37417 **     database to flush their caches.
37418 **
37419 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37420 **      than one billion transactions.
37421 **
37422 ** (11) A database file is well-formed at the beginning and at the conclusion
37423 **      of every transaction.
37424 **
37425 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37426 **      the database file.
37427 **
37428 ** (13) A SHARED lock is held on the database file while reading any
37429 **      content out of the database file.
37430 **
37431 ******************************************************************************/
37432
37433 /*
37434 ** Macros for troubleshooting.  Normally turned off
37435 */
37436 #if 0
37437 int sqlite3PagerTrace=1;  /* True to enable tracing */
37438 #define sqlite3DebugPrintf printf
37439 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37440 #else
37441 #define PAGERTRACE(X)
37442 #endif
37443
37444 /*
37445 ** The following two macros are used within the PAGERTRACE() macros above
37446 ** to print out file-descriptors. 
37447 **
37448 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37449 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37450 ** struct as its argument.
37451 */
37452 #define PAGERID(p) ((int)(p->fd))
37453 #define FILEHANDLEID(fd) ((int)fd)
37454
37455 /*
37456 ** The Pager.eState variable stores the current 'state' of a pager. A
37457 ** pager may be in any one of the seven states shown in the following
37458 ** state diagram.
37459 **
37460 **                            OPEN <------+------+
37461 **                              |         |      |
37462 **                              V         |      |
37463 **               +---------> READER-------+      |
37464 **               |              |                |
37465 **               |              V                |
37466 **               |<-------WRITER_LOCKED------> ERROR
37467 **               |              |                ^  
37468 **               |              V                |
37469 **               |<------WRITER_CACHEMOD-------->|
37470 **               |              |                |
37471 **               |              V                |
37472 **               |<-------WRITER_DBMOD---------->|
37473 **               |              |                |
37474 **               |              V                |
37475 **               +<------WRITER_FINISHED-------->+
37476 **
37477 **
37478 ** List of state transitions and the C [function] that performs each:
37479 ** 
37480 **   OPEN              -> READER              [sqlite3PagerSharedLock]
37481 **   READER            -> OPEN                [pager_unlock]
37482 **
37483 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
37484 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
37485 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
37486 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
37487 **   WRITER_***        -> READER              [pager_end_transaction]
37488 **
37489 **   WRITER_***        -> ERROR               [pager_error]
37490 **   ERROR             -> OPEN                [pager_unlock]
37491 ** 
37492 **
37493 **  OPEN:
37494 **
37495 **    The pager starts up in this state. Nothing is guaranteed in this
37496 **    state - the file may or may not be locked and the database size is
37497 **    unknown. The database may not be read or written.
37498 **
37499 **    * No read or write transaction is active.
37500 **    * Any lock, or no lock at all, may be held on the database file.
37501 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37502 **
37503 **  READER:
37504 **
37505 **    In this state all the requirements for reading the database in 
37506 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
37507 **    was) in exclusive-locking mode, a user-level read transaction is 
37508 **    open. The database size is known in this state.
37509 **
37510 **    A connection running with locking_mode=normal enters this state when
37511 **    it opens a read-transaction on the database and returns to state
37512 **    OPEN after the read-transaction is completed. However a connection
37513 **    running in locking_mode=exclusive (including temp databases) remains in
37514 **    this state even after the read-transaction is closed. The only way
37515 **    a locking_mode=exclusive connection can transition from READER to OPEN
37516 **    is via the ERROR state (see below).
37517 ** 
37518 **    * A read transaction may be active (but a write-transaction cannot).
37519 **    * A SHARED or greater lock is held on the database file.
37520 **    * The dbSize variable may be trusted (even if a user-level read 
37521 **      transaction is not active). The dbOrigSize and dbFileSize variables
37522 **      may not be trusted at this point.
37523 **    * If the database is a WAL database, then the WAL connection is open.
37524 **    * Even if a read-transaction is not open, it is guaranteed that 
37525 **      there is no hot-journal in the file-system.
37526 **
37527 **  WRITER_LOCKED:
37528 **
37529 **    The pager moves to this state from READER when a write-transaction
37530 **    is first opened on the database. In WRITER_LOCKED state, all locks 
37531 **    required to start a write-transaction are held, but no actual 
37532 **    modifications to the cache or database have taken place.
37533 **
37534 **    In rollback mode, a RESERVED or (if the transaction was opened with 
37535 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37536 **    moving to this state, but the journal file is not written to or opened 
37537 **    to in this state. If the transaction is committed or rolled back while 
37538 **    in WRITER_LOCKED state, all that is required is to unlock the database 
37539 **    file.
37540 **
37541 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37542 **    If the connection is running with locking_mode=exclusive, an attempt
37543 **    is made to obtain an EXCLUSIVE lock on the database file.
37544 **
37545 **    * A write transaction is active.
37546 **    * If the connection is open in rollback-mode, a RESERVED or greater 
37547 **      lock is held on the database file.
37548 **    * If the connection is open in WAL-mode, a WAL write transaction
37549 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37550 **      called).
37551 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37552 **    * The contents of the pager cache have not been modified.
37553 **    * The journal file may or may not be open.
37554 **    * Nothing (not even the first header) has been written to the journal.
37555 **
37556 **  WRITER_CACHEMOD:
37557 **
37558 **    A pager moves from WRITER_LOCKED state to this state when a page is
37559 **    first modified by the upper layer. In rollback mode the journal file
37560 **    is opened (if it is not already open) and a header written to the
37561 **    start of it. The database file on disk has not been modified.
37562 **
37563 **    * A write transaction is active.
37564 **    * A RESERVED or greater lock is held on the database file.
37565 **    * The journal file is open and the first header has been written 
37566 **      to it, but the header has not been synced to disk.
37567 **    * The contents of the page cache have been modified.
37568 **
37569 **  WRITER_DBMOD:
37570 **
37571 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37572 **    when it modifies the contents of the database file. WAL connections
37573 **    never enter this state (since they do not modify the database file,
37574 **    just the log file).
37575 **
37576 **    * A write transaction is active.
37577 **    * An EXCLUSIVE or greater lock is held on the database file.
37578 **    * The journal file is open and the first header has been written 
37579 **      and synced to disk.
37580 **    * The contents of the page cache have been modified (and possibly
37581 **      written to disk).
37582 **
37583 **  WRITER_FINISHED:
37584 **
37585 **    It is not possible for a WAL connection to enter this state.
37586 **
37587 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37588 **    state after the entire transaction has been successfully written into the
37589 **    database file. In this state the transaction may be committed simply
37590 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
37591 **    not possible to modify the database further. At this point, the upper 
37592 **    layer must either commit or rollback the transaction.
37593 **
37594 **    * A write transaction is active.
37595 **    * An EXCLUSIVE or greater lock is held on the database file.
37596 **    * All writing and syncing of journal and database data has finished.
37597 **      If no error occured, all that remains is to finalize the journal to
37598 **      commit the transaction. If an error did occur, the caller will need
37599 **      to rollback the transaction. 
37600 **
37601 **  ERROR:
37602 **
37603 **    The ERROR state is entered when an IO or disk-full error (including
37604 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
37605 **    difficult to be sure that the in-memory pager state (cache contents, 
37606 **    db size etc.) are consistent with the contents of the file-system.
37607 **
37608 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37609 **    cannot.
37610 **
37611 **    For example, if an IO error occurs while performing a rollback, 
37612 **    the contents of the page-cache may be left in an inconsistent state.
37613 **    At this point it would be dangerous to change back to READER state
37614 **    (as usually happens after a rollback). Any subsequent readers might
37615 **    report database corruption (due to the inconsistent cache), and if
37616 **    they upgrade to writers, they may inadvertently corrupt the database
37617 **    file. To avoid this hazard, the pager switches into the ERROR state
37618 **    instead of READER following such an error.
37619 **
37620 **    Once it has entered the ERROR state, any attempt to use the pager
37621 **    to read or write data returns an error. Eventually, once all 
37622 **    outstanding transactions have been abandoned, the pager is able to
37623 **    transition back to OPEN state, discarding the contents of the 
37624 **    page-cache and any other in-memory state at the same time. Everything
37625 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37626 **    when a read-transaction is next opened on the pager (transitioning
37627 **    the pager into READER state). At that point the system has recovered 
37628 **    from the error.
37629 **
37630 **    Specifically, the pager jumps into the ERROR state if:
37631 **
37632 **      1. An error occurs while attempting a rollback. This happens in
37633 **         function sqlite3PagerRollback().
37634 **
37635 **      2. An error occurs while attempting to finalize a journal file
37636 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37637 **
37638 **      3. An error occurs while attempting to write to the journal or
37639 **         database file in function pagerStress() in order to free up
37640 **         memory.
37641 **
37642 **    In other cases, the error is returned to the b-tree layer. The b-tree
37643 **    layer then attempts a rollback operation. If the error condition 
37644 **    persists, the pager enters the ERROR state via condition (1) above.
37645 **
37646 **    Condition (3) is necessary because it can be triggered by a read-only
37647 **    statement executed within a transaction. In this case, if the error
37648 **    code were simply returned to the user, the b-tree layer would not
37649 **    automatically attempt a rollback, as it assumes that an error in a
37650 **    read-only statement cannot leave the pager in an internally inconsistent 
37651 **    state.
37652 **
37653 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37654 **    * There are one or more outstanding references to pages (after the
37655 **      last reference is dropped the pager should move back to OPEN state).
37656 **    * The pager is not an in-memory pager.
37657 **    
37658 **
37659 ** Notes:
37660 **
37661 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37662 **     connection is open in WAL mode. A WAL connection is always in one
37663 **     of the first four states.
37664 **
37665 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37666 **     state. There are two exceptions: immediately after exclusive-mode has
37667 **     been turned on (and before any read or write transactions are 
37668 **     executed), and when the pager is leaving the "error state".
37669 **
37670 **   * See also: assert_pager_state().
37671 */
37672 #define PAGER_OPEN                  0
37673 #define PAGER_READER                1
37674 #define PAGER_WRITER_LOCKED         2
37675 #define PAGER_WRITER_CACHEMOD       3
37676 #define PAGER_WRITER_DBMOD          4
37677 #define PAGER_WRITER_FINISHED       5
37678 #define PAGER_ERROR                 6
37679
37680 /*
37681 ** The Pager.eLock variable is almost always set to one of the 
37682 ** following locking-states, according to the lock currently held on
37683 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37684 ** This variable is kept up to date as locks are taken and released by
37685 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37686 **
37687 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37688 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37689 ** the operation was successful. In these circumstances pagerLockDb() and
37690 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37691 ** when unlocking the file, and only updated when locking the file if the
37692 ** VFS call is successful. This way, the Pager.eLock variable may be set
37693 ** to a less exclusive (lower) value than the lock that is actually held
37694 ** at the system level, but it is never set to a more exclusive value.
37695 **
37696 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
37697 ** be a few redundant xLock() calls or a lock may be held for longer than
37698 ** required, but nothing really goes wrong.
37699 **
37700 ** The exception is when the database file is unlocked as the pager moves
37701 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
37702 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37703 ** transition, by the same pager or any other). If the call to xUnlock()
37704 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37705 ** can confuse the call to xCheckReservedLock() call made later as part
37706 ** of hot-journal detection.
37707 **
37708 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
37709 ** lock held by this process or any others". So xCheckReservedLock may 
37710 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37711 ** doesn't know it because of a previous error in xUnlock). If this happens
37712 ** a hot-journal may be mistaken for a journal being created by an active
37713 ** transaction in another process, causing SQLite to read from the database
37714 ** without rolling it back.
37715 **
37716 ** To work around this, if a call to xUnlock() fails when unlocking the
37717 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37718 ** is only changed back to a real locking state after a successful call
37719 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37720 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
37721 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37722 ** lock on the database file before attempting to roll it back. See function
37723 ** PagerSharedLock() for more detail.
37724 **
37725 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
37726 ** PAGER_OPEN state.
37727 */
37728 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37729
37730 /*
37731 ** A macro used for invoking the codec if there is one
37732 */
37733 #ifdef SQLITE_HAS_CODEC
37734 # define CODEC1(P,D,N,X,E) \
37735     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37736 # define CODEC2(P,D,N,X,E,O) \
37737     if( P->xCodec==0 ){ O=(char*)D; }else \
37738     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37739 #else
37740 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37741 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37742 #endif
37743
37744 /*
37745 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
37746 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37747 ** This could conceivably cause corruption following a power failure on
37748 ** such a system. This is currently an undocumented limit.
37749 */
37750 #define MAX_SECTOR_SIZE 0x10000
37751
37752 /*
37753 ** An instance of the following structure is allocated for each active
37754 ** savepoint and statement transaction in the system. All such structures
37755 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37756 ** resized using sqlite3Realloc().
37757 **
37758 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37759 ** set to 0. If a journal-header is written into the main journal while
37760 ** the savepoint is active, then iHdrOffset is set to the byte offset 
37761 ** immediately following the last journal record written into the main
37762 ** journal before the journal-header. This is required during savepoint
37763 ** rollback (see pagerPlaybackSavepoint()).
37764 */
37765 typedef struct PagerSavepoint PagerSavepoint;
37766 struct PagerSavepoint {
37767   i64 iOffset;                 /* Starting offset in main journal */
37768   i64 iHdrOffset;              /* See above */
37769   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37770   Pgno nOrig;                  /* Original number of pages in file */
37771   Pgno iSubRec;                /* Index of first record in sub-journal */
37772 #ifndef SQLITE_OMIT_WAL
37773   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37774 #endif
37775 };
37776
37777 /*
37778 ** A open page cache is an instance of struct Pager. A description of
37779 ** some of the more important member variables follows:
37780 **
37781 ** eState
37782 **
37783 **   The current 'state' of the pager object. See the comment and state
37784 **   diagram above for a description of the pager state.
37785 **
37786 ** eLock
37787 **
37788 **   For a real on-disk database, the current lock held on the database file -
37789 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37790 **
37791 **   For a temporary or in-memory database (neither of which require any
37792 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37793 **   databases always have Pager.exclusiveMode==1, this tricks the pager
37794 **   logic into thinking that it already has all the locks it will ever
37795 **   need (and no reason to release them).
37796 **
37797 **   In some (obscure) circumstances, this variable may also be set to
37798 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37799 **   details.
37800 **
37801 ** changeCountDone
37802 **
37803 **   This boolean variable is used to make sure that the change-counter 
37804 **   (the 4-byte header field at byte offset 24 of the database file) is 
37805 **   not updated more often than necessary. 
37806 **
37807 **   It is set to true when the change-counter field is updated, which 
37808 **   can only happen if an exclusive lock is held on the database file.
37809 **   It is cleared (set to false) whenever an exclusive lock is 
37810 **   relinquished on the database file. Each time a transaction is committed,
37811 **   The changeCountDone flag is inspected. If it is true, the work of
37812 **   updating the change-counter is omitted for the current transaction.
37813 **
37814 **   This mechanism means that when running in exclusive mode, a connection 
37815 **   need only update the change-counter once, for the first transaction
37816 **   committed.
37817 **
37818 ** setMaster
37819 **
37820 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
37821 **   (or may not) specify a master-journal name to be written into the 
37822 **   journal file before it is synced to disk.
37823 **
37824 **   Whether or not a journal file contains a master-journal pointer affects 
37825 **   the way in which the journal file is finalized after the transaction is 
37826 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
37827 **   If a journal file does not contain a master-journal pointer, it is
37828 **   finalized by overwriting the first journal header with zeroes. If
37829 **   it does contain a master-journal pointer the journal file is finalized 
37830 **   by truncating it to zero bytes, just as if the connection were 
37831 **   running in "journal_mode=truncate" mode.
37832 **
37833 **   Journal files that contain master journal pointers cannot be finalized
37834 **   simply by overwriting the first journal-header with zeroes, as the
37835 **   master journal pointer could interfere with hot-journal rollback of any
37836 **   subsequently interrupted transaction that reuses the journal file.
37837 **
37838 **   The flag is cleared as soon as the journal file is finalized (either
37839 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37840 **   journal file from being successfully finalized, the setMaster flag
37841 **   is cleared anyway (and the pager will move to ERROR state).
37842 **
37843 ** doNotSpill, doNotSyncSpill
37844 **
37845 **   These two boolean variables control the behaviour of cache-spills
37846 **   (calls made by the pcache module to the pagerStress() routine to
37847 **   write cached data to the file-system in order to free up memory).
37848 **
37849 **   When doNotSpill is non-zero, writing to the database from pagerStress()
37850 **   is disabled altogether. This is done in a very obscure case that
37851 **   comes up during savepoint rollback that requires the pcache module
37852 **   to allocate a new page to prevent the journal file from being written
37853 **   while it is being traversed by code in pager_playback().
37854 ** 
37855 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37856 **   is permitted, but syncing the journal file is not. This flag is set
37857 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
37858 **   the database page-size in order to prevent a journal sync from happening 
37859 **   in between the journalling of two pages on the same sector. 
37860 **
37861 ** subjInMemory
37862 **
37863 **   This is a boolean variable. If true, then any required sub-journal
37864 **   is opened as an in-memory journal file. If false, then in-memory
37865 **   sub-journals are only used for in-memory pager files.
37866 **
37867 **   This variable is updated by the upper layer each time a new 
37868 **   write-transaction is opened.
37869 **
37870 ** dbSize, dbOrigSize, dbFileSize
37871 **
37872 **   Variable dbSize is set to the number of pages in the database file.
37873 **   It is valid in PAGER_READER and higher states (all states except for
37874 **   OPEN and ERROR). 
37875 **
37876 **   dbSize is set based on the size of the database file, which may be 
37877 **   larger than the size of the database (the value stored at offset
37878 **   28 of the database header by the btree). If the size of the file
37879 **   is not an integer multiple of the page-size, the value stored in
37880 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37881 **   Except, any file that is greater than 0 bytes in size is considered
37882 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
37883 **   to dbSize==1).
37884 **
37885 **   During a write-transaction, if pages with page-numbers greater than
37886 **   dbSize are modified in the cache, dbSize is updated accordingly.
37887 **   Similarly, if the database is truncated using PagerTruncateImage(), 
37888 **   dbSize is updated.
37889 **
37890 **   Variables dbOrigSize and dbFileSize are valid in states 
37891 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37892 **   variable at the start of the transaction. It is used during rollback,
37893 **   and to determine whether or not pages need to be journalled before
37894 **   being modified.
37895 **
37896 **   Throughout a write-transaction, dbFileSize contains the size of
37897 **   the file on disk in pages. It is set to a copy of dbSize when the
37898 **   write-transaction is first opened, and updated when VFS calls are made
37899 **   to write or truncate the database file on disk. 
37900 **
37901 **   The only reason the dbFileSize variable is required is to suppress 
37902 **   unnecessary calls to xTruncate() after committing a transaction. If, 
37903 **   when a transaction is committed, the dbFileSize variable indicates 
37904 **   that the database file is larger than the database image (Pager.dbSize), 
37905 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37906 **   to measure the database file on disk, and then truncates it if required.
37907 **   dbFileSize is not used when rolling back a transaction. In this case
37908 **   pager_truncate() is called unconditionally (which means there may be
37909 **   a call to xFilesize() that is not strictly required). In either case,
37910 **   pager_truncate() may cause the file to become smaller or larger.
37911 **
37912 ** dbHintSize
37913 **
37914 **   The dbHintSize variable is used to limit the number of calls made to
37915 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
37916 **
37917 **   dbHintSize is set to a copy of the dbSize variable when a
37918 **   write-transaction is opened (at the same time as dbFileSize and
37919 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37920 **   dbHintSize is increased to the number of pages that correspond to the
37921 **   size-hint passed to the method call. See pager_write_pagelist() for 
37922 **   details.
37923 **
37924 ** errCode
37925 **
37926 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37927 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
37928 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
37929 **   sub-codes.
37930 */
37931 struct Pager {
37932   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37933   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37934   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
37935   u8 useJournal;              /* Use a rollback journal on this file */
37936   u8 noSync;                  /* Do not sync the journal if true */
37937   u8 fullSync;                /* Do extra syncs of the journal for robustness */
37938   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37939   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
37940   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
37941   u8 tempFile;                /* zFilename is a temporary file */
37942   u8 readOnly;                /* True for a read-only database */
37943   u8 memDb;                   /* True to inhibit all file I/O */
37944
37945   /**************************************************************************
37946   ** The following block contains those class members that change during
37947   ** routine opertion.  Class members not in this block are either fixed
37948   ** when the pager is first created or else only change when there is a
37949   ** significant mode change (such as changing the page_size, locking_mode,
37950   ** or the journal_mode).  From another view, these class members describe
37951   ** the "state" of the pager, while other class members describe the
37952   ** "configuration" of the pager.
37953   */
37954   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37955   u8 eLock;                   /* Current lock held on database file */
37956   u8 changeCountDone;         /* Set after incrementing the change-counter */
37957   u8 setMaster;               /* True if a m-j name has been written to jrnl */
37958   u8 doNotSpill;              /* Do not spill the cache when non-zero */
37959   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
37960   u8 subjInMemory;            /* True to use in-memory sub-journals */
37961   Pgno dbSize;                /* Number of pages in the database */
37962   Pgno dbOrigSize;            /* dbSize before the current transaction */
37963   Pgno dbFileSize;            /* Number of pages in the database file */
37964   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
37965   int errCode;                /* One of several kinds of errors */
37966   int nRec;                   /* Pages journalled since last j-header written */
37967   u32 cksumInit;              /* Quasi-random value added to every checksum */
37968   u32 nSubRec;                /* Number of records written to sub-journal */
37969   Bitvec *pInJournal;         /* One bit for each page in the database file */
37970   sqlite3_file *fd;           /* File descriptor for database */
37971   sqlite3_file *jfd;          /* File descriptor for main journal */
37972   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
37973   i64 journalOff;             /* Current write offset in the journal file */
37974   i64 journalHdr;             /* Byte offset to previous journal header */
37975   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
37976   PagerSavepoint *aSavepoint; /* Array of active savepoints */
37977   int nSavepoint;             /* Number of elements in aSavepoint[] */
37978   char dbFileVers[16];        /* Changes whenever database file changes */
37979   /*
37980   ** End of the routinely-changing class members
37981   ***************************************************************************/
37982
37983   u16 nExtra;                 /* Add this many bytes to each in-memory page */
37984   i16 nReserve;               /* Number of unused bytes at end of each page */
37985   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37986   u32 sectorSize;             /* Assumed sector size during rollback */
37987   int pageSize;               /* Number of bytes in a page */
37988   Pgno mxPgno;                /* Maximum allowed size of the database */
37989   i64 journalSizeLimit;       /* Size limit for persistent journal files */
37990   char *zFilename;            /* Name of the database file */
37991   char *zJournal;             /* Name of the journal file */
37992   int (*xBusyHandler)(void*); /* Function to call when busy */
37993   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37994   int aStat[3];               /* Total cache hits, misses and writes */
37995 #ifdef SQLITE_TEST
37996   int nRead;                  /* Database pages read */
37997 #endif
37998   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37999 #ifdef SQLITE_HAS_CODEC
38000   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
38001   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
38002   void (*xCodecFree)(void*);             /* Destructor for the codec */
38003   void *pCodec;               /* First argument to xCodec... methods */
38004 #endif
38005   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
38006   PCache *pPCache;            /* Pointer to page cache object */
38007 #ifndef SQLITE_OMIT_WAL
38008   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
38009   char *zWal;                 /* File name for write-ahead log */
38010 #endif
38011 };
38012
38013 /*
38014 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
38015 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
38016 ** or CACHE_WRITE to sqlite3_db_status().
38017 */
38018 #define PAGER_STAT_HIT   0
38019 #define PAGER_STAT_MISS  1
38020 #define PAGER_STAT_WRITE 2
38021
38022 /*
38023 ** The following global variables hold counters used for
38024 ** testing purposes only.  These variables do not exist in
38025 ** a non-testing build.  These variables are not thread-safe.
38026 */
38027 #ifdef SQLITE_TEST
38028 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
38029 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
38030 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
38031 # define PAGER_INCR(v)  v++
38032 #else
38033 # define PAGER_INCR(v)
38034 #endif
38035
38036
38037
38038 /*
38039 ** Journal files begin with the following magic string.  The data
38040 ** was obtained from /dev/random.  It is used only as a sanity check.
38041 **
38042 ** Since version 2.8.0, the journal format contains additional sanity
38043 ** checking information.  If the power fails while the journal is being
38044 ** written, semi-random garbage data might appear in the journal
38045 ** file after power is restored.  If an attempt is then made
38046 ** to roll the journal back, the database could be corrupted.  The additional
38047 ** sanity checking data is an attempt to discover the garbage in the
38048 ** journal and ignore it.
38049 **
38050 ** The sanity checking information for the new journal format consists
38051 ** of a 32-bit checksum on each page of data.  The checksum covers both
38052 ** the page number and the pPager->pageSize bytes of data for the page.
38053 ** This cksum is initialized to a 32-bit random value that appears in the
38054 ** journal file right after the header.  The random initializer is important,
38055 ** because garbage data that appears at the end of a journal is likely
38056 ** data that was once in other files that have now been deleted.  If the
38057 ** garbage data came from an obsolete journal file, the checksums might
38058 ** be correct.  But by initializing the checksum to random value which
38059 ** is different for every journal, we minimize that risk.
38060 */
38061 static const unsigned char aJournalMagic[] = {
38062   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
38063 };
38064
38065 /*
38066 ** The size of the of each page record in the journal is given by
38067 ** the following macro.
38068 */
38069 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
38070
38071 /*
38072 ** The journal header size for this pager. This is usually the same 
38073 ** size as a single disk sector. See also setSectorSize().
38074 */
38075 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
38076
38077 /*
38078 ** The macro MEMDB is true if we are dealing with an in-memory database.
38079 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
38080 ** the value of MEMDB will be a constant and the compiler will optimize
38081 ** out code that would never execute.
38082 */
38083 #ifdef SQLITE_OMIT_MEMORYDB
38084 # define MEMDB 0
38085 #else
38086 # define MEMDB pPager->memDb
38087 #endif
38088
38089 /*
38090 ** The maximum legal page number is (2^31 - 1).
38091 */
38092 #define PAGER_MAX_PGNO 2147483647
38093
38094 /*
38095 ** The argument to this macro is a file descriptor (type sqlite3_file*).
38096 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
38097 **
38098 ** This is so that expressions can be written as:
38099 **
38100 **   if( isOpen(pPager->jfd) ){ ...
38101 **
38102 ** instead of
38103 **
38104 **   if( pPager->jfd->pMethods ){ ...
38105 */
38106 #define isOpen(pFd) ((pFd)->pMethods)
38107
38108 /*
38109 ** Return true if this pager uses a write-ahead log instead of the usual
38110 ** rollback journal. Otherwise false.
38111 */
38112 #ifndef SQLITE_OMIT_WAL
38113 static int pagerUseWal(Pager *pPager){
38114   return (pPager->pWal!=0);
38115 }
38116 #else
38117 # define pagerUseWal(x) 0
38118 # define pagerRollbackWal(x) 0
38119 # define pagerWalFrames(v,w,x,y) 0
38120 # define pagerOpenWalIfPresent(z) SQLITE_OK
38121 # define pagerBeginReadTransaction(z) SQLITE_OK
38122 #endif
38123
38124 #ifndef NDEBUG 
38125 /*
38126 ** Usage:
38127 **
38128 **   assert( assert_pager_state(pPager) );
38129 **
38130 ** This function runs many asserts to try to find inconsistencies in
38131 ** the internal state of the Pager object.
38132 */
38133 static int assert_pager_state(Pager *p){
38134   Pager *pPager = p;
38135
38136   /* State must be valid. */
38137   assert( p->eState==PAGER_OPEN
38138        || p->eState==PAGER_READER
38139        || p->eState==PAGER_WRITER_LOCKED
38140        || p->eState==PAGER_WRITER_CACHEMOD
38141        || p->eState==PAGER_WRITER_DBMOD
38142        || p->eState==PAGER_WRITER_FINISHED
38143        || p->eState==PAGER_ERROR
38144   );
38145
38146   /* Regardless of the current state, a temp-file connection always behaves
38147   ** as if it has an exclusive lock on the database file. It never updates
38148   ** the change-counter field, so the changeCountDone flag is always set.
38149   */
38150   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
38151   assert( p->tempFile==0 || pPager->changeCountDone );
38152
38153   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
38154   ** And if the journal-mode is "OFF", the journal file must not be open.
38155   */
38156   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
38157   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
38158
38159   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
38160   ** this means an in-memory pager performs no IO at all, it cannot encounter 
38161   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
38162   ** a journal file. (although the in-memory journal implementation may 
38163   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
38164   ** is therefore not possible for an in-memory pager to enter the ERROR 
38165   ** state.
38166   */
38167   if( MEMDB ){
38168     assert( p->noSync );
38169     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
38170          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
38171     );
38172     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
38173     assert( pagerUseWal(p)==0 );
38174   }
38175
38176   /* If changeCountDone is set, a RESERVED lock or greater must be held
38177   ** on the file.
38178   */
38179   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
38180   assert( p->eLock!=PENDING_LOCK );
38181
38182   switch( p->eState ){
38183     case PAGER_OPEN:
38184       assert( !MEMDB );
38185       assert( pPager->errCode==SQLITE_OK );
38186       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
38187       break;
38188
38189     case PAGER_READER:
38190       assert( pPager->errCode==SQLITE_OK );
38191       assert( p->eLock!=UNKNOWN_LOCK );
38192       assert( p->eLock>=SHARED_LOCK );
38193       break;
38194
38195     case PAGER_WRITER_LOCKED:
38196       assert( p->eLock!=UNKNOWN_LOCK );
38197       assert( pPager->errCode==SQLITE_OK );
38198       if( !pagerUseWal(pPager) ){
38199         assert( p->eLock>=RESERVED_LOCK );
38200       }
38201       assert( pPager->dbSize==pPager->dbOrigSize );
38202       assert( pPager->dbOrigSize==pPager->dbFileSize );
38203       assert( pPager->dbOrigSize==pPager->dbHintSize );
38204       assert( pPager->setMaster==0 );
38205       break;
38206
38207     case PAGER_WRITER_CACHEMOD:
38208       assert( p->eLock!=UNKNOWN_LOCK );
38209       assert( pPager->errCode==SQLITE_OK );
38210       if( !pagerUseWal(pPager) ){
38211         /* It is possible that if journal_mode=wal here that neither the
38212         ** journal file nor the WAL file are open. This happens during
38213         ** a rollback transaction that switches from journal_mode=off
38214         ** to journal_mode=wal.
38215         */
38216         assert( p->eLock>=RESERVED_LOCK );
38217         assert( isOpen(p->jfd) 
38218              || p->journalMode==PAGER_JOURNALMODE_OFF 
38219              || p->journalMode==PAGER_JOURNALMODE_WAL 
38220         );
38221       }
38222       assert( pPager->dbOrigSize==pPager->dbFileSize );
38223       assert( pPager->dbOrigSize==pPager->dbHintSize );
38224       break;
38225
38226     case PAGER_WRITER_DBMOD:
38227       assert( p->eLock==EXCLUSIVE_LOCK );
38228       assert( pPager->errCode==SQLITE_OK );
38229       assert( !pagerUseWal(pPager) );
38230       assert( p->eLock>=EXCLUSIVE_LOCK );
38231       assert( isOpen(p->jfd) 
38232            || p->journalMode==PAGER_JOURNALMODE_OFF 
38233            || p->journalMode==PAGER_JOURNALMODE_WAL 
38234       );
38235       assert( pPager->dbOrigSize<=pPager->dbHintSize );
38236       break;
38237
38238     case PAGER_WRITER_FINISHED:
38239       assert( p->eLock==EXCLUSIVE_LOCK );
38240       assert( pPager->errCode==SQLITE_OK );
38241       assert( !pagerUseWal(pPager) );
38242       assert( isOpen(p->jfd) 
38243            || p->journalMode==PAGER_JOURNALMODE_OFF 
38244            || p->journalMode==PAGER_JOURNALMODE_WAL 
38245       );
38246       break;
38247
38248     case PAGER_ERROR:
38249       /* There must be at least one outstanding reference to the pager if
38250       ** in ERROR state. Otherwise the pager should have already dropped
38251       ** back to OPEN state.
38252       */
38253       assert( pPager->errCode!=SQLITE_OK );
38254       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
38255       break;
38256   }
38257
38258   return 1;
38259 }
38260 #endif /* ifndef NDEBUG */
38261
38262 #ifdef SQLITE_DEBUG 
38263 /*
38264 ** Return a pointer to a human readable string in a static buffer
38265 ** containing the state of the Pager object passed as an argument. This
38266 ** is intended to be used within debuggers. For example, as an alternative
38267 ** to "print *pPager" in gdb:
38268 **
38269 ** (gdb) printf "%s", print_pager_state(pPager)
38270 */
38271 static char *print_pager_state(Pager *p){
38272   static char zRet[1024];
38273
38274   sqlite3_snprintf(1024, zRet,
38275       "Filename:      %s\n"
38276       "State:         %s errCode=%d\n"
38277       "Lock:          %s\n"
38278       "Locking mode:  locking_mode=%s\n"
38279       "Journal mode:  journal_mode=%s\n"
38280       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
38281       "Journal:       journalOff=%lld journalHdr=%lld\n"
38282       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
38283       , p->zFilename
38284       , p->eState==PAGER_OPEN            ? "OPEN" :
38285         p->eState==PAGER_READER          ? "READER" :
38286         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
38287         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
38288         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
38289         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
38290         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
38291       , (int)p->errCode
38292       , p->eLock==NO_LOCK         ? "NO_LOCK" :
38293         p->eLock==RESERVED_LOCK   ? "RESERVED" :
38294         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
38295         p->eLock==SHARED_LOCK     ? "SHARED" :
38296         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
38297       , p->exclusiveMode ? "exclusive" : "normal"
38298       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
38299         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
38300         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
38301         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
38302         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
38303         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
38304       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
38305       , p->journalOff, p->journalHdr
38306       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
38307   );
38308
38309   return zRet;
38310 }
38311 #endif
38312
38313 /*
38314 ** Return true if it is necessary to write page *pPg into the sub-journal.
38315 ** A page needs to be written into the sub-journal if there exists one
38316 ** or more open savepoints for which:
38317 **
38318 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
38319 **   * The bit corresponding to the page-number is not set in
38320 **     PagerSavepoint.pInSavepoint.
38321 */
38322 static int subjRequiresPage(PgHdr *pPg){
38323   Pgno pgno = pPg->pgno;
38324   Pager *pPager = pPg->pPager;
38325   int i;
38326   for(i=0; i<pPager->nSavepoint; i++){
38327     PagerSavepoint *p = &pPager->aSavepoint[i];
38328     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
38329       return 1;
38330     }
38331   }
38332   return 0;
38333 }
38334
38335 /*
38336 ** Return true if the page is already in the journal file.
38337 */
38338 static int pageInJournal(PgHdr *pPg){
38339   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
38340 }
38341
38342 /*
38343 ** Read a 32-bit integer from the given file descriptor.  Store the integer
38344 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
38345 ** error code is something goes wrong.
38346 **
38347 ** All values are stored on disk as big-endian.
38348 */
38349 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
38350   unsigned char ac[4];
38351   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
38352   if( rc==SQLITE_OK ){
38353     *pRes = sqlite3Get4byte(ac);
38354   }
38355   return rc;
38356 }
38357
38358 /*
38359 ** Write a 32-bit integer into a string buffer in big-endian byte order.
38360 */
38361 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
38362
38363
38364 /*
38365 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
38366 ** on success or an error code is something goes wrong.
38367 */
38368 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
38369   char ac[4];
38370   put32bits(ac, val);
38371   return sqlite3OsWrite(fd, ac, 4, offset);
38372 }
38373
38374 /*
38375 ** Unlock the database file to level eLock, which must be either NO_LOCK
38376 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38377 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38378 **
38379 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38380 ** called, do not modify it. See the comment above the #define of 
38381 ** UNKNOWN_LOCK for an explanation of this.
38382 */
38383 static int pagerUnlockDb(Pager *pPager, int eLock){
38384   int rc = SQLITE_OK;
38385
38386   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38387   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38388   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38389   if( isOpen(pPager->fd) ){
38390     assert( pPager->eLock>=eLock );
38391     rc = sqlite3OsUnlock(pPager->fd, eLock);
38392     if( pPager->eLock!=UNKNOWN_LOCK ){
38393       pPager->eLock = (u8)eLock;
38394     }
38395     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38396   }
38397   return rc;
38398 }
38399
38400 /*
38401 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38402 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38403 ** Pager.eLock variable to the new locking state. 
38404 **
38405 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
38406 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
38407 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
38408 ** of this.
38409 */
38410 static int pagerLockDb(Pager *pPager, int eLock){
38411   int rc = SQLITE_OK;
38412
38413   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38414   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38415     rc = sqlite3OsLock(pPager->fd, eLock);
38416     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38417       pPager->eLock = (u8)eLock;
38418       IOTRACE(("LOCK %p %d\n", pPager, eLock))
38419     }
38420   }
38421   return rc;
38422 }
38423
38424 /*
38425 ** This function determines whether or not the atomic-write optimization
38426 ** can be used with this pager. The optimization can be used if:
38427 **
38428 **  (a) the value returned by OsDeviceCharacteristics() indicates that
38429 **      a database page may be written atomically, and
38430 **  (b) the value returned by OsSectorSize() is less than or equal
38431 **      to the page size.
38432 **
38433 ** The optimization is also always enabled for temporary files. It is
38434 ** an error to call this function if pPager is opened on an in-memory
38435 ** database.
38436 **
38437 ** If the optimization cannot be used, 0 is returned. If it can be used,
38438 ** then the value returned is the size of the journal file when it
38439 ** contains rollback data for exactly one page.
38440 */
38441 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38442 static int jrnlBufferSize(Pager *pPager){
38443   assert( !MEMDB );
38444   if( !pPager->tempFile ){
38445     int dc;                           /* Device characteristics */
38446     int nSector;                      /* Sector size */
38447     int szPage;                       /* Page size */
38448
38449     assert( isOpen(pPager->fd) );
38450     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38451     nSector = pPager->sectorSize;
38452     szPage = pPager->pageSize;
38453
38454     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38455     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38456     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38457       return 0;
38458     }
38459   }
38460
38461   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38462 }
38463 #endif
38464
38465 /*
38466 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38467 ** on the cache using a hash function.  This is used for testing
38468 ** and debugging only.
38469 */
38470 #ifdef SQLITE_CHECK_PAGES
38471 /*
38472 ** Return a 32-bit hash of the page data for pPage.
38473 */
38474 static u32 pager_datahash(int nByte, unsigned char *pData){
38475   u32 hash = 0;
38476   int i;
38477   for(i=0; i<nByte; i++){
38478     hash = (hash*1039) + pData[i];
38479   }
38480   return hash;
38481 }
38482 static u32 pager_pagehash(PgHdr *pPage){
38483   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38484 }
38485 static void pager_set_pagehash(PgHdr *pPage){
38486   pPage->pageHash = pager_pagehash(pPage);
38487 }
38488
38489 /*
38490 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38491 ** is defined, and NDEBUG is not defined, an assert() statement checks
38492 ** that the page is either dirty or still matches the calculated page-hash.
38493 */
38494 #define CHECK_PAGE(x) checkPage(x)
38495 static void checkPage(PgHdr *pPg){
38496   Pager *pPager = pPg->pPager;
38497   assert( pPager->eState!=PAGER_ERROR );
38498   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38499 }
38500
38501 #else
38502 #define pager_datahash(X,Y)  0
38503 #define pager_pagehash(X)  0
38504 #define pager_set_pagehash(X)
38505 #define CHECK_PAGE(x)
38506 #endif  /* SQLITE_CHECK_PAGES */
38507
38508 /*
38509 ** When this is called the journal file for pager pPager must be open.
38510 ** This function attempts to read a master journal file name from the 
38511 ** end of the file and, if successful, copies it into memory supplied 
38512 ** by the caller. See comments above writeMasterJournal() for the format
38513 ** used to store a master journal file name at the end of a journal file.
38514 **
38515 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38516 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38517 ** enough space to write the master journal name). If the master journal
38518 ** name in the journal is longer than nMaster bytes (including a
38519 ** nul-terminator), then this is handled as if no master journal name
38520 ** were present in the journal.
38521 **
38522 ** If a master journal file name is present at the end of the journal
38523 ** file, then it is copied into the buffer pointed to by zMaster. A
38524 ** nul-terminator byte is appended to the buffer following the master
38525 ** journal file name.
38526 **
38527 ** If it is determined that no master journal file name is present 
38528 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38529 **
38530 ** If an error occurs while reading from the journal file, an SQLite
38531 ** error code is returned.
38532 */
38533 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38534   int rc;                    /* Return code */
38535   u32 len;                   /* Length in bytes of master journal name */
38536   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
38537   u32 cksum;                 /* MJ checksum value read from journal */
38538   u32 u;                     /* Unsigned loop counter */
38539   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38540   zMaster[0] = '\0';
38541
38542   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38543    || szJ<16
38544    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38545    || len>=nMaster 
38546    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38547    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38548    || memcmp(aMagic, aJournalMagic, 8)
38549    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38550   ){
38551     return rc;
38552   }
38553
38554   /* See if the checksum matches the master journal name */
38555   for(u=0; u<len; u++){
38556     cksum -= zMaster[u];
38557   }
38558   if( cksum ){
38559     /* If the checksum doesn't add up, then one or more of the disk sectors
38560     ** containing the master journal filename is corrupted. This means
38561     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38562     ** master-journal filename.
38563     */
38564     len = 0;
38565   }
38566   zMaster[len] = '\0';
38567    
38568   return SQLITE_OK;
38569 }
38570
38571 /*
38572 ** Return the offset of the sector boundary at or immediately 
38573 ** following the value in pPager->journalOff, assuming a sector 
38574 ** size of pPager->sectorSize bytes.
38575 **
38576 ** i.e for a sector size of 512:
38577 **
38578 **   Pager.journalOff          Return value
38579 **   ---------------------------------------
38580 **   0                         0
38581 **   512                       512
38582 **   100                       512
38583 **   2000                      2048
38584 ** 
38585 */
38586 static i64 journalHdrOffset(Pager *pPager){
38587   i64 offset = 0;
38588   i64 c = pPager->journalOff;
38589   if( c ){
38590     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38591   }
38592   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38593   assert( offset>=c );
38594   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38595   return offset;
38596 }
38597
38598 /*
38599 ** The journal file must be open when this function is called.
38600 **
38601 ** This function is a no-op if the journal file has not been written to
38602 ** within the current transaction (i.e. if Pager.journalOff==0).
38603 **
38604 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38605 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38606 ** zero the 28-byte header at the start of the journal file. In either case, 
38607 ** if the pager is not in no-sync mode, sync the journal file immediately 
38608 ** after writing or truncating it.
38609 **
38610 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38611 ** following the truncation or zeroing described above the size of the 
38612 ** journal file in bytes is larger than this value, then truncate the
38613 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38614 ** not need to be synced following this operation.
38615 **
38616 ** If an IO error occurs, abandon processing and return the IO error code.
38617 ** Otherwise, return SQLITE_OK.
38618 */
38619 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38620   int rc = SQLITE_OK;                               /* Return code */
38621   assert( isOpen(pPager->jfd) );
38622   if( pPager->journalOff ){
38623     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38624
38625     IOTRACE(("JZEROHDR %p\n", pPager))
38626     if( doTruncate || iLimit==0 ){
38627       rc = sqlite3OsTruncate(pPager->jfd, 0);
38628     }else{
38629       static const char zeroHdr[28] = {0};
38630       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38631     }
38632     if( rc==SQLITE_OK && !pPager->noSync ){
38633       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38634     }
38635
38636     /* At this point the transaction is committed but the write lock 
38637     ** is still held on the file. If there is a size limit configured for 
38638     ** the persistent journal and the journal file currently consumes more
38639     ** space than that limit allows for, truncate it now. There is no need
38640     ** to sync the file following this operation.
38641     */
38642     if( rc==SQLITE_OK && iLimit>0 ){
38643       i64 sz;
38644       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38645       if( rc==SQLITE_OK && sz>iLimit ){
38646         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38647       }
38648     }
38649   }
38650   return rc;
38651 }
38652
38653 /*
38654 ** The journal file must be open when this routine is called. A journal
38655 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38656 ** current location.
38657 **
38658 ** The format for the journal header is as follows:
38659 ** - 8 bytes: Magic identifying journal format.
38660 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38661 ** - 4 bytes: Random number used for page hash.
38662 ** - 4 bytes: Initial database page count.
38663 ** - 4 bytes: Sector size used by the process that wrote this journal.
38664 ** - 4 bytes: Database page size.
38665 ** 
38666 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38667 */
38668 static int writeJournalHdr(Pager *pPager){
38669   int rc = SQLITE_OK;                 /* Return code */
38670   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38671   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38672   u32 nWrite;                         /* Bytes of header sector written */
38673   int ii;                             /* Loop counter */
38674
38675   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38676
38677   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38678     nHeader = JOURNAL_HDR_SZ(pPager);
38679   }
38680
38681   /* If there are active savepoints and any of them were created 
38682   ** since the most recent journal header was written, update the 
38683   ** PagerSavepoint.iHdrOffset fields now.
38684   */
38685   for(ii=0; ii<pPager->nSavepoint; ii++){
38686     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38687       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38688     }
38689   }
38690
38691   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38692
38693   /* 
38694   ** Write the nRec Field - the number of page records that follow this
38695   ** journal header. Normally, zero is written to this value at this time.
38696   ** After the records are added to the journal (and the journal synced, 
38697   ** if in full-sync mode), the zero is overwritten with the true number
38698   ** of records (see syncJournal()).
38699   **
38700   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38701   ** reading the journal this value tells SQLite to assume that the
38702   ** rest of the journal file contains valid page records. This assumption
38703   ** is dangerous, as if a failure occurred whilst writing to the journal
38704   ** file it may contain some garbage data. There are two scenarios
38705   ** where this risk can be ignored:
38706   **
38707   **   * When the pager is in no-sync mode. Corruption can follow a
38708   **     power failure in this case anyway.
38709   **
38710   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38711   **     that garbage data is never appended to the journal file.
38712   */
38713   assert( isOpen(pPager->fd) || pPager->noSync );
38714   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38715    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
38716   ){
38717     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38718     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38719   }else{
38720     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38721   }
38722
38723   /* The random check-hash initialiser */ 
38724   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38725   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38726   /* The initial database size */
38727   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38728   /* The assumed sector size for this process */
38729   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38730
38731   /* The page size */
38732   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38733
38734   /* Initializing the tail of the buffer is not necessary.  Everything
38735   ** works find if the following memset() is omitted.  But initializing
38736   ** the memory prevents valgrind from complaining, so we are willing to
38737   ** take the performance hit.
38738   */
38739   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38740          nHeader-(sizeof(aJournalMagic)+20));
38741
38742   /* In theory, it is only necessary to write the 28 bytes that the 
38743   ** journal header consumes to the journal file here. Then increment the 
38744   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
38745   ** record is written to the following sector (leaving a gap in the file
38746   ** that will be implicitly filled in by the OS).
38747   **
38748   ** However it has been discovered that on some systems this pattern can 
38749   ** be significantly slower than contiguously writing data to the file,
38750   ** even if that means explicitly writing data to the block of 
38751   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38752   ** is done. 
38753   **
38754   ** The loop is required here in case the sector-size is larger than the 
38755   ** database page size. Since the zHeader buffer is only Pager.pageSize
38756   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38757   ** to populate the entire journal header sector.
38758   */ 
38759   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38760     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38761     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38762     assert( pPager->journalHdr <= pPager->journalOff );
38763     pPager->journalOff += nHeader;
38764   }
38765
38766   return rc;
38767 }
38768
38769 /*
38770 ** The journal file must be open when this is called. A journal header file
38771 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38772 ** file. The current location in the journal file is given by
38773 ** pPager->journalOff. See comments above function writeJournalHdr() for
38774 ** a description of the journal header format.
38775 **
38776 ** If the header is read successfully, *pNRec is set to the number of
38777 ** page records following this header and *pDbSize is set to the size of the
38778 ** database before the transaction began, in pages. Also, pPager->cksumInit
38779 ** is set to the value read from the journal header. SQLITE_OK is returned
38780 ** in this case.
38781 **
38782 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38783 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38784 ** cannot be read from the journal file an error code is returned.
38785 */
38786 static int readJournalHdr(
38787   Pager *pPager,               /* Pager object */
38788   int isHot,
38789   i64 journalSize,             /* Size of the open journal file in bytes */
38790   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38791   u32 *pDbSize                 /* OUT: Value of original database size field */
38792 ){
38793   int rc;                      /* Return code */
38794   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38795   i64 iHdrOff;                 /* Offset of journal header being read */
38796
38797   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38798
38799   /* Advance Pager.journalOff to the start of the next sector. If the
38800   ** journal file is too small for there to be a header stored at this
38801   ** point, return SQLITE_DONE.
38802   */
38803   pPager->journalOff = journalHdrOffset(pPager);
38804   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38805     return SQLITE_DONE;
38806   }
38807   iHdrOff = pPager->journalOff;
38808
38809   /* Read in the first 8 bytes of the journal header. If they do not match
38810   ** the  magic string found at the start of each journal header, return
38811   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38812   ** proceed.
38813   */
38814   if( isHot || iHdrOff!=pPager->journalHdr ){
38815     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38816     if( rc ){
38817       return rc;
38818     }
38819     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38820       return SQLITE_DONE;
38821     }
38822   }
38823
38824   /* Read the first three 32-bit fields of the journal header: The nRec
38825   ** field, the checksum-initializer and the database size at the start
38826   ** of the transaction. Return an error code if anything goes wrong.
38827   */
38828   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38829    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38830    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38831   ){
38832     return rc;
38833   }
38834
38835   if( pPager->journalOff==0 ){
38836     u32 iPageSize;               /* Page-size field of journal header */
38837     u32 iSectorSize;             /* Sector-size field of journal header */
38838
38839     /* Read the page-size and sector-size journal header fields. */
38840     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38841      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38842     ){
38843       return rc;
38844     }
38845
38846     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38847     ** journal header to zero. In this case, assume that the Pager.pageSize
38848     ** variable is already set to the correct page size.
38849     */
38850     if( iPageSize==0 ){
38851       iPageSize = pPager->pageSize;
38852     }
38853
38854     /* Check that the values read from the page-size and sector-size fields
38855     ** are within range. To be 'in range', both values need to be a power
38856     ** of two greater than or equal to 512 or 32, and not greater than their 
38857     ** respective compile time maximum limits.
38858     */
38859     if( iPageSize<512                  || iSectorSize<32
38860      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38861      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
38862     ){
38863       /* If the either the page-size or sector-size in the journal-header is 
38864       ** invalid, then the process that wrote the journal-header must have 
38865       ** crashed before the header was synced. In this case stop reading 
38866       ** the journal file here.
38867       */
38868       return SQLITE_DONE;
38869     }
38870
38871     /* Update the page-size to match the value read from the journal. 
38872     ** Use a testcase() macro to make sure that malloc failure within 
38873     ** PagerSetPagesize() is tested.
38874     */
38875     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38876     testcase( rc!=SQLITE_OK );
38877
38878     /* Update the assumed sector-size to match the value used by 
38879     ** the process that created this journal. If this journal was
38880     ** created by a process other than this one, then this routine
38881     ** is being called from within pager_playback(). The local value
38882     ** of Pager.sectorSize is restored at the end of that routine.
38883     */
38884     pPager->sectorSize = iSectorSize;
38885   }
38886
38887   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38888   return rc;
38889 }
38890
38891
38892 /*
38893 ** Write the supplied master journal name into the journal file for pager
38894 ** pPager at the current location. The master journal name must be the last
38895 ** thing written to a journal file. If the pager is in full-sync mode, the
38896 ** journal file descriptor is advanced to the next sector boundary before
38897 ** anything is written. The format is:
38898 **
38899 **   + 4 bytes: PAGER_MJ_PGNO.
38900 **   + N bytes: Master journal filename in utf-8.
38901 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38902 **   + 4 bytes: Master journal name checksum.
38903 **   + 8 bytes: aJournalMagic[].
38904 **
38905 ** The master journal page checksum is the sum of the bytes in the master
38906 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38907 **
38908 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
38909 ** this call is a no-op.
38910 */
38911 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38912   int rc;                          /* Return code */
38913   int nMaster;                     /* Length of string zMaster */
38914   i64 iHdrOff;                     /* Offset of header in journal file */
38915   i64 jrnlSize;                    /* Size of journal file on disk */
38916   u32 cksum = 0;                   /* Checksum of string zMaster */
38917
38918   assert( pPager->setMaster==0 );
38919   assert( !pagerUseWal(pPager) );
38920
38921   if( !zMaster 
38922    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38923    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
38924   ){
38925     return SQLITE_OK;
38926   }
38927   pPager->setMaster = 1;
38928   assert( isOpen(pPager->jfd) );
38929   assert( pPager->journalHdr <= pPager->journalOff );
38930
38931   /* Calculate the length in bytes and the checksum of zMaster */
38932   for(nMaster=0; zMaster[nMaster]; nMaster++){
38933     cksum += zMaster[nMaster];
38934   }
38935
38936   /* If in full-sync mode, advance to the next disk sector before writing
38937   ** the master journal name. This is in case the previous page written to
38938   ** the journal has already been synced.
38939   */
38940   if( pPager->fullSync ){
38941     pPager->journalOff = journalHdrOffset(pPager);
38942   }
38943   iHdrOff = pPager->journalOff;
38944
38945   /* Write the master journal data to the end of the journal file. If
38946   ** an error occurs, return the error code to the caller.
38947   */
38948   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38949    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38950    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38951    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38952    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38953   ){
38954     return rc;
38955   }
38956   pPager->journalOff += (nMaster+20);
38957
38958   /* If the pager is in peristent-journal mode, then the physical 
38959   ** journal-file may extend past the end of the master-journal name
38960   ** and 8 bytes of magic data just written to the file. This is 
38961   ** dangerous because the code to rollback a hot-journal file
38962   ** will not be able to find the master-journal name to determine 
38963   ** whether or not the journal is hot. 
38964   **
38965   ** Easiest thing to do in this scenario is to truncate the journal 
38966   ** file to the required size.
38967   */ 
38968   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38969    && jrnlSize>pPager->journalOff
38970   ){
38971     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38972   }
38973   return rc;
38974 }
38975
38976 /*
38977 ** Find a page in the hash table given its page number. Return
38978 ** a pointer to the page or NULL if the requested page is not 
38979 ** already in memory.
38980 */
38981 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38982   PgHdr *p;                         /* Return value */
38983
38984   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38985   ** fail, since no attempt to allocate dynamic memory will be made.
38986   */
38987   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38988   return p;
38989 }
38990
38991 /*
38992 ** Discard the entire contents of the in-memory page-cache.
38993 */
38994 static void pager_reset(Pager *pPager){
38995   sqlite3BackupRestart(pPager->pBackup);
38996   sqlite3PcacheClear(pPager->pPCache);
38997 }
38998
38999 /*
39000 ** Free all structures in the Pager.aSavepoint[] array and set both
39001 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
39002 ** if it is open and the pager is not in exclusive mode.
39003 */
39004 static void releaseAllSavepoints(Pager *pPager){
39005   int ii;               /* Iterator for looping through Pager.aSavepoint */
39006   for(ii=0; ii<pPager->nSavepoint; ii++){
39007     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39008   }
39009   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
39010     sqlite3OsClose(pPager->sjfd);
39011   }
39012   sqlite3_free(pPager->aSavepoint);
39013   pPager->aSavepoint = 0;
39014   pPager->nSavepoint = 0;
39015   pPager->nSubRec = 0;
39016 }
39017
39018 /*
39019 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
39020 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
39021 ** or SQLITE_NOMEM if a malloc failure occurs.
39022 */
39023 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
39024   int ii;                   /* Loop counter */
39025   int rc = SQLITE_OK;       /* Result code */
39026
39027   for(ii=0; ii<pPager->nSavepoint; ii++){
39028     PagerSavepoint *p = &pPager->aSavepoint[ii];
39029     if( pgno<=p->nOrig ){
39030       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
39031       testcase( rc==SQLITE_NOMEM );
39032       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39033     }
39034   }
39035   return rc;
39036 }
39037
39038 /*
39039 ** This function is a no-op if the pager is in exclusive mode and not
39040 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
39041 ** state.
39042 **
39043 ** If the pager is not in exclusive-access mode, the database file is
39044 ** completely unlocked. If the file is unlocked and the file-system does
39045 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
39046 ** closed (if it is open).
39047 **
39048 ** If the pager is in ERROR state when this function is called, the 
39049 ** contents of the pager cache are discarded before switching back to 
39050 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
39051 ** or not, any journal file left in the file-system will be treated
39052 ** as a hot-journal and rolled back the next time a read-transaction
39053 ** is opened (by this or by any other connection).
39054 */
39055 static void pager_unlock(Pager *pPager){
39056
39057   assert( pPager->eState==PAGER_READER 
39058        || pPager->eState==PAGER_OPEN 
39059        || pPager->eState==PAGER_ERROR 
39060   );
39061
39062   sqlite3BitvecDestroy(pPager->pInJournal);
39063   pPager->pInJournal = 0;
39064   releaseAllSavepoints(pPager);
39065
39066   if( pagerUseWal(pPager) ){
39067     assert( !isOpen(pPager->jfd) );
39068     sqlite3WalEndReadTransaction(pPager->pWal);
39069     pPager->eState = PAGER_OPEN;
39070   }else if( !pPager->exclusiveMode ){
39071     int rc;                       /* Error code returned by pagerUnlockDb() */
39072     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
39073
39074     /* If the operating system support deletion of open files, then
39075     ** close the journal file when dropping the database lock.  Otherwise
39076     ** another connection with journal_mode=delete might delete the file
39077     ** out from under us.
39078     */
39079     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
39080     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
39081     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
39082     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
39083     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39084     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
39085     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
39086      || 1!=(pPager->journalMode & 5)
39087     ){
39088       sqlite3OsClose(pPager->jfd);
39089     }
39090
39091     /* If the pager is in the ERROR state and the call to unlock the database
39092     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
39093     ** above the #define for UNKNOWN_LOCK for an explanation of why this
39094     ** is necessary.
39095     */
39096     rc = pagerUnlockDb(pPager, NO_LOCK);
39097     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
39098       pPager->eLock = UNKNOWN_LOCK;
39099     }
39100
39101     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
39102     ** without clearing the error code. This is intentional - the error
39103     ** code is cleared and the cache reset in the block below.
39104     */
39105     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
39106     pPager->changeCountDone = 0;
39107     pPager->eState = PAGER_OPEN;
39108   }
39109
39110   /* If Pager.errCode is set, the contents of the pager cache cannot be
39111   ** trusted. Now that there are no outstanding references to the pager,
39112   ** it can safely move back to PAGER_OPEN state. This happens in both
39113   ** normal and exclusive-locking mode.
39114   */
39115   if( pPager->errCode ){
39116     assert( !MEMDB );
39117     pager_reset(pPager);
39118     pPager->changeCountDone = pPager->tempFile;
39119     pPager->eState = PAGER_OPEN;
39120     pPager->errCode = SQLITE_OK;
39121   }
39122
39123   pPager->journalOff = 0;
39124   pPager->journalHdr = 0;
39125   pPager->setMaster = 0;
39126 }
39127
39128 /*
39129 ** This function is called whenever an IOERR or FULL error that requires
39130 ** the pager to transition into the ERROR state may ahve occurred.
39131 ** The first argument is a pointer to the pager structure, the second 
39132 ** the error-code about to be returned by a pager API function. The 
39133 ** value returned is a copy of the second argument to this function. 
39134 **
39135 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
39136 ** IOERR sub-codes, the pager enters the ERROR state and the error code
39137 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
39138 ** all major API calls on the Pager will immediately return Pager.errCode.
39139 **
39140 ** The ERROR state indicates that the contents of the pager-cache 
39141 ** cannot be trusted. This state can be cleared by completely discarding 
39142 ** the contents of the pager-cache. If a transaction was active when
39143 ** the persistent error occurred, then the rollback journal may need
39144 ** to be replayed to restore the contents of the database file (as if
39145 ** it were a hot-journal).
39146 */
39147 static int pager_error(Pager *pPager, int rc){
39148   int rc2 = rc & 0xff;
39149   assert( rc==SQLITE_OK || !MEMDB );
39150   assert(
39151        pPager->errCode==SQLITE_FULL ||
39152        pPager->errCode==SQLITE_OK ||
39153        (pPager->errCode & 0xff)==SQLITE_IOERR
39154   );
39155   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
39156     pPager->errCode = rc;
39157     pPager->eState = PAGER_ERROR;
39158   }
39159   return rc;
39160 }
39161
39162 /*
39163 ** This routine ends a transaction. A transaction is usually ended by 
39164 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
39165 ** after rollback of a hot-journal, or if an error occurs while opening
39166 ** the journal file or writing the very first journal-header of a
39167 ** database transaction.
39168 ** 
39169 ** This routine is never called in PAGER_ERROR state. If it is called
39170 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
39171 ** exclusive than a RESERVED lock, it is a no-op.
39172 **
39173 ** Otherwise, any active savepoints are released.
39174 **
39175 ** If the journal file is open, then it is "finalized". Once a journal 
39176 ** file has been finalized it is not possible to use it to roll back a 
39177 ** transaction. Nor will it be considered to be a hot-journal by this
39178 ** or any other database connection. Exactly how a journal is finalized
39179 ** depends on whether or not the pager is running in exclusive mode and
39180 ** the current journal-mode (Pager.journalMode value), as follows:
39181 **
39182 **   journalMode==MEMORY
39183 **     Journal file descriptor is simply closed. This destroys an 
39184 **     in-memory journal.
39185 **
39186 **   journalMode==TRUNCATE
39187 **     Journal file is truncated to zero bytes in size.
39188 **
39189 **   journalMode==PERSIST
39190 **     The first 28 bytes of the journal file are zeroed. This invalidates
39191 **     the first journal header in the file, and hence the entire journal
39192 **     file. An invalid journal file cannot be rolled back.
39193 **
39194 **   journalMode==DELETE
39195 **     The journal file is closed and deleted using sqlite3OsDelete().
39196 **
39197 **     If the pager is running in exclusive mode, this method of finalizing
39198 **     the journal file is never used. Instead, if the journalMode is
39199 **     DELETE and the pager is in exclusive mode, the method described under
39200 **     journalMode==PERSIST is used instead.
39201 **
39202 ** After the journal is finalized, the pager moves to PAGER_READER state.
39203 ** If running in non-exclusive rollback mode, the lock on the file is 
39204 ** downgraded to a SHARED_LOCK.
39205 **
39206 ** SQLITE_OK is returned if no error occurs. If an error occurs during
39207 ** any of the IO operations to finalize the journal file or unlock the
39208 ** database then the IO error code is returned to the user. If the 
39209 ** operation to finalize the journal file fails, then the code still
39210 ** tries to unlock the database file if not in exclusive mode. If the
39211 ** unlock operation fails as well, then the first error code related
39212 ** to the first error encountered (the journal finalization one) is
39213 ** returned.
39214 */
39215 static int pager_end_transaction(Pager *pPager, int hasMaster){
39216   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
39217   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
39218
39219   /* Do nothing if the pager does not have an open write transaction
39220   ** or at least a RESERVED lock. This function may be called when there
39221   ** is no write-transaction active but a RESERVED or greater lock is
39222   ** held under two circumstances:
39223   **
39224   **   1. After a successful hot-journal rollback, it is called with
39225   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
39226   **
39227   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
39228   **      lock switches back to locking_mode=normal and then executes a
39229   **      read-transaction, this function is called with eState==PAGER_READER 
39230   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
39231   */
39232   assert( assert_pager_state(pPager) );
39233   assert( pPager->eState!=PAGER_ERROR );
39234   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
39235     return SQLITE_OK;
39236   }
39237
39238   releaseAllSavepoints(pPager);
39239   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
39240   if( isOpen(pPager->jfd) ){
39241     assert( !pagerUseWal(pPager) );
39242
39243     /* Finalize the journal file. */
39244     if( sqlite3IsMemJournal(pPager->jfd) ){
39245       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
39246       sqlite3OsClose(pPager->jfd);
39247     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
39248       if( pPager->journalOff==0 ){
39249         rc = SQLITE_OK;
39250       }else{
39251         rc = sqlite3OsTruncate(pPager->jfd, 0);
39252       }
39253       pPager->journalOff = 0;
39254     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39255       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
39256     ){
39257       rc = zeroJournalHdr(pPager, hasMaster);
39258       pPager->journalOff = 0;
39259     }else{
39260       /* This branch may be executed with Pager.journalMode==MEMORY if
39261       ** a hot-journal was just rolled back. In this case the journal
39262       ** file should be closed and deleted. If this connection writes to
39263       ** the database file, it will do so using an in-memory journal. 
39264       */
39265       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
39266       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
39267            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
39268            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
39269       );
39270       sqlite3OsClose(pPager->jfd);
39271       if( bDelete ){
39272         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39273       }
39274     }
39275   }
39276
39277 #ifdef SQLITE_CHECK_PAGES
39278   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
39279   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
39280     PgHdr *p = pager_lookup(pPager, 1);
39281     if( p ){
39282       p->pageHash = 0;
39283       sqlite3PagerUnref(p);
39284     }
39285   }
39286 #endif
39287
39288   sqlite3BitvecDestroy(pPager->pInJournal);
39289   pPager->pInJournal = 0;
39290   pPager->nRec = 0;
39291   sqlite3PcacheCleanAll(pPager->pPCache);
39292   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
39293
39294   if( pagerUseWal(pPager) ){
39295     /* Drop the WAL write-lock, if any. Also, if the connection was in 
39296     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
39297     ** lock held on the database file.
39298     */
39299     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
39300     assert( rc2==SQLITE_OK );
39301   }
39302   if( !pPager->exclusiveMode 
39303    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
39304   ){
39305     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
39306     pPager->changeCountDone = 0;
39307   }
39308   pPager->eState = PAGER_READER;
39309   pPager->setMaster = 0;
39310
39311   return (rc==SQLITE_OK?rc2:rc);
39312 }
39313
39314 /*
39315 ** Execute a rollback if a transaction is active and unlock the 
39316 ** database file. 
39317 **
39318 ** If the pager has already entered the ERROR state, do not attempt 
39319 ** the rollback at this time. Instead, pager_unlock() is called. The
39320 ** call to pager_unlock() will discard all in-memory pages, unlock
39321 ** the database file and move the pager back to OPEN state. If this 
39322 ** means that there is a hot-journal left in the file-system, the next 
39323 ** connection to obtain a shared lock on the pager (which may be this one) 
39324 ** will roll it back.
39325 **
39326 ** If the pager has not already entered the ERROR state, but an IO or
39327 ** malloc error occurs during a rollback, then this will itself cause 
39328 ** the pager to enter the ERROR state. Which will be cleared by the
39329 ** call to pager_unlock(), as described above.
39330 */
39331 static void pagerUnlockAndRollback(Pager *pPager){
39332   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
39333     assert( assert_pager_state(pPager) );
39334     if( pPager->eState>=PAGER_WRITER_LOCKED ){
39335       sqlite3BeginBenignMalloc();
39336       sqlite3PagerRollback(pPager);
39337       sqlite3EndBenignMalloc();
39338     }else if( !pPager->exclusiveMode ){
39339       assert( pPager->eState==PAGER_READER );
39340       pager_end_transaction(pPager, 0);
39341     }
39342   }
39343   pager_unlock(pPager);
39344 }
39345
39346 /*
39347 ** Parameter aData must point to a buffer of pPager->pageSize bytes
39348 ** of data. Compute and return a checksum based ont the contents of the 
39349 ** page of data and the current value of pPager->cksumInit.
39350 **
39351 ** This is not a real checksum. It is really just the sum of the 
39352 ** random initial value (pPager->cksumInit) and every 200th byte
39353 ** of the page data, starting with byte offset (pPager->pageSize%200).
39354 ** Each byte is interpreted as an 8-bit unsigned integer.
39355 **
39356 ** Changing the formula used to compute this checksum results in an
39357 ** incompatible journal file format.
39358 **
39359 ** If journal corruption occurs due to a power failure, the most likely 
39360 ** scenario is that one end or the other of the record will be changed. 
39361 ** It is much less likely that the two ends of the journal record will be
39362 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
39363 ** though fast and simple, catches the mostly likely kind of corruption.
39364 */
39365 static u32 pager_cksum(Pager *pPager, const u8 *aData){
39366   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
39367   int i = pPager->pageSize-200;          /* Loop counter */
39368   while( i>0 ){
39369     cksum += aData[i];
39370     i -= 200;
39371   }
39372   return cksum;
39373 }
39374
39375 /*
39376 ** Report the current page size and number of reserved bytes back
39377 ** to the codec.
39378 */
39379 #ifdef SQLITE_HAS_CODEC
39380 static void pagerReportSize(Pager *pPager){
39381   if( pPager->xCodecSizeChng ){
39382     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39383                            (int)pPager->nReserve);
39384   }
39385 }
39386 #else
39387 # define pagerReportSize(X)     /* No-op if we do not support a codec */
39388 #endif
39389
39390 /*
39391 ** Read a single page from either the journal file (if isMainJrnl==1) or
39392 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39393 ** The page begins at offset *pOffset into the file. The *pOffset
39394 ** value is increased to the start of the next page in the journal.
39395 **
39396 ** The main rollback journal uses checksums - the statement journal does 
39397 ** not.
39398 **
39399 ** If the page number of the page record read from the (sub-)journal file
39400 ** is greater than the current value of Pager.dbSize, then playback is
39401 ** skipped and SQLITE_OK is returned.
39402 **
39403 ** If pDone is not NULL, then it is a record of pages that have already
39404 ** been played back.  If the page at *pOffset has already been played back
39405 ** (if the corresponding pDone bit is set) then skip the playback.
39406 ** Make sure the pDone bit corresponding to the *pOffset page is set
39407 ** prior to returning.
39408 **
39409 ** If the page record is successfully read from the (sub-)journal file
39410 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39411 ** while reading the record from the (sub-)journal file or while writing
39412 ** to the database file, then the IO error code is returned. If data
39413 ** is successfully read from the (sub-)journal file but appears to be
39414 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39415 ** two circumstances:
39416 ** 
39417 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39418 **   * If the record is being rolled back from the main journal file
39419 **     and the checksum field does not match the record content.
39420 **
39421 ** Neither of these two scenarios are possible during a savepoint rollback.
39422 **
39423 ** If this is a savepoint rollback, then memory may have to be dynamically
39424 ** allocated by this function. If this is the case and an allocation fails,
39425 ** SQLITE_NOMEM is returned.
39426 */
39427 static int pager_playback_one_page(
39428   Pager *pPager,                /* The pager being played back */
39429   i64 *pOffset,                 /* Offset of record to playback */
39430   Bitvec *pDone,                /* Bitvec of pages already played back */
39431   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
39432   int isSavepnt                 /* True for a savepoint rollback */
39433 ){
39434   int rc;
39435   PgHdr *pPg;                   /* An existing page in the cache */
39436   Pgno pgno;                    /* The page number of a page in journal */
39437   u32 cksum;                    /* Checksum used for sanity checking */
39438   char *aData;                  /* Temporary storage for the page */
39439   sqlite3_file *jfd;            /* The file descriptor for the journal file */
39440   int isSynced;                 /* True if journal page is synced */
39441
39442   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
39443   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
39444   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
39445   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
39446
39447   aData = pPager->pTmpSpace;
39448   assert( aData );         /* Temp storage must have already been allocated */
39449   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39450
39451   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
39452   ** or savepoint rollback done at the request of the caller) or this is
39453   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39454   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39455   ** only reads from the main journal, not the sub-journal.
39456   */
39457   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39458        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39459   );
39460   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39461
39462   /* Read the page number and page data from the journal or sub-journal
39463   ** file. Return an error code to the caller if an IO error occurs.
39464   */
39465   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39466   rc = read32bits(jfd, *pOffset, &pgno);
39467   if( rc!=SQLITE_OK ) return rc;
39468   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39469   if( rc!=SQLITE_OK ) return rc;
39470   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39471
39472   /* Sanity checking on the page.  This is more important that I originally
39473   ** thought.  If a power failure occurs while the journal is being written,
39474   ** it could cause invalid data to be written into the journal.  We need to
39475   ** detect this invalid data (with high probability) and ignore it.
39476   */
39477   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39478     assert( !isSavepnt );
39479     return SQLITE_DONE;
39480   }
39481   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39482     return SQLITE_OK;
39483   }
39484   if( isMainJrnl ){
39485     rc = read32bits(jfd, (*pOffset)-4, &cksum);
39486     if( rc ) return rc;
39487     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39488       return SQLITE_DONE;
39489     }
39490   }
39491
39492   /* If this page has already been played by before during the current
39493   ** rollback, then don't bother to play it back again.
39494   */
39495   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39496     return rc;
39497   }
39498
39499   /* When playing back page 1, restore the nReserve setting
39500   */
39501   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39502     pPager->nReserve = ((u8*)aData)[20];
39503     pagerReportSize(pPager);
39504   }
39505
39506   /* If the pager is in CACHEMOD state, then there must be a copy of this
39507   ** page in the pager cache. In this case just update the pager cache,
39508   ** not the database file. The page is left marked dirty in this case.
39509   **
39510   ** An exception to the above rule: If the database is in no-sync mode
39511   ** and a page is moved during an incremental vacuum then the page may
39512   ** not be in the pager cache. Later: if a malloc() or IO error occurs
39513   ** during a Movepage() call, then the page may not be in the cache
39514   ** either. So the condition described in the above paragraph is not
39515   ** assert()able.
39516   **
39517   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39518   ** pager cache if it exists and the main file. The page is then marked 
39519   ** not dirty. Since this code is only executed in PAGER_OPEN state for
39520   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39521   ** if the pager is in OPEN state.
39522   **
39523   ** Ticket #1171:  The statement journal might contain page content that is
39524   ** different from the page content at the start of the transaction.
39525   ** This occurs when a page is changed prior to the start of a statement
39526   ** then changed again within the statement.  When rolling back such a
39527   ** statement we must not write to the original database unless we know
39528   ** for certain that original page contents are synced into the main rollback
39529   ** journal.  Otherwise, a power loss might leave modified data in the
39530   ** database file without an entry in the rollback journal that can
39531   ** restore the database to its original form.  Two conditions must be
39532   ** met before writing to the database files. (1) the database must be
39533   ** locked.  (2) we know that the original page content is fully synced
39534   ** in the main journal either because the page is not in cache or else
39535   ** the page is marked as needSync==0.
39536   **
39537   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
39538   ** is possible to fail a statement on a database that does not yet exist.
39539   ** Do not attempt to write if database file has never been opened.
39540   */
39541   if( pagerUseWal(pPager) ){
39542     pPg = 0;
39543   }else{
39544     pPg = pager_lookup(pPager, pgno);
39545   }
39546   assert( pPg || !MEMDB );
39547   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39548   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39549            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39550            (isMainJrnl?"main-journal":"sub-journal")
39551   ));
39552   if( isMainJrnl ){
39553     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39554   }else{
39555     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39556   }
39557   if( isOpen(pPager->fd)
39558    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39559    && isSynced
39560   ){
39561     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39562     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39563     assert( !pagerUseWal(pPager) );
39564     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39565     if( pgno>pPager->dbFileSize ){
39566       pPager->dbFileSize = pgno;
39567     }
39568     if( pPager->pBackup ){
39569       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39570       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39571       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39572     }
39573   }else if( !isMainJrnl && pPg==0 ){
39574     /* If this is a rollback of a savepoint and data was not written to
39575     ** the database and the page is not in-memory, there is a potential
39576     ** problem. When the page is next fetched by the b-tree layer, it 
39577     ** will be read from the database file, which may or may not be 
39578     ** current. 
39579     **
39580     ** There are a couple of different ways this can happen. All are quite
39581     ** obscure. When running in synchronous mode, this can only happen 
39582     ** if the page is on the free-list at the start of the transaction, then
39583     ** populated, then moved using sqlite3PagerMovepage().
39584     **
39585     ** The solution is to add an in-memory page to the cache containing
39586     ** the data just read from the sub-journal. Mark the page as dirty 
39587     ** and if the pager requires a journal-sync, then mark the page as 
39588     ** requiring a journal-sync before it is written.
39589     */
39590     assert( isSavepnt );
39591     assert( pPager->doNotSpill==0 );
39592     pPager->doNotSpill++;
39593     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39594     assert( pPager->doNotSpill==1 );
39595     pPager->doNotSpill--;
39596     if( rc!=SQLITE_OK ) return rc;
39597     pPg->flags &= ~PGHDR_NEED_READ;
39598     sqlite3PcacheMakeDirty(pPg);
39599   }
39600   if( pPg ){
39601     /* No page should ever be explicitly rolled back that is in use, except
39602     ** for page 1 which is held in use in order to keep the lock on the
39603     ** database active. However such a page may be rolled back as a result
39604     ** of an internal error resulting in an automatic call to
39605     ** sqlite3PagerRollback().
39606     */
39607     void *pData;
39608     pData = pPg->pData;
39609     memcpy(pData, (u8*)aData, pPager->pageSize);
39610     pPager->xReiniter(pPg);
39611     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39612       /* If the contents of this page were just restored from the main 
39613       ** journal file, then its content must be as they were when the 
39614       ** transaction was first opened. In this case we can mark the page
39615       ** as clean, since there will be no need to write it out to the
39616       ** database.
39617       **
39618       ** There is one exception to this rule. If the page is being rolled
39619       ** back as part of a savepoint (or statement) rollback from an 
39620       ** unsynced portion of the main journal file, then it is not safe
39621       ** to mark the page as clean. This is because marking the page as
39622       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39623       ** already in the journal file (recorded in Pager.pInJournal) and
39624       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39625       ** again within this transaction, it will be marked as dirty but
39626       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39627       ** be written out into the database file before its journal file
39628       ** segment is synced. If a crash occurs during or following this,
39629       ** database corruption may ensue.
39630       */
39631       assert( !pagerUseWal(pPager) );
39632       sqlite3PcacheMakeClean(pPg);
39633     }
39634     pager_set_pagehash(pPg);
39635
39636     /* If this was page 1, then restore the value of Pager.dbFileVers.
39637     ** Do this before any decoding. */
39638     if( pgno==1 ){
39639       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39640     }
39641
39642     /* Decode the page just read from disk */
39643     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39644     sqlite3PcacheRelease(pPg);
39645   }
39646   return rc;
39647 }
39648
39649 /*
39650 ** Parameter zMaster is the name of a master journal file. A single journal
39651 ** file that referred to the master journal file has just been rolled back.
39652 ** This routine checks if it is possible to delete the master journal file,
39653 ** and does so if it is.
39654 **
39655 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
39656 ** available for use within this function.
39657 **
39658 ** When a master journal file is created, it is populated with the names 
39659 ** of all of its child journals, one after another, formatted as utf-8 
39660 ** encoded text. The end of each child journal file is marked with a 
39661 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39662 ** file for a transaction involving two databases might be:
39663 **
39664 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39665 **
39666 ** A master journal file may only be deleted once all of its child 
39667 ** journals have been rolled back.
39668 **
39669 ** This function reads the contents of the master-journal file into 
39670 ** memory and loops through each of the child journal names. For
39671 ** each child journal, it checks if:
39672 **
39673 **   * if the child journal exists, and if so
39674 **   * if the child journal contains a reference to master journal 
39675 **     file zMaster
39676 **
39677 ** If a child journal can be found that matches both of the criteria
39678 ** above, this function returns without doing anything. Otherwise, if
39679 ** no such child journal can be found, file zMaster is deleted from
39680 ** the file-system using sqlite3OsDelete().
39681 **
39682 ** If an IO error within this function, an error code is returned. This
39683 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39684 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
39685 ** occur, SQLITE_OK is returned.
39686 **
39687 ** TODO: This function allocates a single block of memory to load
39688 ** the entire contents of the master journal file. This could be
39689 ** a couple of kilobytes or so - potentially larger than the page 
39690 ** size.
39691 */
39692 static int pager_delmaster(Pager *pPager, const char *zMaster){
39693   sqlite3_vfs *pVfs = pPager->pVfs;
39694   int rc;                   /* Return code */
39695   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39696   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39697   char *zMasterJournal = 0; /* Contents of master journal file */
39698   i64 nMasterJournal;       /* Size of master journal file */
39699   char *zJournal;           /* Pointer to one journal within MJ file */
39700   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39701   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39702
39703   /* Allocate space for both the pJournal and pMaster file descriptors.
39704   ** If successful, open the master journal file for reading.
39705   */
39706   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39707   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39708   if( !pMaster ){
39709     rc = SQLITE_NOMEM;
39710   }else{
39711     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39712     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39713   }
39714   if( rc!=SQLITE_OK ) goto delmaster_out;
39715
39716   /* Load the entire master journal file into space obtained from
39717   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39718   ** sufficient space (in zMasterPtr) to hold the names of master
39719   ** journal files extracted from regular rollback-journals.
39720   */
39721   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39722   if( rc!=SQLITE_OK ) goto delmaster_out;
39723   nMasterPtr = pVfs->mxPathname+1;
39724   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39725   if( !zMasterJournal ){
39726     rc = SQLITE_NOMEM;
39727     goto delmaster_out;
39728   }
39729   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39730   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39731   if( rc!=SQLITE_OK ) goto delmaster_out;
39732   zMasterJournal[nMasterJournal] = 0;
39733
39734   zJournal = zMasterJournal;
39735   while( (zJournal-zMasterJournal)<nMasterJournal ){
39736     int exists;
39737     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39738     if( rc!=SQLITE_OK ){
39739       goto delmaster_out;
39740     }
39741     if( exists ){
39742       /* One of the journals pointed to by the master journal exists.
39743       ** Open it and check if it points at the master journal. If
39744       ** so, return without deleting the master journal file.
39745       */
39746       int c;
39747       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39748       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39749       if( rc!=SQLITE_OK ){
39750         goto delmaster_out;
39751       }
39752
39753       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39754       sqlite3OsClose(pJournal);
39755       if( rc!=SQLITE_OK ){
39756         goto delmaster_out;
39757       }
39758
39759       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39760       if( c ){
39761         /* We have a match. Do not delete the master journal file. */
39762         goto delmaster_out;
39763       }
39764     }
39765     zJournal += (sqlite3Strlen30(zJournal)+1);
39766   }
39767  
39768   sqlite3OsClose(pMaster);
39769   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39770
39771 delmaster_out:
39772   sqlite3_free(zMasterJournal);
39773   if( pMaster ){
39774     sqlite3OsClose(pMaster);
39775     assert( !isOpen(pJournal) );
39776     sqlite3_free(pMaster);
39777   }
39778   return rc;
39779 }
39780
39781
39782 /*
39783 ** This function is used to change the actual size of the database 
39784 ** file in the file-system. This only happens when committing a transaction,
39785 ** or rolling back a transaction (including rolling back a hot-journal).
39786 **
39787 ** If the main database file is not open, or the pager is not in either
39788 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
39789 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
39790 ** If the file on disk is currently larger than nPage pages, then use the VFS
39791 ** xTruncate() method to truncate it.
39792 **
39793 ** Or, it might might be the case that the file on disk is smaller than 
39794 ** nPage pages. Some operating system implementations can get confused if 
39795 ** you try to truncate a file to some size that is larger than it 
39796 ** currently is, so detect this case and write a single zero byte to 
39797 ** the end of the new file instead.
39798 **
39799 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39800 ** the database file, return the error code to the caller.
39801 */
39802 static int pager_truncate(Pager *pPager, Pgno nPage){
39803   int rc = SQLITE_OK;
39804   assert( pPager->eState!=PAGER_ERROR );
39805   assert( pPager->eState!=PAGER_READER );
39806   
39807   if( isOpen(pPager->fd) 
39808    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
39809   ){
39810     i64 currentSize, newSize;
39811     int szPage = pPager->pageSize;
39812     assert( pPager->eLock==EXCLUSIVE_LOCK );
39813     /* TODO: Is it safe to use Pager.dbFileSize here? */
39814     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39815     newSize = szPage*(i64)nPage;
39816     if( rc==SQLITE_OK && currentSize!=newSize ){
39817       if( currentSize>newSize ){
39818         rc = sqlite3OsTruncate(pPager->fd, newSize);
39819       }else if( (currentSize+szPage)<=newSize ){
39820         char *pTmp = pPager->pTmpSpace;
39821         memset(pTmp, 0, szPage);
39822         testcase( (newSize-szPage) == currentSize );
39823         testcase( (newSize-szPage) >  currentSize );
39824         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39825       }
39826       if( rc==SQLITE_OK ){
39827         pPager->dbFileSize = nPage;
39828       }
39829     }
39830   }
39831   return rc;
39832 }
39833
39834 /*
39835 ** Return a sanitized version of the sector-size of OS file pFile. The
39836 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
39837 */
39838 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
39839   int iRet = sqlite3OsSectorSize(pFile);
39840   if( iRet<32 ){
39841     iRet = 512;
39842   }else if( iRet>MAX_SECTOR_SIZE ){
39843     assert( MAX_SECTOR_SIZE>=512 );
39844     iRet = MAX_SECTOR_SIZE;
39845   }
39846   return iRet;
39847 }
39848
39849 /*
39850 ** Set the value of the Pager.sectorSize variable for the given
39851 ** pager based on the value returned by the xSectorSize method
39852 ** of the open database file. The sector size will be used used 
39853 ** to determine the size and alignment of journal header and 
39854 ** master journal pointers within created journal files.
39855 **
39856 ** For temporary files the effective sector size is always 512 bytes.
39857 **
39858 ** Otherwise, for non-temporary files, the effective sector size is
39859 ** the value returned by the xSectorSize() method rounded up to 32 if
39860 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39861 ** is greater than MAX_SECTOR_SIZE.
39862 **
39863 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
39864 ** the effective sector size to its minimum value (512).  The purpose of
39865 ** pPager->sectorSize is to define the "blast radius" of bytes that
39866 ** might change if a crash occurs while writing to a single byte in
39867 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
39868 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
39869 ** size.  For backwards compatibility of the rollback journal file format,
39870 ** we cannot reduce the effective sector size below 512.
39871 */
39872 static void setSectorSize(Pager *pPager){
39873   assert( isOpen(pPager->fd) || pPager->tempFile );
39874
39875   if( pPager->tempFile
39876    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
39877               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
39878   ){
39879     /* Sector size doesn't matter for temporary files. Also, the file
39880     ** may not have been opened yet, in which case the OsSectorSize()
39881     ** call will segfault. */
39882     pPager->sectorSize = 512;
39883   }else{
39884     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
39885   }
39886 }
39887
39888 /*
39889 ** Playback the journal and thus restore the database file to
39890 ** the state it was in before we started making changes.  
39891 **
39892 ** The journal file format is as follows: 
39893 **
39894 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
39895 **  (2)  4 byte big-endian integer which is the number of valid page records
39896 **       in the journal.  If this value is 0xffffffff, then compute the
39897 **       number of page records from the journal size.
39898 **  (3)  4 byte big-endian integer which is the initial value for the 
39899 **       sanity checksum.
39900 **  (4)  4 byte integer which is the number of pages to truncate the
39901 **       database to during a rollback.
39902 **  (5)  4 byte big-endian integer which is the sector size.  The header
39903 **       is this many bytes in size.
39904 **  (6)  4 byte big-endian integer which is the page size.
39905 **  (7)  zero padding out to the next sector size.
39906 **  (8)  Zero or more pages instances, each as follows:
39907 **        +  4 byte page number.
39908 **        +  pPager->pageSize bytes of data.
39909 **        +  4 byte checksum
39910 **
39911 ** When we speak of the journal header, we mean the first 7 items above.
39912 ** Each entry in the journal is an instance of the 8th item.
39913 **
39914 ** Call the value from the second bullet "nRec".  nRec is the number of
39915 ** valid page entries in the journal.  In most cases, you can compute the
39916 ** value of nRec from the size of the journal file.  But if a power
39917 ** failure occurred while the journal was being written, it could be the
39918 ** case that the size of the journal file had already been increased but
39919 ** the extra entries had not yet made it safely to disk.  In such a case,
39920 ** the value of nRec computed from the file size would be too large.  For
39921 ** that reason, we always use the nRec value in the header.
39922 **
39923 ** If the nRec value is 0xffffffff it means that nRec should be computed
39924 ** from the file size.  This value is used when the user selects the
39925 ** no-sync option for the journal.  A power failure could lead to corruption
39926 ** in this case.  But for things like temporary table (which will be
39927 ** deleted when the power is restored) we don't care.  
39928 **
39929 ** If the file opened as the journal file is not a well-formed
39930 ** journal file then all pages up to the first corrupted page are rolled
39931 ** back (or no pages if the journal header is corrupted). The journal file
39932 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39933 ** been encountered.
39934 **
39935 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39936 ** and an error code is returned.
39937 **
39938 ** The isHot parameter indicates that we are trying to rollback a journal
39939 ** that might be a hot journal.  Or, it could be that the journal is 
39940 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39941 ** If the journal really is hot, reset the pager cache prior rolling
39942 ** back any content.  If the journal is merely persistent, no reset is
39943 ** needed.
39944 */
39945 static int pager_playback(Pager *pPager, int isHot){
39946   sqlite3_vfs *pVfs = pPager->pVfs;
39947   i64 szJ;                 /* Size of the journal file in bytes */
39948   u32 nRec;                /* Number of Records in the journal */
39949   u32 u;                   /* Unsigned loop counter */
39950   Pgno mxPg = 0;           /* Size of the original file in pages */
39951   int rc;                  /* Result code of a subroutine */
39952   int res = 1;             /* Value returned by sqlite3OsAccess() */
39953   char *zMaster = 0;       /* Name of master journal file if any */
39954   int needPagerReset;      /* True to reset page prior to first page rollback */
39955
39956   /* Figure out how many records are in the journal.  Abort early if
39957   ** the journal is empty.
39958   */
39959   assert( isOpen(pPager->jfd) );
39960   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39961   if( rc!=SQLITE_OK ){
39962     goto end_playback;
39963   }
39964
39965   /* Read the master journal name from the journal, if it is present.
39966   ** If a master journal file name is specified, but the file is not
39967   ** present on disk, then the journal is not hot and does not need to be
39968   ** played back.
39969   **
39970   ** TODO: Technically the following is an error because it assumes that
39971   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39972   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39973   **  mxPathname is 512, which is the same as the minimum allowable value
39974   ** for pageSize.
39975   */
39976   zMaster = pPager->pTmpSpace;
39977   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39978   if( rc==SQLITE_OK && zMaster[0] ){
39979     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39980   }
39981   zMaster = 0;
39982   if( rc!=SQLITE_OK || !res ){
39983     goto end_playback;
39984   }
39985   pPager->journalOff = 0;
39986   needPagerReset = isHot;
39987
39988   /* This loop terminates either when a readJournalHdr() or 
39989   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
39990   ** occurs. 
39991   */
39992   while( 1 ){
39993     /* Read the next journal header from the journal file.  If there are
39994     ** not enough bytes left in the journal file for a complete header, or
39995     ** it is corrupted, then a process must have failed while writing it.
39996     ** This indicates nothing more needs to be rolled back.
39997     */
39998     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39999     if( rc!=SQLITE_OK ){ 
40000       if( rc==SQLITE_DONE ){
40001         rc = SQLITE_OK;
40002       }
40003       goto end_playback;
40004     }
40005
40006     /* If nRec is 0xffffffff, then this journal was created by a process
40007     ** working in no-sync mode. This means that the rest of the journal
40008     ** file consists of pages, there are no more journal headers. Compute
40009     ** the value of nRec based on this assumption.
40010     */
40011     if( nRec==0xffffffff ){
40012       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
40013       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
40014     }
40015
40016     /* If nRec is 0 and this rollback is of a transaction created by this
40017     ** process and if this is the final header in the journal, then it means
40018     ** that this part of the journal was being filled but has not yet been
40019     ** synced to disk.  Compute the number of pages based on the remaining
40020     ** size of the file.
40021     **
40022     ** The third term of the test was added to fix ticket #2565.
40023     ** When rolling back a hot journal, nRec==0 always means that the next
40024     ** chunk of the journal contains zero pages to be rolled back.  But
40025     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
40026     ** the journal, it means that the journal might contain additional
40027     ** pages that need to be rolled back and that the number of pages 
40028     ** should be computed based on the journal file size.
40029     */
40030     if( nRec==0 && !isHot &&
40031         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
40032       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
40033     }
40034
40035     /* If this is the first header read from the journal, truncate the
40036     ** database file back to its original size.
40037     */
40038     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
40039       rc = pager_truncate(pPager, mxPg);
40040       if( rc!=SQLITE_OK ){
40041         goto end_playback;
40042       }
40043       pPager->dbSize = mxPg;
40044     }
40045
40046     /* Copy original pages out of the journal and back into the 
40047     ** database file and/or page cache.
40048     */
40049     for(u=0; u<nRec; u++){
40050       if( needPagerReset ){
40051         pager_reset(pPager);
40052         needPagerReset = 0;
40053       }
40054       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
40055       if( rc!=SQLITE_OK ){
40056         if( rc==SQLITE_DONE ){
40057           pPager->journalOff = szJ;
40058           break;
40059         }else if( rc==SQLITE_IOERR_SHORT_READ ){
40060           /* If the journal has been truncated, simply stop reading and
40061           ** processing the journal. This might happen if the journal was
40062           ** not completely written and synced prior to a crash.  In that
40063           ** case, the database should have never been written in the
40064           ** first place so it is OK to simply abandon the rollback. */
40065           rc = SQLITE_OK;
40066           goto end_playback;
40067         }else{
40068           /* If we are unable to rollback, quit and return the error
40069           ** code.  This will cause the pager to enter the error state
40070           ** so that no further harm will be done.  Perhaps the next
40071           ** process to come along will be able to rollback the database.
40072           */
40073           goto end_playback;
40074         }
40075       }
40076     }
40077   }
40078   /*NOTREACHED*/
40079   assert( 0 );
40080
40081 end_playback:
40082   /* Following a rollback, the database file should be back in its original
40083   ** state prior to the start of the transaction, so invoke the
40084   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
40085   ** assertion that the transaction counter was modified.
40086   */
40087 #ifdef SQLITE_DEBUG
40088   if( pPager->fd->pMethods ){
40089     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
40090   }
40091 #endif
40092
40093   /* If this playback is happening automatically as a result of an IO or 
40094   ** malloc error that occurred after the change-counter was updated but 
40095   ** before the transaction was committed, then the change-counter 
40096   ** modification may just have been reverted. If this happens in exclusive 
40097   ** mode, then subsequent transactions performed by the connection will not
40098   ** update the change-counter at all. This may lead to cache inconsistency
40099   ** problems for other processes at some point in the future. So, just
40100   ** in case this has happened, clear the changeCountDone flag now.
40101   */
40102   pPager->changeCountDone = pPager->tempFile;
40103
40104   if( rc==SQLITE_OK ){
40105     zMaster = pPager->pTmpSpace;
40106     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40107     testcase( rc!=SQLITE_OK );
40108   }
40109   if( rc==SQLITE_OK
40110    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40111   ){
40112     rc = sqlite3PagerSync(pPager);
40113   }
40114   if( rc==SQLITE_OK ){
40115     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
40116     testcase( rc!=SQLITE_OK );
40117   }
40118   if( rc==SQLITE_OK && zMaster[0] && res ){
40119     /* If there was a master journal and this routine will return success,
40120     ** see if it is possible to delete the master journal.
40121     */
40122     rc = pager_delmaster(pPager, zMaster);
40123     testcase( rc!=SQLITE_OK );
40124   }
40125
40126   /* The Pager.sectorSize variable may have been updated while rolling
40127   ** back a journal created by a process with a different sector size
40128   ** value. Reset it to the correct value for this process.
40129   */
40130   setSectorSize(pPager);
40131   return rc;
40132 }
40133
40134
40135 /*
40136 ** Read the content for page pPg out of the database file and into 
40137 ** pPg->pData. A shared lock or greater must be held on the database
40138 ** file before this function is called.
40139 **
40140 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
40141 ** the value read from the database file.
40142 **
40143 ** If an IO error occurs, then the IO error is returned to the caller.
40144 ** Otherwise, SQLITE_OK is returned.
40145 */
40146 static int readDbPage(PgHdr *pPg){
40147   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
40148   Pgno pgno = pPg->pgno;       /* Page number to read */
40149   int rc = SQLITE_OK;          /* Return code */
40150   int isInWal = 0;             /* True if page is in log file */
40151   int pgsz = pPager->pageSize; /* Number of bytes to read */
40152
40153   assert( pPager->eState>=PAGER_READER && !MEMDB );
40154   assert( isOpen(pPager->fd) );
40155
40156   if( NEVER(!isOpen(pPager->fd)) ){
40157     assert( pPager->tempFile );
40158     memset(pPg->pData, 0, pPager->pageSize);
40159     return SQLITE_OK;
40160   }
40161
40162   if( pagerUseWal(pPager) ){
40163     /* Try to pull the page from the write-ahead log. */
40164     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
40165   }
40166   if( rc==SQLITE_OK && !isInWal ){
40167     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
40168     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
40169     if( rc==SQLITE_IOERR_SHORT_READ ){
40170       rc = SQLITE_OK;
40171     }
40172   }
40173
40174   if( pgno==1 ){
40175     if( rc ){
40176       /* If the read is unsuccessful, set the dbFileVers[] to something
40177       ** that will never be a valid file version.  dbFileVers[] is a copy
40178       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
40179       ** zero or the size of the database in page. Bytes 32..35 and 35..39
40180       ** should be page numbers which are never 0xffffffff.  So filling
40181       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
40182       **
40183       ** For an encrypted database, the situation is more complex:  bytes
40184       ** 24..39 of the database are white noise.  But the probability of
40185       ** white noising equaling 16 bytes of 0xff is vanishingly small so
40186       ** we should still be ok.
40187       */
40188       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
40189     }else{
40190       u8 *dbFileVers = &((u8*)pPg->pData)[24];
40191       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
40192     }
40193   }
40194   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
40195
40196   PAGER_INCR(sqlite3_pager_readdb_count);
40197   PAGER_INCR(pPager->nRead);
40198   IOTRACE(("PGIN %p %d\n", pPager, pgno));
40199   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
40200                PAGERID(pPager), pgno, pager_pagehash(pPg)));
40201
40202   return rc;
40203 }
40204
40205 /*
40206 ** Update the value of the change-counter at offsets 24 and 92 in
40207 ** the header and the sqlite version number at offset 96.
40208 **
40209 ** This is an unconditional update.  See also the pager_incr_changecounter()
40210 ** routine which only updates the change-counter if the update is actually
40211 ** needed, as determined by the pPager->changeCountDone state variable.
40212 */
40213 static void pager_write_changecounter(PgHdr *pPg){
40214   u32 change_counter;
40215
40216   /* Increment the value just read and write it back to byte 24. */
40217   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
40218   put32bits(((char*)pPg->pData)+24, change_counter);
40219
40220   /* Also store the SQLite version number in bytes 96..99 and in
40221   ** bytes 92..95 store the change counter for which the version number
40222   ** is valid. */
40223   put32bits(((char*)pPg->pData)+92, change_counter);
40224   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
40225 }
40226
40227 #ifndef SQLITE_OMIT_WAL
40228 /*
40229 ** This function is invoked once for each page that has already been 
40230 ** written into the log file when a WAL transaction is rolled back.
40231 ** Parameter iPg is the page number of said page. The pCtx argument 
40232 ** is actually a pointer to the Pager structure.
40233 **
40234 ** If page iPg is present in the cache, and has no outstanding references,
40235 ** it is discarded. Otherwise, if there are one or more outstanding
40236 ** references, the page content is reloaded from the database. If the
40237 ** attempt to reload content from the database is required and fails, 
40238 ** return an SQLite error code. Otherwise, SQLITE_OK.
40239 */
40240 static int pagerUndoCallback(void *pCtx, Pgno iPg){
40241   int rc = SQLITE_OK;
40242   Pager *pPager = (Pager *)pCtx;
40243   PgHdr *pPg;
40244
40245   pPg = sqlite3PagerLookup(pPager, iPg);
40246   if( pPg ){
40247     if( sqlite3PcachePageRefcount(pPg)==1 ){
40248       sqlite3PcacheDrop(pPg);
40249     }else{
40250       rc = readDbPage(pPg);
40251       if( rc==SQLITE_OK ){
40252         pPager->xReiniter(pPg);
40253       }
40254       sqlite3PagerUnref(pPg);
40255     }
40256   }
40257
40258   /* Normally, if a transaction is rolled back, any backup processes are
40259   ** updated as data is copied out of the rollback journal and into the
40260   ** database. This is not generally possible with a WAL database, as
40261   ** rollback involves simply truncating the log file. Therefore, if one
40262   ** or more frames have already been written to the log (and therefore 
40263   ** also copied into the backup databases) as part of this transaction,
40264   ** the backups must be restarted.
40265   */
40266   sqlite3BackupRestart(pPager->pBackup);
40267
40268   return rc;
40269 }
40270
40271 /*
40272 ** This function is called to rollback a transaction on a WAL database.
40273 */
40274 static int pagerRollbackWal(Pager *pPager){
40275   int rc;                         /* Return Code */
40276   PgHdr *pList;                   /* List of dirty pages to revert */
40277
40278   /* For all pages in the cache that are currently dirty or have already
40279   ** been written (but not committed) to the log file, do one of the 
40280   ** following:
40281   **
40282   **   + Discard the cached page (if refcount==0), or
40283   **   + Reload page content from the database (if refcount>0).
40284   */
40285   pPager->dbSize = pPager->dbOrigSize;
40286   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
40287   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40288   while( pList && rc==SQLITE_OK ){
40289     PgHdr *pNext = pList->pDirty;
40290     rc = pagerUndoCallback((void *)pPager, pList->pgno);
40291     pList = pNext;
40292   }
40293
40294   return rc;
40295 }
40296
40297 /*
40298 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
40299 ** the contents of the list of pages headed by pList (connected by pDirty),
40300 ** this function notifies any active backup processes that the pages have
40301 ** changed. 
40302 **
40303 ** The list of pages passed into this routine is always sorted by page number.
40304 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
40305 */ 
40306 static int pagerWalFrames(
40307   Pager *pPager,                  /* Pager object */
40308   PgHdr *pList,                   /* List of frames to log */
40309   Pgno nTruncate,                 /* Database size after this commit */
40310   int isCommit                    /* True if this is a commit */
40311 ){
40312   int rc;                         /* Return code */
40313   int nList;                      /* Number of pages in pList */
40314 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
40315   PgHdr *p;                       /* For looping over pages */
40316 #endif
40317
40318   assert( pPager->pWal );
40319   assert( pList );
40320 #ifdef SQLITE_DEBUG
40321   /* Verify that the page list is in accending order */
40322   for(p=pList; p && p->pDirty; p=p->pDirty){
40323     assert( p->pgno < p->pDirty->pgno );
40324   }
40325 #endif
40326
40327   assert( pList->pDirty==0 || isCommit );
40328   if( isCommit ){
40329     /* If a WAL transaction is being committed, there is no point in writing
40330     ** any pages with page numbers greater than nTruncate into the WAL file.
40331     ** They will never be read by any client. So remove them from the pDirty
40332     ** list here. */
40333     PgHdr *p;
40334     PgHdr **ppNext = &pList;
40335     nList = 0;
40336     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
40337       if( p->pgno<=nTruncate ){
40338         ppNext = &p->pDirty;
40339         nList++;
40340       }
40341     }
40342     assert( pList );
40343   }else{
40344     nList = 1;
40345   }
40346   pPager->aStat[PAGER_STAT_WRITE] += nList;
40347
40348   if( pList->pgno==1 ) pager_write_changecounter(pList);
40349   rc = sqlite3WalFrames(pPager->pWal, 
40350       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
40351   );
40352   if( rc==SQLITE_OK && pPager->pBackup ){
40353     PgHdr *p;
40354     for(p=pList; p; p=p->pDirty){
40355       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
40356     }
40357   }
40358
40359 #ifdef SQLITE_CHECK_PAGES
40360   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40361   for(p=pList; p; p=p->pDirty){
40362     pager_set_pagehash(p);
40363   }
40364 #endif
40365
40366   return rc;
40367 }
40368
40369 /*
40370 ** Begin a read transaction on the WAL.
40371 **
40372 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
40373 ** makes a snapshot of the database at the current point in time and preserves
40374 ** that snapshot for use by the reader in spite of concurrently changes by
40375 ** other writers or checkpointers.
40376 */
40377 static int pagerBeginReadTransaction(Pager *pPager){
40378   int rc;                         /* Return code */
40379   int changed = 0;                /* True if cache must be reset */
40380
40381   assert( pagerUseWal(pPager) );
40382   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40383
40384   /* sqlite3WalEndReadTransaction() was not called for the previous
40385   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
40386   ** are in locking_mode=NORMAL and EndRead() was previously called,
40387   ** the duplicate call is harmless.
40388   */
40389   sqlite3WalEndReadTransaction(pPager->pWal);
40390
40391   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40392   if( rc!=SQLITE_OK || changed ){
40393     pager_reset(pPager);
40394   }
40395
40396   return rc;
40397 }
40398 #endif
40399
40400 /*
40401 ** This function is called as part of the transition from PAGER_OPEN
40402 ** to PAGER_READER state to determine the size of the database file
40403 ** in pages (assuming the page size currently stored in Pager.pageSize).
40404 **
40405 ** If no error occurs, SQLITE_OK is returned and the size of the database
40406 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40407 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40408 */
40409 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40410   Pgno nPage;                     /* Value to return via *pnPage */
40411
40412   /* Query the WAL sub-system for the database size. The WalDbsize()
40413   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40414   ** if the database size is not available. The database size is not
40415   ** available from the WAL sub-system if the log file is empty or
40416   ** contains no valid committed transactions.
40417   */
40418   assert( pPager->eState==PAGER_OPEN );
40419   assert( pPager->eLock>=SHARED_LOCK );
40420   nPage = sqlite3WalDbsize(pPager->pWal);
40421
40422   /* If the database size was not available from the WAL sub-system,
40423   ** determine it based on the size of the database file. If the size
40424   ** of the database file is not an integer multiple of the page-size,
40425   ** round down to the nearest page. Except, any file larger than 0
40426   ** bytes in size is considered to contain at least one page.
40427   */
40428   if( nPage==0 ){
40429     i64 n = 0;                    /* Size of db file in bytes */
40430     assert( isOpen(pPager->fd) || pPager->tempFile );
40431     if( isOpen(pPager->fd) ){
40432       int rc = sqlite3OsFileSize(pPager->fd, &n);
40433       if( rc!=SQLITE_OK ){
40434         return rc;
40435       }
40436     }
40437     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
40438   }
40439
40440   /* If the current number of pages in the file is greater than the
40441   ** configured maximum pager number, increase the allowed limit so
40442   ** that the file can be read.
40443   */
40444   if( nPage>pPager->mxPgno ){
40445     pPager->mxPgno = (Pgno)nPage;
40446   }
40447
40448   *pnPage = nPage;
40449   return SQLITE_OK;
40450 }
40451
40452 #ifndef SQLITE_OMIT_WAL
40453 /*
40454 ** Check if the *-wal file that corresponds to the database opened by pPager
40455 ** exists if the database is not empy, or verify that the *-wal file does
40456 ** not exist (by deleting it) if the database file is empty.
40457 **
40458 ** If the database is not empty and the *-wal file exists, open the pager
40459 ** in WAL mode.  If the database is empty or if no *-wal file exists and
40460 ** if no error occurs, make sure Pager.journalMode is not set to
40461 ** PAGER_JOURNALMODE_WAL.
40462 **
40463 ** Return SQLITE_OK or an error code.
40464 **
40465 ** The caller must hold a SHARED lock on the database file to call this
40466 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
40467 ** a WAL on a none-empty database, this ensures there is no race condition 
40468 ** between the xAccess() below and an xDelete() being executed by some 
40469 ** other connection.
40470 */
40471 static int pagerOpenWalIfPresent(Pager *pPager){
40472   int rc = SQLITE_OK;
40473   assert( pPager->eState==PAGER_OPEN );
40474   assert( pPager->eLock>=SHARED_LOCK );
40475
40476   if( !pPager->tempFile ){
40477     int isWal;                    /* True if WAL file exists */
40478     Pgno nPage;                   /* Size of the database file */
40479
40480     rc = pagerPagecount(pPager, &nPage);
40481     if( rc ) return rc;
40482     if( nPage==0 ){
40483       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40484       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
40485       isWal = 0;
40486     }else{
40487       rc = sqlite3OsAccess(
40488           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40489       );
40490     }
40491     if( rc==SQLITE_OK ){
40492       if( isWal ){
40493         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40494         rc = sqlite3PagerOpenWal(pPager, 0);
40495       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40496         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40497       }
40498     }
40499   }
40500   return rc;
40501 }
40502 #endif
40503
40504 /*
40505 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40506 ** the entire master journal file. The case pSavepoint==NULL occurs when 
40507 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
40508 ** savepoint.
40509 **
40510 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
40511 ** being rolled back), then the rollback consists of up to three stages,
40512 ** performed in the order specified:
40513 **
40514 **   * Pages are played back from the main journal starting at byte
40515 **     offset PagerSavepoint.iOffset and continuing to 
40516 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
40517 **     file if PagerSavepoint.iHdrOffset is zero.
40518 **
40519 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40520 **     back starting from the journal header immediately following 
40521 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
40522 **
40523 **   * Pages are then played back from the sub-journal file, starting
40524 **     with the PagerSavepoint.iSubRec and continuing to the end of
40525 **     the journal file.
40526 **
40527 ** Throughout the rollback process, each time a page is rolled back, the
40528 ** corresponding bit is set in a bitvec structure (variable pDone in the
40529 ** implementation below). This is used to ensure that a page is only
40530 ** rolled back the first time it is encountered in either journal.
40531 **
40532 ** If pSavepoint is NULL, then pages are only played back from the main
40533 ** journal file. There is no need for a bitvec in this case.
40534 **
40535 ** In either case, before playback commences the Pager.dbSize variable
40536 ** is reset to the value that it held at the start of the savepoint 
40537 ** (or transaction). No page with a page-number greater than this value
40538 ** is played back. If one is encountered it is simply skipped.
40539 */
40540 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40541   i64 szJ;                 /* Effective size of the main journal */
40542   i64 iHdrOff;             /* End of first segment of main-journal records */
40543   int rc = SQLITE_OK;      /* Return code */
40544   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
40545
40546   assert( pPager->eState!=PAGER_ERROR );
40547   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40548
40549   /* Allocate a bitvec to use to store the set of pages rolled back */
40550   if( pSavepoint ){
40551     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40552     if( !pDone ){
40553       return SQLITE_NOMEM;
40554     }
40555   }
40556
40557   /* Set the database size back to the value it was before the savepoint 
40558   ** being reverted was opened.
40559   */
40560   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40561   pPager->changeCountDone = pPager->tempFile;
40562
40563   if( !pSavepoint && pagerUseWal(pPager) ){
40564     return pagerRollbackWal(pPager);
40565   }
40566
40567   /* Use pPager->journalOff as the effective size of the main rollback
40568   ** journal.  The actual file might be larger than this in
40569   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40570   ** past pPager->journalOff is off-limits to us.
40571   */
40572   szJ = pPager->journalOff;
40573   assert( pagerUseWal(pPager)==0 || szJ==0 );
40574
40575   /* Begin by rolling back records from the main journal starting at
40576   ** PagerSavepoint.iOffset and continuing to the next journal header.
40577   ** There might be records in the main journal that have a page number
40578   ** greater than the current database size (pPager->dbSize) but those
40579   ** will be skipped automatically.  Pages are added to pDone as they
40580   ** are played back.
40581   */
40582   if( pSavepoint && !pagerUseWal(pPager) ){
40583     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40584     pPager->journalOff = pSavepoint->iOffset;
40585     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40586       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40587     }
40588     assert( rc!=SQLITE_DONE );
40589   }else{
40590     pPager->journalOff = 0;
40591   }
40592
40593   /* Continue rolling back records out of the main journal starting at
40594   ** the first journal header seen and continuing until the effective end
40595   ** of the main journal file.  Continue to skip out-of-range pages and
40596   ** continue adding pages rolled back to pDone.
40597   */
40598   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40599     u32 ii;            /* Loop counter */
40600     u32 nJRec = 0;     /* Number of Journal Records */
40601     u32 dummy;
40602     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40603     assert( rc!=SQLITE_DONE );
40604
40605     /*
40606     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40607     ** test is related to ticket #2565.  See the discussion in the
40608     ** pager_playback() function for additional information.
40609     */
40610     if( nJRec==0 
40611      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40612     ){
40613       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40614     }
40615     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40616       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40617     }
40618     assert( rc!=SQLITE_DONE );
40619   }
40620   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40621
40622   /* Finally,  rollback pages from the sub-journal.  Page that were
40623   ** previously rolled back out of the main journal (and are hence in pDone)
40624   ** will be skipped.  Out-of-range pages are also skipped.
40625   */
40626   if( pSavepoint ){
40627     u32 ii;            /* Loop counter */
40628     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
40629
40630     if( pagerUseWal(pPager) ){
40631       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40632     }
40633     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40634       assert( offset==(i64)ii*(4+pPager->pageSize) );
40635       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40636     }
40637     assert( rc!=SQLITE_DONE );
40638   }
40639
40640   sqlite3BitvecDestroy(pDone);
40641   if( rc==SQLITE_OK ){
40642     pPager->journalOff = szJ;
40643   }
40644
40645   return rc;
40646 }
40647
40648 /*
40649 ** Change the maximum number of in-memory pages that are allowed.
40650 */
40651 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40652   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40653 }
40654
40655 /*
40656 ** Free as much memory as possible from the pager.
40657 */
40658 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
40659   sqlite3PcacheShrink(pPager->pPCache);
40660 }
40661
40662 /*
40663 ** Adjust the robustness of the database to damage due to OS crashes
40664 ** or power failures by changing the number of syncs()s when writing
40665 ** the rollback journal.  There are three levels:
40666 **
40667 **    OFF       sqlite3OsSync() is never called.  This is the default
40668 **              for temporary and transient files.
40669 **
40670 **    NORMAL    The journal is synced once before writes begin on the
40671 **              database.  This is normally adequate protection, but
40672 **              it is theoretically possible, though very unlikely,
40673 **              that an inopertune power failure could leave the journal
40674 **              in a state which would cause damage to the database
40675 **              when it is rolled back.
40676 **
40677 **    FULL      The journal is synced twice before writes begin on the
40678 **              database (with some additional information - the nRec field
40679 **              of the journal header - being written in between the two
40680 **              syncs).  If we assume that writing a
40681 **              single disk sector is atomic, then this mode provides
40682 **              assurance that the journal will not be corrupted to the
40683 **              point of causing damage to the database during rollback.
40684 **
40685 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40686 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40687 ** prior to the start of checkpoint and that the database file is synced
40688 ** at the conclusion of the checkpoint if the entire content of the WAL
40689 ** was written back into the database.  But no sync operations occur for
40690 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40691 ** file is synced following each commit operation, in addition to the
40692 ** syncs associated with NORMAL.
40693 **
40694 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40695 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40696 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40697 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40698 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40699 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40700 ** the xSync primitive is called and is relevant to all platforms.
40701 **
40702 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40703 ** and FULL=3.
40704 */
40705 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40706 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40707   Pager *pPager,        /* The pager to set safety level for */
40708   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
40709   int bFullFsync,       /* PRAGMA fullfsync */
40710   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40711 ){
40712   assert( level>=1 && level<=3 );
40713   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40714   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40715   if( pPager->noSync ){
40716     pPager->syncFlags = 0;
40717     pPager->ckptSyncFlags = 0;
40718   }else if( bFullFsync ){
40719     pPager->syncFlags = SQLITE_SYNC_FULL;
40720     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40721   }else if( bCkptFullFsync ){
40722     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40723     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40724   }else{
40725     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40726     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40727   }
40728   pPager->walSyncFlags = pPager->syncFlags;
40729   if( pPager->fullSync ){
40730     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
40731   }
40732 }
40733 #endif
40734
40735 /*
40736 ** The following global variable is incremented whenever the library
40737 ** attempts to open a temporary file.  This information is used for
40738 ** testing and analysis only.  
40739 */
40740 #ifdef SQLITE_TEST
40741 SQLITE_API int sqlite3_opentemp_count = 0;
40742 #endif
40743
40744 /*
40745 ** Open a temporary file.
40746 **
40747 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
40748 ** or some other error code if we fail. The OS will automatically 
40749 ** delete the temporary file when it is closed.
40750 **
40751 ** The flags passed to the VFS layer xOpen() call are those specified
40752 ** by parameter vfsFlags ORed with the following:
40753 **
40754 **     SQLITE_OPEN_READWRITE
40755 **     SQLITE_OPEN_CREATE
40756 **     SQLITE_OPEN_EXCLUSIVE
40757 **     SQLITE_OPEN_DELETEONCLOSE
40758 */
40759 static int pagerOpentemp(
40760   Pager *pPager,        /* The pager object */
40761   sqlite3_file *pFile,  /* Write the file descriptor here */
40762   int vfsFlags          /* Flags passed through to the VFS */
40763 ){
40764   int rc;               /* Return code */
40765
40766 #ifdef SQLITE_TEST
40767   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40768 #endif
40769
40770   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40771             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40772   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40773   assert( rc!=SQLITE_OK || isOpen(pFile) );
40774   return rc;
40775 }
40776
40777 /*
40778 ** Set the busy handler function.
40779 **
40780 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
40781 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40782 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
40783 ** lock. It does *not* invoke the busy handler when upgrading from
40784 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40785 ** (which occurs during hot-journal rollback). Summary:
40786 **
40787 **   Transition                        | Invokes xBusyHandler
40788 **   --------------------------------------------------------
40789 **   NO_LOCK       -> SHARED_LOCK      | Yes
40790 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40791 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40792 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40793 **
40794 ** If the busy-handler callback returns non-zero, the lock is 
40795 ** retried. If it returns zero, then the SQLITE_BUSY error is
40796 ** returned to the caller of the pager API function.
40797 */
40798 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40799   Pager *pPager,                       /* Pager object */
40800   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40801   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40802 ){
40803   pPager->xBusyHandler = xBusyHandler;
40804   pPager->pBusyHandlerArg = pBusyHandlerArg;
40805
40806   if( isOpen(pPager->fd) ){
40807     void **ap = (void **)&pPager->xBusyHandler;
40808     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
40809     assert( ap[1]==pBusyHandlerArg );
40810     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
40811   }
40812 }
40813
40814 /*
40815 ** Change the page size used by the Pager object. The new page size 
40816 ** is passed in *pPageSize.
40817 **
40818 ** If the pager is in the error state when this function is called, it
40819 ** is a no-op. The value returned is the error state error code (i.e. 
40820 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40821 **
40822 ** Otherwise, if all of the following are true:
40823 **
40824 **   * the new page size (value of *pPageSize) is valid (a power 
40825 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40826 **
40827 **   * there are no outstanding page references, and
40828 **
40829 **   * the database is either not an in-memory database or it is
40830 **     an in-memory database that currently consists of zero pages.
40831 **
40832 ** then the pager object page size is set to *pPageSize.
40833 **
40834 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
40835 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
40836 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
40837 ** In all other cases, SQLITE_OK is returned.
40838 **
40839 ** If the page size is not changed, either because one of the enumerated
40840 ** conditions above is not true, the pager was in error state when this
40841 ** function was called, or because the memory allocation attempt failed, 
40842 ** then *pPageSize is set to the old, retained page size before returning.
40843 */
40844 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40845   int rc = SQLITE_OK;
40846
40847   /* It is not possible to do a full assert_pager_state() here, as this
40848   ** function may be called from within PagerOpen(), before the state
40849   ** of the Pager object is internally consistent.
40850   **
40851   ** At one point this function returned an error if the pager was in 
40852   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40853   ** there is at least one outstanding page reference, this function
40854   ** is a no-op for that case anyhow.
40855   */
40856
40857   u32 pageSize = *pPageSize;
40858   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40859   if( (pPager->memDb==0 || pPager->dbSize==0)
40860    && sqlite3PcacheRefCount(pPager->pPCache)==0 
40861    && pageSize && pageSize!=(u32)pPager->pageSize 
40862   ){
40863     char *pNew = NULL;             /* New temp space */
40864     i64 nByte = 0;
40865
40866     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40867       rc = sqlite3OsFileSize(pPager->fd, &nByte);
40868     }
40869     if( rc==SQLITE_OK ){
40870       pNew = (char *)sqlite3PageMalloc(pageSize);
40871       if( !pNew ) rc = SQLITE_NOMEM;
40872     }
40873
40874     if( rc==SQLITE_OK ){
40875       pager_reset(pPager);
40876       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
40877       pPager->pageSize = pageSize;
40878       sqlite3PageFree(pPager->pTmpSpace);
40879       pPager->pTmpSpace = pNew;
40880       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40881     }
40882   }
40883
40884   *pPageSize = pPager->pageSize;
40885   if( rc==SQLITE_OK ){
40886     if( nReserve<0 ) nReserve = pPager->nReserve;
40887     assert( nReserve>=0 && nReserve<1000 );
40888     pPager->nReserve = (i16)nReserve;
40889     pagerReportSize(pPager);
40890   }
40891   return rc;
40892 }
40893
40894 /*
40895 ** Return a pointer to the "temporary page" buffer held internally
40896 ** by the pager.  This is a buffer that is big enough to hold the
40897 ** entire content of a database page.  This buffer is used internally
40898 ** during rollback and will be overwritten whenever a rollback
40899 ** occurs.  But other modules are free to use it too, as long as
40900 ** no rollbacks are happening.
40901 */
40902 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40903   return pPager->pTmpSpace;
40904 }
40905
40906 /*
40907 ** Attempt to set the maximum database page count if mxPage is positive. 
40908 ** Make no changes if mxPage is zero or negative.  And never reduce the
40909 ** maximum page count below the current size of the database.
40910 **
40911 ** Regardless of mxPage, return the current maximum page count.
40912 */
40913 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40914   if( mxPage>0 ){
40915     pPager->mxPgno = mxPage;
40916   }
40917   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
40918   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
40919   return pPager->mxPgno;
40920 }
40921
40922 /*
40923 ** The following set of routines are used to disable the simulated
40924 ** I/O error mechanism.  These routines are used to avoid simulated
40925 ** errors in places where we do not care about errors.
40926 **
40927 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
40928 ** and generate no code.
40929 */
40930 #ifdef SQLITE_TEST
40931 SQLITE_API extern int sqlite3_io_error_pending;
40932 SQLITE_API extern int sqlite3_io_error_hit;
40933 static int saved_cnt;
40934 void disable_simulated_io_errors(void){
40935   saved_cnt = sqlite3_io_error_pending;
40936   sqlite3_io_error_pending = -1;
40937 }
40938 void enable_simulated_io_errors(void){
40939   sqlite3_io_error_pending = saved_cnt;
40940 }
40941 #else
40942 # define disable_simulated_io_errors()
40943 # define enable_simulated_io_errors()
40944 #endif
40945
40946 /*
40947 ** Read the first N bytes from the beginning of the file into memory
40948 ** that pDest points to. 
40949 **
40950 ** If the pager was opened on a transient file (zFilename==""), or
40951 ** opened on a file less than N bytes in size, the output buffer is
40952 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
40953 ** function is used to read database headers, and a new transient or
40954 ** zero sized database has a header than consists entirely of zeroes.
40955 **
40956 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40957 ** the error code is returned to the caller and the contents of the
40958 ** output buffer undefined.
40959 */
40960 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40961   int rc = SQLITE_OK;
40962   memset(pDest, 0, N);
40963   assert( isOpen(pPager->fd) || pPager->tempFile );
40964
40965   /* This routine is only called by btree immediately after creating
40966   ** the Pager object.  There has not been an opportunity to transition
40967   ** to WAL mode yet.
40968   */
40969   assert( !pagerUseWal(pPager) );
40970
40971   if( isOpen(pPager->fd) ){
40972     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40973     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40974     if( rc==SQLITE_IOERR_SHORT_READ ){
40975       rc = SQLITE_OK;
40976     }
40977   }
40978   return rc;
40979 }
40980
40981 /*
40982 ** This function may only be called when a read-transaction is open on
40983 ** the pager. It returns the total number of pages in the database.
40984 **
40985 ** However, if the file is between 1 and <page-size> bytes in size, then 
40986 ** this is considered a 1 page file.
40987 */
40988 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40989   assert( pPager->eState>=PAGER_READER );
40990   assert( pPager->eState!=PAGER_WRITER_FINISHED );
40991   *pnPage = (int)pPager->dbSize;
40992 }
40993
40994
40995 /*
40996 ** Try to obtain a lock of type locktype on the database file. If
40997 ** a similar or greater lock is already held, this function is a no-op
40998 ** (returning SQLITE_OK immediately).
40999 **
41000 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
41001 ** the busy callback if the lock is currently not available. Repeat 
41002 ** until the busy callback returns false or until the attempt to 
41003 ** obtain the lock succeeds.
41004 **
41005 ** Return SQLITE_OK on success and an error code if we cannot obtain
41006 ** the lock. If the lock is obtained successfully, set the Pager.state 
41007 ** variable to locktype before returning.
41008 */
41009 static int pager_wait_on_lock(Pager *pPager, int locktype){
41010   int rc;                              /* Return code */
41011
41012   /* Check that this is either a no-op (because the requested lock is 
41013   ** already held, or one of the transistions that the busy-handler
41014   ** may be invoked during, according to the comment above
41015   ** sqlite3PagerSetBusyhandler().
41016   */
41017   assert( (pPager->eLock>=locktype)
41018        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
41019        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
41020   );
41021
41022   do {
41023     rc = pagerLockDb(pPager, locktype);
41024   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
41025   return rc;
41026 }
41027
41028 /*
41029 ** Function assertTruncateConstraint(pPager) checks that one of the 
41030 ** following is true for all dirty pages currently in the page-cache:
41031 **
41032 **   a) The page number is less than or equal to the size of the 
41033 **      current database image, in pages, OR
41034 **
41035 **   b) if the page content were written at this time, it would not
41036 **      be necessary to write the current content out to the sub-journal
41037 **      (as determined by function subjRequiresPage()).
41038 **
41039 ** If the condition asserted by this function were not true, and the
41040 ** dirty page were to be discarded from the cache via the pagerStress()
41041 ** routine, pagerStress() would not write the current page content to
41042 ** the database file. If a savepoint transaction were rolled back after
41043 ** this happened, the correct behaviour would be to restore the current
41044 ** content of the page. However, since this content is not present in either
41045 ** the database file or the portion of the rollback journal and 
41046 ** sub-journal rolled back the content could not be restored and the
41047 ** database image would become corrupt. It is therefore fortunate that 
41048 ** this circumstance cannot arise.
41049 */
41050 #if defined(SQLITE_DEBUG)
41051 static void assertTruncateConstraintCb(PgHdr *pPg){
41052   assert( pPg->flags&PGHDR_DIRTY );
41053   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
41054 }
41055 static void assertTruncateConstraint(Pager *pPager){
41056   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
41057 }
41058 #else
41059 # define assertTruncateConstraint(pPager)
41060 #endif
41061
41062 /*
41063 ** Truncate the in-memory database file image to nPage pages. This 
41064 ** function does not actually modify the database file on disk. It 
41065 ** just sets the internal state of the pager object so that the 
41066 ** truncation will be done when the current transaction is committed.
41067 */
41068 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
41069   assert( pPager->dbSize>=nPage );
41070   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41071   pPager->dbSize = nPage;
41072   assertTruncateConstraint(pPager);
41073 }
41074
41075
41076 /*
41077 ** This function is called before attempting a hot-journal rollback. It
41078 ** syncs the journal file to disk, then sets pPager->journalHdr to the
41079 ** size of the journal file so that the pager_playback() routine knows
41080 ** that the entire journal file has been synced.
41081 **
41082 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
41083 ** that if a power-failure occurs during the rollback, the process that
41084 ** attempts rollback following system recovery sees the same journal
41085 ** content as this process.
41086 **
41087 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
41088 ** an SQLite error code.
41089 */
41090 static int pagerSyncHotJournal(Pager *pPager){
41091   int rc = SQLITE_OK;
41092   if( !pPager->noSync ){
41093     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
41094   }
41095   if( rc==SQLITE_OK ){
41096     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
41097   }
41098   return rc;
41099 }
41100
41101 /*
41102 ** Shutdown the page cache.  Free all memory and close all files.
41103 **
41104 ** If a transaction was in progress when this routine is called, that
41105 ** transaction is rolled back.  All outstanding pages are invalidated
41106 ** and their memory is freed.  Any attempt to use a page associated
41107 ** with this page cache after this function returns will likely
41108 ** result in a coredump.
41109 **
41110 ** This function always succeeds. If a transaction is active an attempt
41111 ** is made to roll it back. If an error occurs during the rollback 
41112 ** a hot journal may be left in the filesystem but no error is returned
41113 ** to the caller.
41114 */
41115 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
41116   u8 *pTmp = (u8 *)pPager->pTmpSpace;
41117
41118   assert( assert_pager_state(pPager) );
41119   disable_simulated_io_errors();
41120   sqlite3BeginBenignMalloc();
41121   /* pPager->errCode = 0; */
41122   pPager->exclusiveMode = 0;
41123 #ifndef SQLITE_OMIT_WAL
41124   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
41125   pPager->pWal = 0;
41126 #endif
41127   pager_reset(pPager);
41128   if( MEMDB ){
41129     pager_unlock(pPager);
41130   }else{
41131     /* If it is open, sync the journal file before calling UnlockAndRollback.
41132     ** If this is not done, then an unsynced portion of the open journal 
41133     ** file may be played back into the database. If a power failure occurs 
41134     ** while this is happening, the database could become corrupt.
41135     **
41136     ** If an error occurs while trying to sync the journal, shift the pager
41137     ** into the ERROR state. This causes UnlockAndRollback to unlock the
41138     ** database and close the journal file without attempting to roll it
41139     ** back or finalize it. The next database user will have to do hot-journal
41140     ** rollback before accessing the database file.
41141     */
41142     if( isOpen(pPager->jfd) ){
41143       pager_error(pPager, pagerSyncHotJournal(pPager));
41144     }
41145     pagerUnlockAndRollback(pPager);
41146   }
41147   sqlite3EndBenignMalloc();
41148   enable_simulated_io_errors();
41149   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
41150   IOTRACE(("CLOSE %p\n", pPager))
41151   sqlite3OsClose(pPager->jfd);
41152   sqlite3OsClose(pPager->fd);
41153   sqlite3PageFree(pTmp);
41154   sqlite3PcacheClose(pPager->pPCache);
41155
41156 #ifdef SQLITE_HAS_CODEC
41157   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41158 #endif
41159
41160   assert( !pPager->aSavepoint && !pPager->pInJournal );
41161   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
41162
41163   sqlite3_free(pPager);
41164   return SQLITE_OK;
41165 }
41166
41167 #if !defined(NDEBUG) || defined(SQLITE_TEST)
41168 /*
41169 ** Return the page number for page pPg.
41170 */
41171 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
41172   return pPg->pgno;
41173 }
41174 #endif
41175
41176 /*
41177 ** Increment the reference count for page pPg.
41178 */
41179 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
41180   sqlite3PcacheRef(pPg);
41181 }
41182
41183 /*
41184 ** Sync the journal. In other words, make sure all the pages that have
41185 ** been written to the journal have actually reached the surface of the
41186 ** disk and can be restored in the event of a hot-journal rollback.
41187 **
41188 ** If the Pager.noSync flag is set, then this function is a no-op.
41189 ** Otherwise, the actions required depend on the journal-mode and the 
41190 ** device characteristics of the file-system, as follows:
41191 **
41192 **   * If the journal file is an in-memory journal file, no action need
41193 **     be taken.
41194 **
41195 **   * Otherwise, if the device does not support the SAFE_APPEND property,
41196 **     then the nRec field of the most recently written journal header
41197 **     is updated to contain the number of journal records that have
41198 **     been written following it. If the pager is operating in full-sync
41199 **     mode, then the journal file is synced before this field is updated.
41200 **
41201 **   * If the device does not support the SEQUENTIAL property, then 
41202 **     journal file is synced.
41203 **
41204 ** Or, in pseudo-code:
41205 **
41206 **   if( NOT <in-memory journal> ){
41207 **     if( NOT SAFE_APPEND ){
41208 **       if( <full-sync mode> ) xSync(<journal file>);
41209 **       <update nRec field>
41210 **     } 
41211 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
41212 **   }
41213 **
41214 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
41215 ** page currently held in memory before returning SQLITE_OK. If an IO
41216 ** error is encountered, then the IO error code is returned to the caller.
41217 */
41218 static int syncJournal(Pager *pPager, int newHdr){
41219   int rc;                         /* Return code */
41220
41221   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41222        || pPager->eState==PAGER_WRITER_DBMOD
41223   );
41224   assert( assert_pager_state(pPager) );
41225   assert( !pagerUseWal(pPager) );
41226
41227   rc = sqlite3PagerExclusiveLock(pPager);
41228   if( rc!=SQLITE_OK ) return rc;
41229
41230   if( !pPager->noSync ){
41231     assert( !pPager->tempFile );
41232     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
41233       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41234       assert( isOpen(pPager->jfd) );
41235
41236       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41237         /* This block deals with an obscure problem. If the last connection
41238         ** that wrote to this database was operating in persistent-journal
41239         ** mode, then the journal file may at this point actually be larger
41240         ** than Pager.journalOff bytes. If the next thing in the journal
41241         ** file happens to be a journal-header (written as part of the
41242         ** previous connection's transaction), and a crash or power-failure 
41243         ** occurs after nRec is updated but before this connection writes 
41244         ** anything else to the journal file (or commits/rolls back its 
41245         ** transaction), then SQLite may become confused when doing the 
41246         ** hot-journal rollback following recovery. It may roll back all
41247         ** of this connections data, then proceed to rolling back the old,
41248         ** out-of-date data that follows it. Database corruption.
41249         **
41250         ** To work around this, if the journal file does appear to contain
41251         ** a valid header following Pager.journalOff, then write a 0x00
41252         ** byte to the start of it to prevent it from being recognized.
41253         **
41254         ** Variable iNextHdrOffset is set to the offset at which this
41255         ** problematic header will occur, if it exists. aMagic is used 
41256         ** as a temporary buffer to inspect the first couple of bytes of
41257         ** the potential journal header.
41258         */
41259         i64 iNextHdrOffset;
41260         u8 aMagic[8];
41261         u8 zHeader[sizeof(aJournalMagic)+4];
41262
41263         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41264         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
41265
41266         iNextHdrOffset = journalHdrOffset(pPager);
41267         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
41268         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
41269           static const u8 zerobyte = 0;
41270           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
41271         }
41272         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
41273           return rc;
41274         }
41275
41276         /* Write the nRec value into the journal file header. If in
41277         ** full-synchronous mode, sync the journal first. This ensures that
41278         ** all data has really hit the disk before nRec is updated to mark
41279         ** it as a candidate for rollback.
41280         **
41281         ** This is not required if the persistent media supports the
41282         ** SAFE_APPEND property. Because in this case it is not possible 
41283         ** for garbage data to be appended to the file, the nRec field
41284         ** is populated with 0xFFFFFFFF when the journal header is written
41285         ** and never needs to be updated.
41286         */
41287         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41288           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41289           IOTRACE(("JSYNC %p\n", pPager))
41290           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
41291           if( rc!=SQLITE_OK ) return rc;
41292         }
41293         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
41294         rc = sqlite3OsWrite(
41295             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
41296         );
41297         if( rc!=SQLITE_OK ) return rc;
41298       }
41299       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41300         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41301         IOTRACE(("JSYNC %p\n", pPager))
41302         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
41303           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
41304         );
41305         if( rc!=SQLITE_OK ) return rc;
41306       }
41307
41308       pPager->journalHdr = pPager->journalOff;
41309       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41310         pPager->nRec = 0;
41311         rc = writeJournalHdr(pPager);
41312         if( rc!=SQLITE_OK ) return rc;
41313       }
41314     }else{
41315       pPager->journalHdr = pPager->journalOff;
41316     }
41317   }
41318
41319   /* Unless the pager is in noSync mode, the journal file was just 
41320   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
41321   ** all pages.
41322   */
41323   sqlite3PcacheClearSyncFlags(pPager->pPCache);
41324   pPager->eState = PAGER_WRITER_DBMOD;
41325   assert( assert_pager_state(pPager) );
41326   return SQLITE_OK;
41327 }
41328
41329 /*
41330 ** The argument is the first in a linked list of dirty pages connected
41331 ** by the PgHdr.pDirty pointer. This function writes each one of the
41332 ** in-memory pages in the list to the database file. The argument may
41333 ** be NULL, representing an empty list. In this case this function is
41334 ** a no-op.
41335 **
41336 ** The pager must hold at least a RESERVED lock when this function
41337 ** is called. Before writing anything to the database file, this lock
41338 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
41339 ** SQLITE_BUSY is returned and no data is written to the database file.
41340 ** 
41341 ** If the pager is a temp-file pager and the actual file-system file
41342 ** is not yet open, it is created and opened before any data is 
41343 ** written out.
41344 **
41345 ** Once the lock has been upgraded and, if necessary, the file opened,
41346 ** the pages are written out to the database file in list order. Writing
41347 ** a page is skipped if it meets either of the following criteria:
41348 **
41349 **   * The page number is greater than Pager.dbSize, or
41350 **   * The PGHDR_DONT_WRITE flag is set on the page.
41351 **
41352 ** If writing out a page causes the database file to grow, Pager.dbFileSize
41353 ** is updated accordingly. If page 1 is written out, then the value cached
41354 ** in Pager.dbFileVers[] is updated to match the new value stored in
41355 ** the database file.
41356 **
41357 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41358 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
41359 ** be obtained, SQLITE_BUSY is returned.
41360 */
41361 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
41362   int rc = SQLITE_OK;                  /* Return code */
41363
41364   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
41365   assert( !pagerUseWal(pPager) );
41366   assert( pPager->eState==PAGER_WRITER_DBMOD );
41367   assert( pPager->eLock==EXCLUSIVE_LOCK );
41368
41369   /* If the file is a temp-file has not yet been opened, open it now. It
41370   ** is not possible for rc to be other than SQLITE_OK if this branch
41371   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
41372   */
41373   if( !isOpen(pPager->fd) ){
41374     assert( pPager->tempFile && rc==SQLITE_OK );
41375     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
41376   }
41377
41378   /* Before the first write, give the VFS a hint of what the final
41379   ** file size will be.
41380   */
41381   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
41382   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
41383     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
41384     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
41385     pPager->dbHintSize = pPager->dbSize;
41386   }
41387
41388   while( rc==SQLITE_OK && pList ){
41389     Pgno pgno = pList->pgno;
41390
41391     /* If there are dirty pages in the page cache with page numbers greater
41392     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41393     ** make the file smaller (presumably by auto-vacuum code). Do not write
41394     ** any such pages to the file.
41395     **
41396     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41397     ** set (set by sqlite3PagerDontWrite()).
41398     */
41399     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41400       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
41401       char *pData;                                   /* Data to write */    
41402
41403       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41404       if( pList->pgno==1 ) pager_write_changecounter(pList);
41405
41406       /* Encode the database */
41407       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41408
41409       /* Write out the page data. */
41410       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41411
41412       /* If page 1 was just written, update Pager.dbFileVers to match
41413       ** the value now stored in the database file. If writing this 
41414       ** page caused the database file to grow, update dbFileSize. 
41415       */
41416       if( pgno==1 ){
41417         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41418       }
41419       if( pgno>pPager->dbFileSize ){
41420         pPager->dbFileSize = pgno;
41421       }
41422       pPager->aStat[PAGER_STAT_WRITE]++;
41423
41424       /* Update any backup objects copying the contents of this pager. */
41425       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41426
41427       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41428                    PAGERID(pPager), pgno, pager_pagehash(pList)));
41429       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41430       PAGER_INCR(sqlite3_pager_writedb_count);
41431     }else{
41432       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41433     }
41434     pager_set_pagehash(pList);
41435     pList = pList->pDirty;
41436   }
41437
41438   return rc;
41439 }
41440
41441 /*
41442 ** Ensure that the sub-journal file is open. If it is already open, this 
41443 ** function is a no-op.
41444 **
41445 ** SQLITE_OK is returned if everything goes according to plan. An 
41446 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
41447 ** fails.
41448 */
41449 static int openSubJournal(Pager *pPager){
41450   int rc = SQLITE_OK;
41451   if( !isOpen(pPager->sjfd) ){
41452     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41453       sqlite3MemJournalOpen(pPager->sjfd);
41454     }else{
41455       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41456     }
41457   }
41458   return rc;
41459 }
41460
41461 /*
41462 ** Append a record of the current state of page pPg to the sub-journal. 
41463 ** It is the callers responsibility to use subjRequiresPage() to check 
41464 ** that it is really required before calling this function.
41465 **
41466 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41467 ** for all open savepoints before returning.
41468 **
41469 ** This function returns SQLITE_OK if everything is successful, an IO
41470 ** error code if the attempt to write to the sub-journal fails, or 
41471 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41472 ** bitvec.
41473 */
41474 static int subjournalPage(PgHdr *pPg){
41475   int rc = SQLITE_OK;
41476   Pager *pPager = pPg->pPager;
41477   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41478
41479     /* Open the sub-journal, if it has not already been opened */
41480     assert( pPager->useJournal );
41481     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41482     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41483     assert( pagerUseWal(pPager) 
41484          || pageInJournal(pPg) 
41485          || pPg->pgno>pPager->dbOrigSize 
41486     );
41487     rc = openSubJournal(pPager);
41488
41489     /* If the sub-journal was opened successfully (or was already open),
41490     ** write the journal record into the file.  */
41491     if( rc==SQLITE_OK ){
41492       void *pData = pPg->pData;
41493       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
41494       char *pData2;
41495   
41496       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41497       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41498       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41499       if( rc==SQLITE_OK ){
41500         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41501       }
41502     }
41503   }
41504   if( rc==SQLITE_OK ){
41505     pPager->nSubRec++;
41506     assert( pPager->nSavepoint>0 );
41507     rc = addToSavepointBitvecs(pPager, pPg->pgno);
41508   }
41509   return rc;
41510 }
41511
41512 /*
41513 ** This function is called by the pcache layer when it has reached some
41514 ** soft memory limit. The first argument is a pointer to a Pager object
41515 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41516 ** database). The second argument is a reference to a page that is 
41517 ** currently dirty but has no outstanding references. The page
41518 ** is always associated with the Pager object passed as the first 
41519 ** argument.
41520 **
41521 ** The job of this function is to make pPg clean by writing its contents
41522 ** out to the database file, if possible. This may involve syncing the
41523 ** journal file. 
41524 **
41525 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41526 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41527 ** page clean, the IO error code is returned. If the page cannot be
41528 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41529 ** is returned by sqlite3PcacheMakeClean() is not called.
41530 */
41531 static int pagerStress(void *p, PgHdr *pPg){
41532   Pager *pPager = (Pager *)p;
41533   int rc = SQLITE_OK;
41534
41535   assert( pPg->pPager==pPager );
41536   assert( pPg->flags&PGHDR_DIRTY );
41537
41538   /* The doNotSyncSpill flag is set during times when doing a sync of
41539   ** journal (and adding a new header) is not allowed.  This occurs
41540   ** during calls to sqlite3PagerWrite() while trying to journal multiple
41541   ** pages belonging to the same sector.
41542   **
41543   ** The doNotSpill flag inhibits all cache spilling regardless of whether
41544   ** or not a sync is required.  This is set during a rollback.
41545   **
41546   ** Spilling is also prohibited when in an error state since that could
41547   ** lead to database corruption.   In the current implementaton it 
41548   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
41549   ** while in the error state, hence it is impossible for this routine to
41550   ** be called in the error state.  Nevertheless, we include a NEVER()
41551   ** test for the error state as a safeguard against future changes.
41552   */
41553   if( NEVER(pPager->errCode) ) return SQLITE_OK;
41554   if( pPager->doNotSpill ) return SQLITE_OK;
41555   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41556     return SQLITE_OK;
41557   }
41558
41559   pPg->pDirty = 0;
41560   if( pagerUseWal(pPager) ){
41561     /* Write a single frame for this page to the log. */
41562     if( subjRequiresPage(pPg) ){ 
41563       rc = subjournalPage(pPg); 
41564     }
41565     if( rc==SQLITE_OK ){
41566       rc = pagerWalFrames(pPager, pPg, 0, 0);
41567     }
41568   }else{
41569   
41570     /* Sync the journal file if required. */
41571     if( pPg->flags&PGHDR_NEED_SYNC 
41572      || pPager->eState==PAGER_WRITER_CACHEMOD
41573     ){
41574       rc = syncJournal(pPager, 1);
41575     }
41576   
41577     /* If the page number of this page is larger than the current size of
41578     ** the database image, it may need to be written to the sub-journal.
41579     ** This is because the call to pager_write_pagelist() below will not
41580     ** actually write data to the file in this case.
41581     **
41582     ** Consider the following sequence of events:
41583     **
41584     **   BEGIN;
41585     **     <journal page X>
41586     **     <modify page X>
41587     **     SAVEPOINT sp;
41588     **       <shrink database file to Y pages>
41589     **       pagerStress(page X)
41590     **     ROLLBACK TO sp;
41591     **
41592     ** If (X>Y), then when pagerStress is called page X will not be written
41593     ** out to the database file, but will be dropped from the cache. Then,
41594     ** following the "ROLLBACK TO sp" statement, reading page X will read
41595     ** data from the database file. This will be the copy of page X as it
41596     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41597     ** was executed.
41598     **
41599     ** The solution is to write the current data for page X into the 
41600     ** sub-journal file now (if it is not already there), so that it will
41601     ** be restored to its current value when the "ROLLBACK TO sp" is 
41602     ** executed.
41603     */
41604     if( NEVER(
41605         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41606     ) ){
41607       rc = subjournalPage(pPg);
41608     }
41609   
41610     /* Write the contents of the page out to the database file. */
41611     if( rc==SQLITE_OK ){
41612       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41613       rc = pager_write_pagelist(pPager, pPg);
41614     }
41615   }
41616
41617   /* Mark the page as clean. */
41618   if( rc==SQLITE_OK ){
41619     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41620     sqlite3PcacheMakeClean(pPg);
41621   }
41622
41623   return pager_error(pPager, rc); 
41624 }
41625
41626
41627 /*
41628 ** Allocate and initialize a new Pager object and put a pointer to it
41629 ** in *ppPager. The pager should eventually be freed by passing it
41630 ** to sqlite3PagerClose().
41631 **
41632 ** The zFilename argument is the path to the database file to open.
41633 ** If zFilename is NULL then a randomly-named temporary file is created
41634 ** and used as the file to be cached. Temporary files are be deleted
41635 ** automatically when they are closed. If zFilename is ":memory:" then 
41636 ** all information is held in cache. It is never written to disk. 
41637 ** This can be used to implement an in-memory database.
41638 **
41639 ** The nExtra parameter specifies the number of bytes of space allocated
41640 ** along with each page reference. This space is available to the user
41641 ** via the sqlite3PagerGetExtra() API.
41642 **
41643 ** The flags argument is used to specify properties that affect the
41644 ** operation of the pager. It should be passed some bitwise combination
41645 ** of the PAGER_* flags.
41646 **
41647 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41648 ** of the xOpen() method of the supplied VFS when opening files. 
41649 **
41650 ** If the pager object is allocated and the specified file opened 
41651 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41652 ** the new pager object. If an error occurs, *ppPager is set to NULL
41653 ** and error code returned. This function may return SQLITE_NOMEM
41654 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
41655 ** various SQLITE_IO_XXX errors.
41656 */
41657 SQLITE_PRIVATE int sqlite3PagerOpen(
41658   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41659   Pager **ppPager,         /* OUT: Return the Pager structure here */
41660   const char *zFilename,   /* Name of the database file to open */
41661   int nExtra,              /* Extra bytes append to each in-memory page */
41662   int flags,               /* flags controlling this file */
41663   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41664   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41665 ){
41666   u8 *pPtr;
41667   Pager *pPager = 0;       /* Pager object to allocate and return */
41668   int rc = SQLITE_OK;      /* Return code */
41669   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41670   int memDb = 0;           /* True if this is an in-memory file */
41671   int readOnly = 0;        /* True if this is a read-only file */
41672   int journalFileSize;     /* Bytes to allocate for each journal fd */
41673   char *zPathname = 0;     /* Full path to database file */
41674   int nPathname = 0;       /* Number of bytes in zPathname */
41675   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41676   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41677   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41678   const char *zUri = 0;    /* URI args to copy */
41679   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41680
41681   /* Figure out how much space is required for each journal file-handle
41682   ** (there are two of them, the main journal and the sub-journal). This
41683   ** is the maximum space required for an in-memory journal file handle 
41684   ** and a regular journal file-handle. Note that a "regular journal-handle"
41685   ** may be a wrapper capable of caching the first portion of the journal
41686   ** file in memory to implement the atomic-write optimization (see 
41687   ** source file journal.c).
41688   */
41689   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41690     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41691   }else{
41692     journalFileSize = ROUND8(sqlite3MemJournalSize());
41693   }
41694
41695   /* Set the output variable to NULL in case an error occurs. */
41696   *ppPager = 0;
41697
41698 #ifndef SQLITE_OMIT_MEMORYDB
41699   if( flags & PAGER_MEMORY ){
41700     memDb = 1;
41701     if( zFilename && zFilename[0] ){
41702       zPathname = sqlite3DbStrDup(0, zFilename);
41703       if( zPathname==0  ) return SQLITE_NOMEM;
41704       nPathname = sqlite3Strlen30(zPathname);
41705       zFilename = 0;
41706     }
41707   }
41708 #endif
41709
41710   /* Compute and store the full pathname in an allocated buffer pointed
41711   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41712   ** leave both nPathname and zPathname set to 0.
41713   */
41714   if( zFilename && zFilename[0] ){
41715     const char *z;
41716     nPathname = pVfs->mxPathname+1;
41717     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
41718     if( zPathname==0 ){
41719       return SQLITE_NOMEM;
41720     }
41721     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41722     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41723     nPathname = sqlite3Strlen30(zPathname);
41724     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41725     while( *z ){
41726       z += sqlite3Strlen30(z)+1;
41727       z += sqlite3Strlen30(z)+1;
41728     }
41729     nUri = (int)(&z[1] - zUri);
41730     assert( nUri>=0 );
41731     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41732       /* This branch is taken when the journal path required by
41733       ** the database being opened will be more than pVfs->mxPathname
41734       ** bytes in length. This means the database cannot be opened,
41735       ** as it will not be possible to open the journal file or even
41736       ** check for a hot-journal before reading.
41737       */
41738       rc = SQLITE_CANTOPEN_BKPT;
41739     }
41740     if( rc!=SQLITE_OK ){
41741       sqlite3DbFree(0, zPathname);
41742       return rc;
41743     }
41744   }
41745
41746   /* Allocate memory for the Pager structure, PCache object, the
41747   ** three file descriptors, the database file name and the journal 
41748   ** file name. The layout in memory is as follows:
41749   **
41750   **     Pager object                    (sizeof(Pager) bytes)
41751   **     PCache object                   (sqlite3PcacheSize() bytes)
41752   **     Database file handle            (pVfs->szOsFile bytes)
41753   **     Sub-journal file handle         (journalFileSize bytes)
41754   **     Main journal file handle        (journalFileSize bytes)
41755   **     Database file name              (nPathname+1 bytes)
41756   **     Journal file name               (nPathname+8+1 bytes)
41757   */
41758   pPtr = (u8 *)sqlite3MallocZero(
41759     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41760     ROUND8(pcacheSize) +           /* PCache object */
41761     ROUND8(pVfs->szOsFile) +       /* The main db file */
41762     journalFileSize * 2 +          /* The two journal files */ 
41763     nPathname + 1 + nUri +         /* zFilename */
41764     nPathname + 8 + 2              /* zJournal */
41765 #ifndef SQLITE_OMIT_WAL
41766     + nPathname + 4 + 2            /* zWal */
41767 #endif
41768   );
41769   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41770   if( !pPtr ){
41771     sqlite3DbFree(0, zPathname);
41772     return SQLITE_NOMEM;
41773   }
41774   pPager =              (Pager*)(pPtr);
41775   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41776   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41777   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41778   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41779   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41780   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41781
41782   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41783   if( zPathname ){
41784     assert( nPathname>0 );
41785     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41786     memcpy(pPager->zFilename, zPathname, nPathname);
41787     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41788     memcpy(pPager->zJournal, zPathname, nPathname);
41789     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
41790     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41791 #ifndef SQLITE_OMIT_WAL
41792     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41793     memcpy(pPager->zWal, zPathname, nPathname);
41794     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
41795     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41796 #endif
41797     sqlite3DbFree(0, zPathname);
41798   }
41799   pPager->pVfs = pVfs;
41800   pPager->vfsFlags = vfsFlags;
41801
41802   /* Open the pager file.
41803   */
41804   if( zFilename && zFilename[0] ){
41805     int fout = 0;                    /* VFS flags returned by xOpen() */
41806     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41807     assert( !memDb );
41808     readOnly = (fout&SQLITE_OPEN_READONLY);
41809
41810     /* If the file was successfully opened for read/write access,
41811     ** choose a default page size in case we have to create the
41812     ** database file. The default page size is the maximum of:
41813     **
41814     **    + SQLITE_DEFAULT_PAGE_SIZE,
41815     **    + The value returned by sqlite3OsSectorSize()
41816     **    + The largest page size that can be written atomically.
41817     */
41818     if( rc==SQLITE_OK && !readOnly ){
41819       setSectorSize(pPager);
41820       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41821       if( szPageDflt<pPager->sectorSize ){
41822         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41823           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41824         }else{
41825           szPageDflt = (u32)pPager->sectorSize;
41826         }
41827       }
41828 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41829       {
41830         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41831         int ii;
41832         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41833         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41834         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41835         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41836           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41837             szPageDflt = ii;
41838           }
41839         }
41840       }
41841 #endif
41842     }
41843   }else{
41844     /* If a temporary file is requested, it is not opened immediately.
41845     ** In this case we accept the default page size and delay actually
41846     ** opening the file until the first call to OsWrite().
41847     **
41848     ** This branch is also run for an in-memory database. An in-memory
41849     ** database is the same as a temp-file that is never written out to
41850     ** disk and uses an in-memory rollback journal.
41851     */ 
41852     tempFile = 1;
41853     pPager->eState = PAGER_READER;
41854     pPager->eLock = EXCLUSIVE_LOCK;
41855     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41856   }
41857
41858   /* The following call to PagerSetPagesize() serves to set the value of 
41859   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41860   */
41861   if( rc==SQLITE_OK ){
41862     assert( pPager->memDb==0 );
41863     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41864     testcase( rc!=SQLITE_OK );
41865   }
41866
41867   /* If an error occurred in either of the blocks above, free the 
41868   ** Pager structure and close the file.
41869   */
41870   if( rc!=SQLITE_OK ){
41871     assert( !pPager->pTmpSpace );
41872     sqlite3OsClose(pPager->fd);
41873     sqlite3_free(pPager);
41874     return rc;
41875   }
41876
41877   /* Initialize the PCache object. */
41878   assert( nExtra<1000 );
41879   nExtra = ROUND8(nExtra);
41880   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41881                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41882
41883   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41884   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41885
41886   pPager->useJournal = (u8)useJournal;
41887   /* pPager->stmtOpen = 0; */
41888   /* pPager->stmtInUse = 0; */
41889   /* pPager->nRef = 0; */
41890   /* pPager->stmtSize = 0; */
41891   /* pPager->stmtJSize = 0; */
41892   /* pPager->nPage = 0; */
41893   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41894   /* pPager->state = PAGER_UNLOCK; */
41895 #if 0
41896   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41897 #endif
41898   /* pPager->errMask = 0; */
41899   pPager->tempFile = (u8)tempFile;
41900   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
41901           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41902   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41903   pPager->exclusiveMode = (u8)tempFile; 
41904   pPager->changeCountDone = pPager->tempFile;
41905   pPager->memDb = (u8)memDb;
41906   pPager->readOnly = (u8)readOnly;
41907   assert( useJournal || pPager->tempFile );
41908   pPager->noSync = pPager->tempFile;
41909   if( pPager->noSync ){
41910     assert( pPager->fullSync==0 );
41911     assert( pPager->syncFlags==0 );
41912     assert( pPager->walSyncFlags==0 );
41913     assert( pPager->ckptSyncFlags==0 );
41914   }else{
41915     pPager->fullSync = 1;
41916     pPager->syncFlags = SQLITE_SYNC_NORMAL;
41917     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
41918     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41919   }
41920   /* pPager->pFirst = 0; */
41921   /* pPager->pFirstSynced = 0; */
41922   /* pPager->pLast = 0; */
41923   pPager->nExtra = (u16)nExtra;
41924   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
41925   assert( isOpen(pPager->fd) || tempFile );
41926   setSectorSize(pPager);
41927   if( !useJournal ){
41928     pPager->journalMode = PAGER_JOURNALMODE_OFF;
41929   }else if( memDb ){
41930     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
41931   }
41932   /* pPager->xBusyHandler = 0; */
41933   /* pPager->pBusyHandlerArg = 0; */
41934   pPager->xReiniter = xReinit;
41935   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
41936
41937   *ppPager = pPager;
41938   return SQLITE_OK;
41939 }
41940
41941
41942
41943 /*
41944 ** This function is called after transitioning from PAGER_UNLOCK to
41945 ** PAGER_SHARED state. It tests if there is a hot journal present in
41946 ** the file-system for the given pager. A hot journal is one that 
41947 ** needs to be played back. According to this function, a hot-journal
41948 ** file exists if the following criteria are met:
41949 **
41950 **   * The journal file exists in the file system, and
41951 **   * No process holds a RESERVED or greater lock on the database file, and
41952 **   * The database file itself is greater than 0 bytes in size, and
41953 **   * The first byte of the journal file exists and is not 0x00.
41954 **
41955 ** If the current size of the database file is 0 but a journal file
41956 ** exists, that is probably an old journal left over from a prior
41957 ** database with the same name. In this case the journal file is
41958 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
41959 ** is returned.
41960 **
41961 ** This routine does not check if there is a master journal filename
41962 ** at the end of the file. If there is, and that master journal file
41963 ** does not exist, then the journal file is not really hot. In this
41964 ** case this routine will return a false-positive. The pager_playback()
41965 ** routine will discover that the journal file is not really hot and 
41966 ** will not roll it back. 
41967 **
41968 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
41969 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41970 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41971 ** to determine whether or not a hot-journal file exists, the IO error
41972 ** code is returned and the value of *pExists is undefined.
41973 */
41974 static int hasHotJournal(Pager *pPager, int *pExists){
41975   sqlite3_vfs * const pVfs = pPager->pVfs;
41976   int rc = SQLITE_OK;           /* Return code */
41977   int exists = 1;               /* True if a journal file is present */
41978   int jrnlOpen = !!isOpen(pPager->jfd);
41979
41980   assert( pPager->useJournal );
41981   assert( isOpen(pPager->fd) );
41982   assert( pPager->eState==PAGER_OPEN );
41983
41984   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41985     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41986   ));
41987
41988   *pExists = 0;
41989   if( !jrnlOpen ){
41990     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41991   }
41992   if( rc==SQLITE_OK && exists ){
41993     int locked = 0;             /* True if some process holds a RESERVED lock */
41994
41995     /* Race condition here:  Another process might have been holding the
41996     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
41997     ** call above, but then delete the journal and drop the lock before
41998     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
41999     ** is the case, this routine might think there is a hot journal when
42000     ** in fact there is none.  This results in a false-positive which will
42001     ** be dealt with by the playback routine.  Ticket #3883.
42002     */
42003     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
42004     if( rc==SQLITE_OK && !locked ){
42005       Pgno nPage;                 /* Number of pages in database file */
42006
42007       /* Check the size of the database file. If it consists of 0 pages,
42008       ** then delete the journal file. See the header comment above for 
42009       ** the reasoning here.  Delete the obsolete journal file under
42010       ** a RESERVED lock to avoid race conditions and to avoid violating
42011       ** [H33020].
42012       */
42013       rc = pagerPagecount(pPager, &nPage);
42014       if( rc==SQLITE_OK ){
42015         if( nPage==0 ){
42016           sqlite3BeginBenignMalloc();
42017           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
42018             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
42019             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
42020           }
42021           sqlite3EndBenignMalloc();
42022         }else{
42023           /* The journal file exists and no other connection has a reserved
42024           ** or greater lock on the database file. Now check that there is
42025           ** at least one non-zero bytes at the start of the journal file.
42026           ** If there is, then we consider this journal to be hot. If not, 
42027           ** it can be ignored.
42028           */
42029           if( !jrnlOpen ){
42030             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
42031             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
42032           }
42033           if( rc==SQLITE_OK ){
42034             u8 first = 0;
42035             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
42036             if( rc==SQLITE_IOERR_SHORT_READ ){
42037               rc = SQLITE_OK;
42038             }
42039             if( !jrnlOpen ){
42040               sqlite3OsClose(pPager->jfd);
42041             }
42042             *pExists = (first!=0);
42043           }else if( rc==SQLITE_CANTOPEN ){
42044             /* If we cannot open the rollback journal file in order to see if
42045             ** its has a zero header, that might be due to an I/O error, or
42046             ** it might be due to the race condition described above and in
42047             ** ticket #3883.  Either way, assume that the journal is hot.
42048             ** This might be a false positive.  But if it is, then the
42049             ** automatic journal playback and recovery mechanism will deal
42050             ** with it under an EXCLUSIVE lock where we do not need to
42051             ** worry so much with race conditions.
42052             */
42053             *pExists = 1;
42054             rc = SQLITE_OK;
42055           }
42056         }
42057       }
42058     }
42059   }
42060
42061   return rc;
42062 }
42063
42064 /*
42065 ** This function is called to obtain a shared lock on the database file.
42066 ** It is illegal to call sqlite3PagerAcquire() until after this function
42067 ** has been successfully called. If a shared-lock is already held when
42068 ** this function is called, it is a no-op.
42069 **
42070 ** The following operations are also performed by this function.
42071 **
42072 **   1) If the pager is currently in PAGER_OPEN state (no lock held
42073 **      on the database file), then an attempt is made to obtain a
42074 **      SHARED lock on the database file. Immediately after obtaining
42075 **      the SHARED lock, the file-system is checked for a hot-journal,
42076 **      which is played back if present. Following any hot-journal 
42077 **      rollback, the contents of the cache are validated by checking
42078 **      the 'change-counter' field of the database file header and
42079 **      discarded if they are found to be invalid.
42080 **
42081 **   2) If the pager is running in exclusive-mode, and there are currently
42082 **      no outstanding references to any pages, and is in the error state,
42083 **      then an attempt is made to clear the error state by discarding
42084 **      the contents of the page cache and rolling back any open journal
42085 **      file.
42086 **
42087 ** If everything is successful, SQLITE_OK is returned. If an IO error 
42088 ** occurs while locking the database, checking for a hot-journal file or 
42089 ** rolling back a journal file, the IO error code is returned.
42090 */
42091 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
42092   int rc = SQLITE_OK;                /* Return code */
42093
42094   /* This routine is only called from b-tree and only when there are no
42095   ** outstanding pages. This implies that the pager state should either
42096   ** be OPEN or READER. READER is only possible if the pager is or was in 
42097   ** exclusive access mode.
42098   */
42099   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
42100   assert( assert_pager_state(pPager) );
42101   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42102   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
42103
42104   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
42105     int bHotJournal = 1;          /* True if there exists a hot journal-file */
42106
42107     assert( !MEMDB );
42108
42109     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
42110     if( rc!=SQLITE_OK ){
42111       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
42112       goto failed;
42113     }
42114
42115     /* If a journal file exists, and there is no RESERVED lock on the
42116     ** database file, then it either needs to be played back or deleted.
42117     */
42118     if( pPager->eLock<=SHARED_LOCK ){
42119       rc = hasHotJournal(pPager, &bHotJournal);
42120     }
42121     if( rc!=SQLITE_OK ){
42122       goto failed;
42123     }
42124     if( bHotJournal ){
42125       /* Get an EXCLUSIVE lock on the database file. At this point it is
42126       ** important that a RESERVED lock is not obtained on the way to the
42127       ** EXCLUSIVE lock. If it were, another process might open the
42128       ** database file, detect the RESERVED lock, and conclude that the
42129       ** database is safe to read while this process is still rolling the 
42130       ** hot-journal back.
42131       ** 
42132       ** Because the intermediate RESERVED lock is not requested, any
42133       ** other process attempting to access the database file will get to 
42134       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
42135       ** on the database file.
42136       **
42137       ** Unless the pager is in locking_mode=exclusive mode, the lock is
42138       ** downgraded to SHARED_LOCK before this function returns.
42139       */
42140       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42141       if( rc!=SQLITE_OK ){
42142         goto failed;
42143       }
42144  
42145       /* If it is not already open and the file exists on disk, open the 
42146       ** journal for read/write access. Write access is required because 
42147       ** in exclusive-access mode the file descriptor will be kept open 
42148       ** and possibly used for a transaction later on. Also, write-access 
42149       ** is usually required to finalize the journal in journal_mode=persist 
42150       ** mode (and also for journal_mode=truncate on some systems).
42151       **
42152       ** If the journal does not exist, it usually means that some 
42153       ** other connection managed to get in and roll it back before 
42154       ** this connection obtained the exclusive lock above. Or, it 
42155       ** may mean that the pager was in the error-state when this
42156       ** function was called and the journal file does not exist.
42157       */
42158       if( !isOpen(pPager->jfd) ){
42159         sqlite3_vfs * const pVfs = pPager->pVfs;
42160         int bExists;              /* True if journal file exists */
42161         rc = sqlite3OsAccess(
42162             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
42163         if( rc==SQLITE_OK && bExists ){
42164           int fout = 0;
42165           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
42166           assert( !pPager->tempFile );
42167           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
42168           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42169           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
42170             rc = SQLITE_CANTOPEN_BKPT;
42171             sqlite3OsClose(pPager->jfd);
42172           }
42173         }
42174       }
42175  
42176       /* Playback and delete the journal.  Drop the database write
42177       ** lock and reacquire the read lock. Purge the cache before
42178       ** playing back the hot-journal so that we don't end up with
42179       ** an inconsistent cache.  Sync the hot journal before playing
42180       ** it back since the process that crashed and left the hot journal
42181       ** probably did not sync it and we are required to always sync
42182       ** the journal before playing it back.
42183       */
42184       if( isOpen(pPager->jfd) ){
42185         assert( rc==SQLITE_OK );
42186         rc = pagerSyncHotJournal(pPager);
42187         if( rc==SQLITE_OK ){
42188           rc = pager_playback(pPager, 1);
42189           pPager->eState = PAGER_OPEN;
42190         }
42191       }else if( !pPager->exclusiveMode ){
42192         pagerUnlockDb(pPager, SHARED_LOCK);
42193       }
42194
42195       if( rc!=SQLITE_OK ){
42196         /* This branch is taken if an error occurs while trying to open
42197         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
42198         ** pager_unlock() routine will be called before returning to unlock
42199         ** the file. If the unlock attempt fails, then Pager.eLock must be
42200         ** set to UNKNOWN_LOCK (see the comment above the #define for 
42201         ** UNKNOWN_LOCK above for an explanation). 
42202         **
42203         ** In order to get pager_unlock() to do this, set Pager.eState to
42204         ** PAGER_ERROR now. This is not actually counted as a transition
42205         ** to ERROR state in the state diagram at the top of this file,
42206         ** since we know that the same call to pager_unlock() will very
42207         ** shortly transition the pager object to the OPEN state. Calling
42208         ** assert_pager_state() would fail now, as it should not be possible
42209         ** to be in ERROR state when there are zero outstanding page 
42210         ** references.
42211         */
42212         pager_error(pPager, rc);
42213         goto failed;
42214       }
42215
42216       assert( pPager->eState==PAGER_OPEN );
42217       assert( (pPager->eLock==SHARED_LOCK)
42218            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
42219       );
42220     }
42221
42222     if( !pPager->tempFile 
42223      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
42224     ){
42225       /* The shared-lock has just been acquired on the database file
42226       ** and there are already pages in the cache (from a previous
42227       ** read or write transaction).  Check to see if the database
42228       ** has been modified.  If the database has changed, flush the
42229       ** cache.
42230       **
42231       ** Database changes is detected by looking at 15 bytes beginning
42232       ** at offset 24 into the file.  The first 4 of these 16 bytes are
42233       ** a 32-bit counter that is incremented with each change.  The
42234       ** other bytes change randomly with each file change when
42235       ** a codec is in use.
42236       ** 
42237       ** There is a vanishingly small chance that a change will not be 
42238       ** detected.  The chance of an undetected change is so small that
42239       ** it can be neglected.
42240       */
42241       Pgno nPage = 0;
42242       char dbFileVers[sizeof(pPager->dbFileVers)];
42243
42244       rc = pagerPagecount(pPager, &nPage);
42245       if( rc ) goto failed;
42246
42247       if( nPage>0 ){
42248         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
42249         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
42250         if( rc!=SQLITE_OK ){
42251           goto failed;
42252         }
42253       }else{
42254         memset(dbFileVers, 0, sizeof(dbFileVers));
42255       }
42256
42257       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
42258         pager_reset(pPager);
42259       }
42260     }
42261
42262     /* If there is a WAL file in the file-system, open this database in WAL
42263     ** mode. Otherwise, the following function call is a no-op.
42264     */
42265     rc = pagerOpenWalIfPresent(pPager);
42266 #ifndef SQLITE_OMIT_WAL
42267     assert( pPager->pWal==0 || rc==SQLITE_OK );
42268 #endif
42269   }
42270
42271   if( pagerUseWal(pPager) ){
42272     assert( rc==SQLITE_OK );
42273     rc = pagerBeginReadTransaction(pPager);
42274   }
42275
42276   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
42277     rc = pagerPagecount(pPager, &pPager->dbSize);
42278   }
42279
42280  failed:
42281   if( rc!=SQLITE_OK ){
42282     assert( !MEMDB );
42283     pager_unlock(pPager);
42284     assert( pPager->eState==PAGER_OPEN );
42285   }else{
42286     pPager->eState = PAGER_READER;
42287   }
42288   return rc;
42289 }
42290
42291 /*
42292 ** If the reference count has reached zero, rollback any active
42293 ** transaction and unlock the pager.
42294 **
42295 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
42296 ** the rollback journal, the unlock is not performed and there is
42297 ** nothing to rollback, so this routine is a no-op.
42298 */ 
42299 static void pagerUnlockIfUnused(Pager *pPager){
42300   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
42301     pagerUnlockAndRollback(pPager);
42302   }
42303 }
42304
42305 /*
42306 ** Acquire a reference to page number pgno in pager pPager (a page
42307 ** reference has type DbPage*). If the requested reference is 
42308 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
42309 **
42310 ** If the requested page is already in the cache, it is returned. 
42311 ** Otherwise, a new page object is allocated and populated with data
42312 ** read from the database file. In some cases, the pcache module may
42313 ** choose not to allocate a new page object and may reuse an existing
42314 ** object with no outstanding references.
42315 **
42316 ** The extra data appended to a page is always initialized to zeros the 
42317 ** first time a page is loaded into memory. If the page requested is 
42318 ** already in the cache when this function is called, then the extra
42319 ** data is left as it was when the page object was last used.
42320 **
42321 ** If the database image is smaller than the requested page or if a 
42322 ** non-zero value is passed as the noContent parameter and the 
42323 ** requested page is not already stored in the cache, then no 
42324 ** actual disk read occurs. In this case the memory image of the 
42325 ** page is initialized to all zeros. 
42326 **
42327 ** If noContent is true, it means that we do not care about the contents
42328 ** of the page. This occurs in two seperate scenarios:
42329 **
42330 **   a) When reading a free-list leaf page from the database, and
42331 **
42332 **   b) When a savepoint is being rolled back and we need to load
42333 **      a new page into the cache to be filled with the data read
42334 **      from the savepoint journal.
42335 **
42336 ** If noContent is true, then the data returned is zeroed instead of
42337 ** being read from the database. Additionally, the bits corresponding
42338 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
42339 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
42340 ** savepoints are set. This means if the page is made writable at any
42341 ** point in the future, using a call to sqlite3PagerWrite(), its contents
42342 ** will not be journaled. This saves IO.
42343 **
42344 ** The acquisition might fail for several reasons.  In all cases,
42345 ** an appropriate error code is returned and *ppPage is set to NULL.
42346 **
42347 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
42348 ** to find a page in the in-memory cache first.  If the page is not already
42349 ** in memory, this routine goes to disk to read it in whereas Lookup()
42350 ** just returns 0.  This routine acquires a read-lock the first time it
42351 ** has to go to disk, and could also playback an old journal if necessary.
42352 ** Since Lookup() never goes to disk, it never has to deal with locks
42353 ** or journal files.
42354 */
42355 SQLITE_PRIVATE int sqlite3PagerAcquire(
42356   Pager *pPager,      /* The pager open on the database file */
42357   Pgno pgno,          /* Page number to fetch */
42358   DbPage **ppPage,    /* Write a pointer to the page here */
42359   int noContent       /* Do not bother reading content from disk if true */
42360 ){
42361   int rc;
42362   PgHdr *pPg;
42363
42364   assert( pPager->eState>=PAGER_READER );
42365   assert( assert_pager_state(pPager) );
42366
42367   if( pgno==0 ){
42368     return SQLITE_CORRUPT_BKPT;
42369   }
42370
42371   /* If the pager is in the error state, return an error immediately. 
42372   ** Otherwise, request the page from the PCache layer. */
42373   if( pPager->errCode!=SQLITE_OK ){
42374     rc = pPager->errCode;
42375   }else{
42376     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
42377   }
42378
42379   if( rc!=SQLITE_OK ){
42380     /* Either the call to sqlite3PcacheFetch() returned an error or the
42381     ** pager was already in the error-state when this function was called.
42382     ** Set pPg to 0 and jump to the exception handler.  */
42383     pPg = 0;
42384     goto pager_acquire_err;
42385   }
42386   assert( (*ppPage)->pgno==pgno );
42387   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
42388
42389   if( (*ppPage)->pPager && !noContent ){
42390     /* In this case the pcache already contains an initialized copy of
42391     ** the page. Return without further ado.  */
42392     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42393     pPager->aStat[PAGER_STAT_HIT]++;
42394     return SQLITE_OK;
42395
42396   }else{
42397     /* The pager cache has created a new page. Its content needs to 
42398     ** be initialized.  */
42399
42400     pPg = *ppPage;
42401     pPg->pPager = pPager;
42402
42403     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42404     ** number greater than this, or the unused locking-page, is requested. */
42405     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42406       rc = SQLITE_CORRUPT_BKPT;
42407       goto pager_acquire_err;
42408     }
42409
42410     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42411       if( pgno>pPager->mxPgno ){
42412         rc = SQLITE_FULL;
42413         goto pager_acquire_err;
42414       }
42415       if( noContent ){
42416         /* Failure to set the bits in the InJournal bit-vectors is benign.
42417         ** It merely means that we might do some extra work to journal a 
42418         ** page that does not need to be journaled.  Nevertheless, be sure 
42419         ** to test the case where a malloc error occurs while trying to set 
42420         ** a bit in a bit vector.
42421         */
42422         sqlite3BeginBenignMalloc();
42423         if( pgno<=pPager->dbOrigSize ){
42424           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42425           testcase( rc==SQLITE_NOMEM );
42426         }
42427         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42428         testcase( rc==SQLITE_NOMEM );
42429         sqlite3EndBenignMalloc();
42430       }
42431       memset(pPg->pData, 0, pPager->pageSize);
42432       IOTRACE(("ZERO %p %d\n", pPager, pgno));
42433     }else{
42434       assert( pPg->pPager==pPager );
42435       pPager->aStat[PAGER_STAT_MISS]++;
42436       rc = readDbPage(pPg);
42437       if( rc!=SQLITE_OK ){
42438         goto pager_acquire_err;
42439       }
42440     }
42441     pager_set_pagehash(pPg);
42442   }
42443
42444   return SQLITE_OK;
42445
42446 pager_acquire_err:
42447   assert( rc!=SQLITE_OK );
42448   if( pPg ){
42449     sqlite3PcacheDrop(pPg);
42450   }
42451   pagerUnlockIfUnused(pPager);
42452
42453   *ppPage = 0;
42454   return rc;
42455 }
42456
42457 /*
42458 ** Acquire a page if it is already in the in-memory cache.  Do
42459 ** not read the page from disk.  Return a pointer to the page,
42460 ** or 0 if the page is not in cache. 
42461 **
42462 ** See also sqlite3PagerGet().  The difference between this routine
42463 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42464 ** in the page if the page is not already in cache.  This routine
42465 ** returns NULL if the page is not in cache or if a disk I/O error 
42466 ** has ever happened.
42467 */
42468 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42469   PgHdr *pPg = 0;
42470   assert( pPager!=0 );
42471   assert( pgno!=0 );
42472   assert( pPager->pPCache!=0 );
42473   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42474   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42475   return pPg;
42476 }
42477
42478 /*
42479 ** Release a page reference.
42480 **
42481 ** If the number of references to the page drop to zero, then the
42482 ** page is added to the LRU list.  When all references to all pages
42483 ** are released, a rollback occurs and the lock on the database is
42484 ** removed.
42485 */
42486 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42487   if( pPg ){
42488     Pager *pPager = pPg->pPager;
42489     sqlite3PcacheRelease(pPg);
42490     pagerUnlockIfUnused(pPager);
42491   }
42492 }
42493
42494 /*
42495 ** This function is called at the start of every write transaction.
42496 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
42497 ** file when this routine is called.
42498 **
42499 ** Open the journal file for pager pPager and write a journal header
42500 ** to the start of it. If there are active savepoints, open the sub-journal
42501 ** as well. This function is only used when the journal file is being 
42502 ** opened to write a rollback log for a transaction. It is not used 
42503 ** when opening a hot journal file to roll it back.
42504 **
42505 ** If the journal file is already open (as it may be in exclusive mode),
42506 ** then this function just writes a journal header to the start of the
42507 ** already open file. 
42508 **
42509 ** Whether or not the journal file is opened by this function, the
42510 ** Pager.pInJournal bitvec structure is allocated.
42511 **
42512 ** Return SQLITE_OK if everything is successful. Otherwise, return 
42513 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
42514 ** an IO error code if opening or writing the journal file fails.
42515 */
42516 static int pager_open_journal(Pager *pPager){
42517   int rc = SQLITE_OK;                        /* Return code */
42518   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
42519
42520   assert( pPager->eState==PAGER_WRITER_LOCKED );
42521   assert( assert_pager_state(pPager) );
42522   assert( pPager->pInJournal==0 );
42523   
42524   /* If already in the error state, this function is a no-op.  But on
42525   ** the other hand, this routine is never called if we are already in
42526   ** an error state. */
42527   if( NEVER(pPager->errCode) ) return pPager->errCode;
42528
42529   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42530     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42531     if( pPager->pInJournal==0 ){
42532       return SQLITE_NOMEM;
42533     }
42534   
42535     /* Open the journal file if it is not already open. */
42536     if( !isOpen(pPager->jfd) ){
42537       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42538         sqlite3MemJournalOpen(pPager->jfd);
42539       }else{
42540         const int flags =                   /* VFS flags to open journal file */
42541           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42542           (pPager->tempFile ? 
42543             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42544             (SQLITE_OPEN_MAIN_JOURNAL)
42545           );
42546   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42547         rc = sqlite3JournalOpen(
42548             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42549         );
42550   #else
42551         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42552   #endif
42553       }
42554       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42555     }
42556   
42557   
42558     /* Write the first journal header to the journal file and open 
42559     ** the sub-journal if necessary.
42560     */
42561     if( rc==SQLITE_OK ){
42562       /* TODO: Check if all of these are really required. */
42563       pPager->nRec = 0;
42564       pPager->journalOff = 0;
42565       pPager->setMaster = 0;
42566       pPager->journalHdr = 0;
42567       rc = writeJournalHdr(pPager);
42568     }
42569   }
42570
42571   if( rc!=SQLITE_OK ){
42572     sqlite3BitvecDestroy(pPager->pInJournal);
42573     pPager->pInJournal = 0;
42574   }else{
42575     assert( pPager->eState==PAGER_WRITER_LOCKED );
42576     pPager->eState = PAGER_WRITER_CACHEMOD;
42577   }
42578
42579   return rc;
42580 }
42581
42582 /*
42583 ** Begin a write-transaction on the specified pager object. If a 
42584 ** write-transaction has already been opened, this function is a no-op.
42585 **
42586 ** If the exFlag argument is false, then acquire at least a RESERVED
42587 ** lock on the database file. If exFlag is true, then acquire at least
42588 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
42589 ** functions need be called.
42590 **
42591 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42592 ** within this transaction will be opened as an in-memory file. This
42593 ** has no effect if the sub-journal is already opened (as it may be when
42594 ** running in exclusive mode) or if the transaction does not require a
42595 ** sub-journal. If the subjInMemory argument is zero, then any required
42596 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
42597 ** or using a temporary file otherwise.
42598 */
42599 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42600   int rc = SQLITE_OK;
42601
42602   if( pPager->errCode ) return pPager->errCode;
42603   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42604   pPager->subjInMemory = (u8)subjInMemory;
42605
42606   if( ALWAYS(pPager->eState==PAGER_READER) ){
42607     assert( pPager->pInJournal==0 );
42608
42609     if( pagerUseWal(pPager) ){
42610       /* If the pager is configured to use locking_mode=exclusive, and an
42611       ** exclusive lock on the database is not already held, obtain it now.
42612       */
42613       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42614         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42615         if( rc!=SQLITE_OK ){
42616           return rc;
42617         }
42618         sqlite3WalExclusiveMode(pPager->pWal, 1);
42619       }
42620
42621       /* Grab the write lock on the log file. If successful, upgrade to
42622       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42623       ** The busy-handler is not invoked if another connection already
42624       ** holds the write-lock. If possible, the upper layer will call it.
42625       */
42626       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42627     }else{
42628       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42629       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42630       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42631       ** lock, but not when obtaining the RESERVED lock.
42632       */
42633       rc = pagerLockDb(pPager, RESERVED_LOCK);
42634       if( rc==SQLITE_OK && exFlag ){
42635         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42636       }
42637     }
42638
42639     if( rc==SQLITE_OK ){
42640       /* Change to WRITER_LOCKED state.
42641       **
42642       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42643       ** when it has an open transaction, but never to DBMOD or FINISHED.
42644       ** This is because in those states the code to roll back savepoint 
42645       ** transactions may copy data from the sub-journal into the database 
42646       ** file as well as into the page cache. Which would be incorrect in 
42647       ** WAL mode.
42648       */
42649       pPager->eState = PAGER_WRITER_LOCKED;
42650       pPager->dbHintSize = pPager->dbSize;
42651       pPager->dbFileSize = pPager->dbSize;
42652       pPager->dbOrigSize = pPager->dbSize;
42653       pPager->journalOff = 0;
42654     }
42655
42656     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42657     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42658     assert( assert_pager_state(pPager) );
42659   }
42660
42661   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42662   return rc;
42663 }
42664
42665 /*
42666 ** Mark a single data page as writeable. The page is written into the 
42667 ** main journal or sub-journal as required. If the page is written into
42668 ** one of the journals, the corresponding bit is set in the 
42669 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42670 ** of any open savepoints as appropriate.
42671 */
42672 static int pager_write(PgHdr *pPg){
42673   void *pData = pPg->pData;
42674   Pager *pPager = pPg->pPager;
42675   int rc = SQLITE_OK;
42676
42677   /* This routine is not called unless a write-transaction has already 
42678   ** been started. The journal file may or may not be open at this point.
42679   ** It is never called in the ERROR state.
42680   */
42681   assert( pPager->eState==PAGER_WRITER_LOCKED
42682        || pPager->eState==PAGER_WRITER_CACHEMOD
42683        || pPager->eState==PAGER_WRITER_DBMOD
42684   );
42685   assert( assert_pager_state(pPager) );
42686
42687   /* If an error has been previously detected, report the same error
42688   ** again. This should not happen, but the check provides robustness. */
42689   if( NEVER(pPager->errCode) )  return pPager->errCode;
42690
42691   /* Higher-level routines never call this function if database is not
42692   ** writable.  But check anyway, just for robustness. */
42693   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42694
42695   CHECK_PAGE(pPg);
42696
42697   /* The journal file needs to be opened. Higher level routines have already
42698   ** obtained the necessary locks to begin the write-transaction, but the
42699   ** rollback journal might not yet be open. Open it now if this is the case.
42700   **
42701   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
42702   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42703   ** an error might occur and the pager would end up in WRITER_LOCKED state
42704   ** with pages marked as dirty in the cache.
42705   */
42706   if( pPager->eState==PAGER_WRITER_LOCKED ){
42707     rc = pager_open_journal(pPager);
42708     if( rc!=SQLITE_OK ) return rc;
42709   }
42710   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42711   assert( assert_pager_state(pPager) );
42712
42713   /* Mark the page as dirty.  If the page has already been written
42714   ** to the journal then we can return right away.
42715   */
42716   sqlite3PcacheMakeDirty(pPg);
42717   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42718     assert( !pagerUseWal(pPager) );
42719   }else{
42720   
42721     /* The transaction journal now exists and we have a RESERVED or an
42722     ** EXCLUSIVE lock on the main database file.  Write the current page to
42723     ** the transaction journal if it is not there already.
42724     */
42725     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42726       assert( pagerUseWal(pPager)==0 );
42727       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42728         u32 cksum;
42729         char *pData2;
42730         i64 iOff = pPager->journalOff;
42731
42732         /* We should never write to the journal file the page that
42733         ** contains the database locks.  The following assert verifies
42734         ** that we do not. */
42735         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42736
42737         assert( pPager->journalHdr<=pPager->journalOff );
42738         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42739         cksum = pager_cksum(pPager, (u8*)pData2);
42740
42741         /* Even if an IO or diskfull error occurs while journalling the
42742         ** page in the block above, set the need-sync flag for the page.
42743         ** Otherwise, when the transaction is rolled back, the logic in
42744         ** playback_one_page() will think that the page needs to be restored
42745         ** in the database file. And if an IO error occurs while doing so,
42746         ** then corruption may follow.
42747         */
42748         pPg->flags |= PGHDR_NEED_SYNC;
42749
42750         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42751         if( rc!=SQLITE_OK ) return rc;
42752         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42753         if( rc!=SQLITE_OK ) return rc;
42754         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42755         if( rc!=SQLITE_OK ) return rc;
42756
42757         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
42758                  pPager->journalOff, pPager->pageSize));
42759         PAGER_INCR(sqlite3_pager_writej_count);
42760         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42761              PAGERID(pPager), pPg->pgno, 
42762              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42763
42764         pPager->journalOff += 8 + pPager->pageSize;
42765         pPager->nRec++;
42766         assert( pPager->pInJournal!=0 );
42767         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42768         testcase( rc==SQLITE_NOMEM );
42769         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42770         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42771         if( rc!=SQLITE_OK ){
42772           assert( rc==SQLITE_NOMEM );
42773           return rc;
42774         }
42775       }else{
42776         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42777           pPg->flags |= PGHDR_NEED_SYNC;
42778         }
42779         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42780                 PAGERID(pPager), pPg->pgno,
42781                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42782       }
42783     }
42784   
42785     /* If the statement journal is open and the page is not in it,
42786     ** then write the current page to the statement journal.  Note that
42787     ** the statement journal format differs from the standard journal format
42788     ** in that it omits the checksums and the header.
42789     */
42790     if( subjRequiresPage(pPg) ){
42791       rc = subjournalPage(pPg);
42792     }
42793   }
42794
42795   /* Update the database size and return.
42796   */
42797   if( pPager->dbSize<pPg->pgno ){
42798     pPager->dbSize = pPg->pgno;
42799   }
42800   return rc;
42801 }
42802
42803 /*
42804 ** Mark a data page as writeable. This routine must be called before 
42805 ** making changes to a page. The caller must check the return value 
42806 ** of this function and be careful not to change any page data unless 
42807 ** this routine returns SQLITE_OK.
42808 **
42809 ** The difference between this function and pager_write() is that this
42810 ** function also deals with the special case where 2 or more pages
42811 ** fit on a single disk sector. In this case all co-resident pages
42812 ** must have been written to the journal file before returning.
42813 **
42814 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42815 ** as appropriate. Otherwise, SQLITE_OK.
42816 */
42817 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42818   int rc = SQLITE_OK;
42819
42820   PgHdr *pPg = pDbPage;
42821   Pager *pPager = pPg->pPager;
42822   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42823
42824   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42825   assert( pPager->eState!=PAGER_ERROR );
42826   assert( assert_pager_state(pPager) );
42827
42828   if( nPagePerSector>1 ){
42829     Pgno nPageCount;          /* Total number of pages in database file */
42830     Pgno pg1;                 /* First page of the sector pPg is located on. */
42831     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42832     int ii;                   /* Loop counter */
42833     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42834
42835     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42836     ** a journal header to be written between the pages journaled by
42837     ** this function.
42838     */
42839     assert( !MEMDB );
42840     assert( pPager->doNotSyncSpill==0 );
42841     pPager->doNotSyncSpill++;
42842
42843     /* This trick assumes that both the page-size and sector-size are
42844     ** an integer power of 2. It sets variable pg1 to the identifier
42845     ** of the first page of the sector pPg is located on.
42846     */
42847     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42848
42849     nPageCount = pPager->dbSize;
42850     if( pPg->pgno>nPageCount ){
42851       nPage = (pPg->pgno - pg1)+1;
42852     }else if( (pg1+nPagePerSector-1)>nPageCount ){
42853       nPage = nPageCount+1-pg1;
42854     }else{
42855       nPage = nPagePerSector;
42856     }
42857     assert(nPage>0);
42858     assert(pg1<=pPg->pgno);
42859     assert((pg1+nPage)>pPg->pgno);
42860
42861     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42862       Pgno pg = pg1+ii;
42863       PgHdr *pPage;
42864       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42865         if( pg!=PAGER_MJ_PGNO(pPager) ){
42866           rc = sqlite3PagerGet(pPager, pg, &pPage);
42867           if( rc==SQLITE_OK ){
42868             rc = pager_write(pPage);
42869             if( pPage->flags&PGHDR_NEED_SYNC ){
42870               needSync = 1;
42871             }
42872             sqlite3PagerUnref(pPage);
42873           }
42874         }
42875       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42876         if( pPage->flags&PGHDR_NEED_SYNC ){
42877           needSync = 1;
42878         }
42879         sqlite3PagerUnref(pPage);
42880       }
42881     }
42882
42883     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
42884     ** starting at pg1, then it needs to be set for all of them. Because
42885     ** writing to any of these nPage pages may damage the others, the
42886     ** journal file must contain sync()ed copies of all of them
42887     ** before any of them can be written out to the database file.
42888     */
42889     if( rc==SQLITE_OK && needSync ){
42890       assert( !MEMDB );
42891       for(ii=0; ii<nPage; ii++){
42892         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42893         if( pPage ){
42894           pPage->flags |= PGHDR_NEED_SYNC;
42895           sqlite3PagerUnref(pPage);
42896         }
42897       }
42898     }
42899
42900     assert( pPager->doNotSyncSpill==1 );
42901     pPager->doNotSyncSpill--;
42902   }else{
42903     rc = pager_write(pDbPage);
42904   }
42905   return rc;
42906 }
42907
42908 /*
42909 ** Return TRUE if the page given in the argument was previously passed
42910 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
42911 ** to change the content of the page.
42912 */
42913 #ifndef NDEBUG
42914 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42915   return pPg->flags&PGHDR_DIRTY;
42916 }
42917 #endif
42918
42919 /*
42920 ** A call to this routine tells the pager that it is not necessary to
42921 ** write the information on page pPg back to the disk, even though
42922 ** that page might be marked as dirty.  This happens, for example, when
42923 ** the page has been added as a leaf of the freelist and so its
42924 ** content no longer matters.
42925 **
42926 ** The overlying software layer calls this routine when all of the data
42927 ** on the given page is unused. The pager marks the page as clean so
42928 ** that it does not get written to disk.
42929 **
42930 ** Tests show that this optimization can quadruple the speed of large 
42931 ** DELETE operations.
42932 */
42933 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42934   Pager *pPager = pPg->pPager;
42935   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42936     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42937     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42938     pPg->flags |= PGHDR_DONT_WRITE;
42939     pager_set_pagehash(pPg);
42940   }
42941 }
42942
42943 /*
42944 ** This routine is called to increment the value of the database file 
42945 ** change-counter, stored as a 4-byte big-endian integer starting at 
42946 ** byte offset 24 of the pager file.  The secondary change counter at
42947 ** 92 is also updated, as is the SQLite version number at offset 96.
42948 **
42949 ** But this only happens if the pPager->changeCountDone flag is false.
42950 ** To avoid excess churning of page 1, the update only happens once.
42951 ** See also the pager_write_changecounter() routine that does an 
42952 ** unconditional update of the change counters.
42953 **
42954 ** If the isDirectMode flag is zero, then this is done by calling 
42955 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42956 ** page data. In this case the file will be updated when the current
42957 ** transaction is committed.
42958 **
42959 ** The isDirectMode flag may only be non-zero if the library was compiled
42960 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42961 ** if isDirect is non-zero, then the database file is updated directly
42962 ** by writing an updated version of page 1 using a call to the 
42963 ** sqlite3OsWrite() function.
42964 */
42965 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42966   int rc = SQLITE_OK;
42967
42968   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42969        || pPager->eState==PAGER_WRITER_DBMOD
42970   );
42971   assert( assert_pager_state(pPager) );
42972
42973   /* Declare and initialize constant integer 'isDirect'. If the
42974   ** atomic-write optimization is enabled in this build, then isDirect
42975   ** is initialized to the value passed as the isDirectMode parameter
42976   ** to this function. Otherwise, it is always set to zero.
42977   **
42978   ** The idea is that if the atomic-write optimization is not
42979   ** enabled at compile time, the compiler can omit the tests of
42980   ** 'isDirect' below, as well as the block enclosed in the
42981   ** "if( isDirect )" condition.
42982   */
42983 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42984 # define DIRECT_MODE 0
42985   assert( isDirectMode==0 );
42986   UNUSED_PARAMETER(isDirectMode);
42987 #else
42988 # define DIRECT_MODE isDirectMode
42989 #endif
42990
42991   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
42992     PgHdr *pPgHdr;                /* Reference to page 1 */
42993
42994     assert( !pPager->tempFile && isOpen(pPager->fd) );
42995
42996     /* Open page 1 of the file for writing. */
42997     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42998     assert( pPgHdr==0 || rc==SQLITE_OK );
42999
43000     /* If page one was fetched successfully, and this function is not
43001     ** operating in direct-mode, make page 1 writable.  When not in 
43002     ** direct mode, page 1 is always held in cache and hence the PagerGet()
43003     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
43004     */
43005     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
43006       rc = sqlite3PagerWrite(pPgHdr);
43007     }
43008
43009     if( rc==SQLITE_OK ){
43010       /* Actually do the update of the change counter */
43011       pager_write_changecounter(pPgHdr);
43012
43013       /* If running in direct mode, write the contents of page 1 to the file. */
43014       if( DIRECT_MODE ){
43015         const void *zBuf;
43016         assert( pPager->dbFileSize>0 );
43017         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
43018         if( rc==SQLITE_OK ){
43019           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
43020           pPager->aStat[PAGER_STAT_WRITE]++;
43021         }
43022         if( rc==SQLITE_OK ){
43023           pPager->changeCountDone = 1;
43024         }
43025       }else{
43026         pPager->changeCountDone = 1;
43027       }
43028     }
43029
43030     /* Release the page reference. */
43031     sqlite3PagerUnref(pPgHdr);
43032   }
43033   return rc;
43034 }
43035
43036 /*
43037 ** Sync the database file to disk. This is a no-op for in-memory databases
43038 ** or pages with the Pager.noSync flag set.
43039 **
43040 ** If successful, or if called on a pager for which it is a no-op, this
43041 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
43042 */
43043 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
43044   int rc = SQLITE_OK;
43045   if( !pPager->noSync ){
43046     assert( !MEMDB );
43047     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
43048   }else if( isOpen(pPager->fd) ){
43049     assert( !MEMDB );
43050     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
43051     if( rc==SQLITE_NOTFOUND ){
43052       rc = SQLITE_OK;
43053     }
43054   }
43055   return rc;
43056 }
43057
43058 /*
43059 ** This function may only be called while a write-transaction is active in
43060 ** rollback. If the connection is in WAL mode, this call is a no-op. 
43061 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
43062 ** the database file, an attempt is made to obtain one.
43063 **
43064 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
43065 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
43066 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
43067 ** returned.
43068 */
43069 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
43070   int rc = SQLITE_OK;
43071   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
43072        || pPager->eState==PAGER_WRITER_DBMOD 
43073        || pPager->eState==PAGER_WRITER_LOCKED 
43074   );
43075   assert( assert_pager_state(pPager) );
43076   if( 0==pagerUseWal(pPager) ){
43077     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43078   }
43079   return rc;
43080 }
43081
43082 /*
43083 ** Sync the database file for the pager pPager. zMaster points to the name
43084 ** of a master journal file that should be written into the individual
43085 ** journal file. zMaster may be NULL, which is interpreted as no master
43086 ** journal (a single database transaction).
43087 **
43088 ** This routine ensures that:
43089 **
43090 **   * The database file change-counter is updated,
43091 **   * the journal is synced (unless the atomic-write optimization is used),
43092 **   * all dirty pages are written to the database file, 
43093 **   * the database file is truncated (if required), and
43094 **   * the database file synced. 
43095 **
43096 ** The only thing that remains to commit the transaction is to finalize 
43097 ** (delete, truncate or zero the first part of) the journal file (or 
43098 ** delete the master journal file if specified).
43099 **
43100 ** Note that if zMaster==NULL, this does not overwrite a previous value
43101 ** passed to an sqlite3PagerCommitPhaseOne() call.
43102 **
43103 ** If the final parameter - noSync - is true, then the database file itself
43104 ** is not synced. The caller must call sqlite3PagerSync() directly to
43105 ** sync the database file before calling CommitPhaseTwo() to delete the
43106 ** journal file in this case.
43107 */
43108 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
43109   Pager *pPager,                  /* Pager object */
43110   const char *zMaster,            /* If not NULL, the master journal name */
43111   int noSync                      /* True to omit the xSync on the db file */
43112 ){
43113   int rc = SQLITE_OK;             /* Return code */
43114
43115   assert( pPager->eState==PAGER_WRITER_LOCKED
43116        || pPager->eState==PAGER_WRITER_CACHEMOD
43117        || pPager->eState==PAGER_WRITER_DBMOD
43118        || pPager->eState==PAGER_ERROR
43119   );
43120   assert( assert_pager_state(pPager) );
43121
43122   /* If a prior error occurred, report that error again. */
43123   if( NEVER(pPager->errCode) ) return pPager->errCode;
43124
43125   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
43126       pPager->zFilename, zMaster, pPager->dbSize));
43127
43128   /* If no database changes have been made, return early. */
43129   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
43130
43131   if( MEMDB ){
43132     /* If this is an in-memory db, or no pages have been written to, or this
43133     ** function has already been called, it is mostly a no-op.  However, any
43134     ** backup in progress needs to be restarted.
43135     */
43136     sqlite3BackupRestart(pPager->pBackup);
43137   }else{
43138     if( pagerUseWal(pPager) ){
43139       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
43140       PgHdr *pPageOne = 0;
43141       if( pList==0 ){
43142         /* Must have at least one page for the WAL commit flag.
43143         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
43144         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
43145         pList = pPageOne;
43146         pList->pDirty = 0;
43147       }
43148       assert( rc==SQLITE_OK );
43149       if( ALWAYS(pList) ){
43150         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
43151       }
43152       sqlite3PagerUnref(pPageOne);
43153       if( rc==SQLITE_OK ){
43154         sqlite3PcacheCleanAll(pPager->pPCache);
43155       }
43156     }else{
43157       /* The following block updates the change-counter. Exactly how it
43158       ** does this depends on whether or not the atomic-update optimization
43159       ** was enabled at compile time, and if this transaction meets the 
43160       ** runtime criteria to use the operation: 
43161       **
43162       **    * The file-system supports the atomic-write property for
43163       **      blocks of size page-size, and 
43164       **    * This commit is not part of a multi-file transaction, and
43165       **    * Exactly one page has been modified and store in the journal file.
43166       **
43167       ** If the optimization was not enabled at compile time, then the
43168       ** pager_incr_changecounter() function is called to update the change
43169       ** counter in 'indirect-mode'. If the optimization is compiled in but
43170       ** is not applicable to this transaction, call sqlite3JournalCreate()
43171       ** to make sure the journal file has actually been created, then call
43172       ** pager_incr_changecounter() to update the change-counter in indirect
43173       ** mode. 
43174       **
43175       ** Otherwise, if the optimization is both enabled and applicable,
43176       ** then call pager_incr_changecounter() to update the change-counter
43177       ** in 'direct' mode. In this case the journal file will never be
43178       ** created for this transaction.
43179       */
43180   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43181       PgHdr *pPg;
43182       assert( isOpen(pPager->jfd) 
43183            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
43184            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
43185       );
43186       if( !zMaster && isOpen(pPager->jfd) 
43187        && pPager->journalOff==jrnlBufferSize(pPager) 
43188        && pPager->dbSize>=pPager->dbOrigSize
43189        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
43190       ){
43191         /* Update the db file change counter via the direct-write method. The 
43192         ** following call will modify the in-memory representation of page 1 
43193         ** to include the updated change counter and then write page 1 
43194         ** directly to the database file. Because of the atomic-write 
43195         ** property of the host file-system, this is safe.
43196         */
43197         rc = pager_incr_changecounter(pPager, 1);
43198       }else{
43199         rc = sqlite3JournalCreate(pPager->jfd);
43200         if( rc==SQLITE_OK ){
43201           rc = pager_incr_changecounter(pPager, 0);
43202         }
43203       }
43204   #else
43205       rc = pager_incr_changecounter(pPager, 0);
43206   #endif
43207       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43208   
43209       /* If this transaction has made the database smaller, then all pages
43210       ** being discarded by the truncation must be written to the journal
43211       ** file.
43212       **
43213       ** Before reading the pages with page numbers larger than the 
43214       ** current value of Pager.dbSize, set dbSize back to the value
43215       ** that it took at the start of the transaction. Otherwise, the
43216       ** calls to sqlite3PagerGet() return zeroed pages instead of 
43217       ** reading data from the database file.
43218       */
43219       if( pPager->dbSize<pPager->dbOrigSize 
43220        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
43221       ){
43222         Pgno i;                                   /* Iterator variable */
43223         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
43224         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
43225         pPager->dbSize = pPager->dbOrigSize;
43226         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
43227           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
43228             PgHdr *pPage;             /* Page to journal */
43229             rc = sqlite3PagerGet(pPager, i, &pPage);
43230             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43231             rc = sqlite3PagerWrite(pPage);
43232             sqlite3PagerUnref(pPage);
43233             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43234           }
43235         }
43236         pPager->dbSize = dbSize;
43237       } 
43238   
43239       /* Write the master journal name into the journal file. If a master 
43240       ** journal file name has already been written to the journal file, 
43241       ** or if zMaster is NULL (no master journal), then this call is a no-op.
43242       */
43243       rc = writeMasterJournal(pPager, zMaster);
43244       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43245   
43246       /* Sync the journal file and write all dirty pages to the database.
43247       ** If the atomic-update optimization is being used, this sync will not 
43248       ** create the journal file or perform any real IO.
43249       **
43250       ** Because the change-counter page was just modified, unless the
43251       ** atomic-update optimization is used it is almost certain that the
43252       ** journal requires a sync here. However, in locking_mode=exclusive
43253       ** on a system under memory pressure it is just possible that this is 
43254       ** not the case. In this case it is likely enough that the redundant
43255       ** xSync() call will be changed to a no-op by the OS anyhow. 
43256       */
43257       rc = syncJournal(pPager, 0);
43258       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43259   
43260       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
43261       if( rc!=SQLITE_OK ){
43262         assert( rc!=SQLITE_IOERR_BLOCKED );
43263         goto commit_phase_one_exit;
43264       }
43265       sqlite3PcacheCleanAll(pPager->pPCache);
43266   
43267       /* If the file on disk is not the same size as the database image,
43268       ** then use pager_truncate to grow or shrink the file here.
43269       */
43270       if( pPager->dbSize!=pPager->dbFileSize ){
43271         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
43272         assert( pPager->eState==PAGER_WRITER_DBMOD );
43273         rc = pager_truncate(pPager, nNew);
43274         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43275       }
43276   
43277       /* Finally, sync the database file. */
43278       if( !noSync ){
43279         rc = sqlite3PagerSync(pPager);
43280       }
43281       IOTRACE(("DBSYNC %p\n", pPager))
43282     }
43283   }
43284
43285 commit_phase_one_exit:
43286   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
43287     pPager->eState = PAGER_WRITER_FINISHED;
43288   }
43289   return rc;
43290 }
43291
43292
43293 /*
43294 ** When this function is called, the database file has been completely
43295 ** updated to reflect the changes made by the current transaction and
43296 ** synced to disk. The journal file still exists in the file-system 
43297 ** though, and if a failure occurs at this point it will eventually
43298 ** be used as a hot-journal and the current transaction rolled back.
43299 **
43300 ** This function finalizes the journal file, either by deleting, 
43301 ** truncating or partially zeroing it, so that it cannot be used 
43302 ** for hot-journal rollback. Once this is done the transaction is
43303 ** irrevocably committed.
43304 **
43305 ** If an error occurs, an IO error code is returned and the pager
43306 ** moves into the error state. Otherwise, SQLITE_OK is returned.
43307 */
43308 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
43309   int rc = SQLITE_OK;                  /* Return code */
43310
43311   /* This routine should not be called if a prior error has occurred.
43312   ** But if (due to a coding error elsewhere in the system) it does get
43313   ** called, just return the same error code without doing anything. */
43314   if( NEVER(pPager->errCode) ) return pPager->errCode;
43315
43316   assert( pPager->eState==PAGER_WRITER_LOCKED
43317        || pPager->eState==PAGER_WRITER_FINISHED
43318        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
43319   );
43320   assert( assert_pager_state(pPager) );
43321
43322   /* An optimization. If the database was not actually modified during
43323   ** this transaction, the pager is running in exclusive-mode and is
43324   ** using persistent journals, then this function is a no-op.
43325   **
43326   ** The start of the journal file currently contains a single journal 
43327   ** header with the nRec field set to 0. If such a journal is used as
43328   ** a hot-journal during hot-journal rollback, 0 changes will be made
43329   ** to the database file. So there is no need to zero the journal 
43330   ** header. Since the pager is in exclusive mode, there is no need
43331   ** to drop any locks either.
43332   */
43333   if( pPager->eState==PAGER_WRITER_LOCKED 
43334    && pPager->exclusiveMode 
43335    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43336   ){
43337     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
43338     pPager->eState = PAGER_READER;
43339     return SQLITE_OK;
43340   }
43341
43342   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
43343   rc = pager_end_transaction(pPager, pPager->setMaster);
43344   return pager_error(pPager, rc);
43345 }
43346
43347 /*
43348 ** If a write transaction is open, then all changes made within the 
43349 ** transaction are reverted and the current write-transaction is closed.
43350 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
43351 ** state if an error occurs.
43352 **
43353 ** If the pager is already in PAGER_ERROR state when this function is called,
43354 ** it returns Pager.errCode immediately. No work is performed in this case.
43355 **
43356 ** Otherwise, in rollback mode, this function performs two functions:
43357 **
43358 **   1) It rolls back the journal file, restoring all database file and 
43359 **      in-memory cache pages to the state they were in when the transaction
43360 **      was opened, and
43361 **
43362 **   2) It finalizes the journal file, so that it is not used for hot
43363 **      rollback at any point in the future.
43364 **
43365 ** Finalization of the journal file (task 2) is only performed if the 
43366 ** rollback is successful.
43367 **
43368 ** In WAL mode, all cache-entries containing data modified within the
43369 ** current transaction are either expelled from the cache or reverted to
43370 ** their pre-transaction state by re-reading data from the database or
43371 ** WAL files. The WAL transaction is then closed.
43372 */
43373 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
43374   int rc = SQLITE_OK;                  /* Return code */
43375   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
43376
43377   /* PagerRollback() is a no-op if called in READER or OPEN state. If
43378   ** the pager is already in the ERROR state, the rollback is not 
43379   ** attempted here. Instead, the error code is returned to the caller.
43380   */
43381   assert( assert_pager_state(pPager) );
43382   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
43383   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
43384
43385   if( pagerUseWal(pPager) ){
43386     int rc2;
43387     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43388     rc2 = pager_end_transaction(pPager, pPager->setMaster);
43389     if( rc==SQLITE_OK ) rc = rc2;
43390   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43391     int eState = pPager->eState;
43392     rc = pager_end_transaction(pPager, 0);
43393     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43394       /* This can happen using journal_mode=off. Move the pager to the error 
43395       ** state to indicate that the contents of the cache may not be trusted.
43396       ** Any active readers will get SQLITE_ABORT.
43397       */
43398       pPager->errCode = SQLITE_ABORT;
43399       pPager->eState = PAGER_ERROR;
43400       return rc;
43401     }
43402   }else{
43403     rc = pager_playback(pPager, 0);
43404   }
43405
43406   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43407   assert( rc==SQLITE_OK || rc==SQLITE_FULL
43408           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
43409
43410   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43411   ** cache. So call pager_error() on the way out to make any error persistent.
43412   */
43413   return pager_error(pPager, rc);
43414 }
43415
43416 /*
43417 ** Return TRUE if the database file is opened read-only.  Return FALSE
43418 ** if the database is (in theory) writable.
43419 */
43420 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43421   return pPager->readOnly;
43422 }
43423
43424 /*
43425 ** Return the number of references to the pager.
43426 */
43427 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43428   return sqlite3PcacheRefCount(pPager->pPCache);
43429 }
43430
43431 /*
43432 ** Return the approximate number of bytes of memory currently
43433 ** used by the pager and its associated cache.
43434 */
43435 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43436   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43437                                      + 5*sizeof(void*);
43438   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43439            + sqlite3MallocSize(pPager)
43440            + pPager->pageSize;
43441 }
43442
43443 /*
43444 ** Return the number of references to the specified page.
43445 */
43446 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43447   return sqlite3PcachePageRefcount(pPage);
43448 }
43449
43450 #ifdef SQLITE_TEST
43451 /*
43452 ** This routine is used for testing and analysis only.
43453 */
43454 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43455   static int a[11];
43456   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43457   a[1] = sqlite3PcachePagecount(pPager->pPCache);
43458   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43459   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43460   a[4] = pPager->eState;
43461   a[5] = pPager->errCode;
43462   a[6] = pPager->aStat[PAGER_STAT_HIT];
43463   a[7] = pPager->aStat[PAGER_STAT_MISS];
43464   a[8] = 0;  /* Used to be pPager->nOvfl */
43465   a[9] = pPager->nRead;
43466   a[10] = pPager->aStat[PAGER_STAT_WRITE];
43467   return a;
43468 }
43469 #endif
43470
43471 /*
43472 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
43473 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
43474 ** current cache hit or miss count, according to the value of eStat. If the 
43475 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
43476 ** returning.
43477 */
43478 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
43479
43480   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
43481        || eStat==SQLITE_DBSTATUS_CACHE_MISS
43482        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
43483   );
43484
43485   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
43486   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
43487   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
43488
43489   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
43490   if( reset ){
43491     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
43492   }
43493 }
43494
43495 /*
43496 ** Return true if this is an in-memory pager.
43497 */
43498 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43499   return MEMDB;
43500 }
43501
43502 /*
43503 ** Check that there are at least nSavepoint savepoints open. If there are
43504 ** currently less than nSavepoints open, then open one or more savepoints
43505 ** to make up the difference. If the number of savepoints is already
43506 ** equal to nSavepoint, then this function is a no-op.
43507 **
43508 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
43509 ** occurs while opening the sub-journal file, then an IO error code is
43510 ** returned. Otherwise, SQLITE_OK.
43511 */
43512 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43513   int rc = SQLITE_OK;                       /* Return code */
43514   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
43515
43516   assert( pPager->eState>=PAGER_WRITER_LOCKED );
43517   assert( assert_pager_state(pPager) );
43518
43519   if( nSavepoint>nCurrent && pPager->useJournal ){
43520     int ii;                                 /* Iterator variable */
43521     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
43522
43523     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43524     ** if the allocation fails. Otherwise, zero the new portion in case a 
43525     ** malloc failure occurs while populating it in the for(...) loop below.
43526     */
43527     aNew = (PagerSavepoint *)sqlite3Realloc(
43528         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43529     );
43530     if( !aNew ){
43531       return SQLITE_NOMEM;
43532     }
43533     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43534     pPager->aSavepoint = aNew;
43535
43536     /* Populate the PagerSavepoint structures just allocated. */
43537     for(ii=nCurrent; ii<nSavepoint; ii++){
43538       aNew[ii].nOrig = pPager->dbSize;
43539       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43540         aNew[ii].iOffset = pPager->journalOff;
43541       }else{
43542         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43543       }
43544       aNew[ii].iSubRec = pPager->nSubRec;
43545       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43546       if( !aNew[ii].pInSavepoint ){
43547         return SQLITE_NOMEM;
43548       }
43549       if( pagerUseWal(pPager) ){
43550         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43551       }
43552       pPager->nSavepoint = ii+1;
43553     }
43554     assert( pPager->nSavepoint==nSavepoint );
43555     assertTruncateConstraint(pPager);
43556   }
43557
43558   return rc;
43559 }
43560
43561 /*
43562 ** This function is called to rollback or release (commit) a savepoint.
43563 ** The savepoint to release or rollback need not be the most recently 
43564 ** created savepoint.
43565 **
43566 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43567 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43568 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43569 ** that have occurred since the specified savepoint was created.
43570 **
43571 ** The savepoint to rollback or release is identified by parameter 
43572 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43573 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43574 ** on the most recently created savepoint. If iSavepoint is greater than
43575 ** (Pager.nSavepoint-1), then this function is a no-op.
43576 **
43577 ** If a negative value is passed to this function, then the current
43578 ** transaction is rolled back. This is different to calling 
43579 ** sqlite3PagerRollback() because this function does not terminate
43580 ** the transaction or unlock the database, it just restores the 
43581 ** contents of the database to its original state. 
43582 **
43583 ** In any case, all savepoints with an index greater than iSavepoint 
43584 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43585 ** then savepoint iSavepoint is also destroyed.
43586 **
43587 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43588 ** or an IO error code if an IO error occurs while rolling back a 
43589 ** savepoint. If no errors occur, SQLITE_OK is returned.
43590 */ 
43591 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43592   int rc = pPager->errCode;       /* Return code */
43593
43594   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43595   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43596
43597   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43598     int ii;            /* Iterator variable */
43599     int nNew;          /* Number of remaining savepoints after this op. */
43600
43601     /* Figure out how many savepoints will still be active after this
43602     ** operation. Store this value in nNew. Then free resources associated 
43603     ** with any savepoints that are destroyed by this operation.
43604     */
43605     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43606     for(ii=nNew; ii<pPager->nSavepoint; ii++){
43607       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43608     }
43609     pPager->nSavepoint = nNew;
43610
43611     /* If this is a release of the outermost savepoint, truncate 
43612     ** the sub-journal to zero bytes in size. */
43613     if( op==SAVEPOINT_RELEASE ){
43614       if( nNew==0 && isOpen(pPager->sjfd) ){
43615         /* Only truncate if it is an in-memory sub-journal. */
43616         if( sqlite3IsMemJournal(pPager->sjfd) ){
43617           rc = sqlite3OsTruncate(pPager->sjfd, 0);
43618           assert( rc==SQLITE_OK );
43619         }
43620         pPager->nSubRec = 0;
43621       }
43622     }
43623     /* Else this is a rollback operation, playback the specified savepoint.
43624     ** If this is a temp-file, it is possible that the journal file has
43625     ** not yet been opened. In this case there have been no changes to
43626     ** the database file, so the playback operation can be skipped.
43627     */
43628     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43629       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43630       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43631       assert(rc!=SQLITE_DONE);
43632     }
43633   }
43634
43635   return rc;
43636 }
43637
43638 /*
43639 ** Return the full pathname of the database file.
43640 **
43641 ** Except, if the pager is in-memory only, then return an empty string if
43642 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
43643 ** used to report the filename to the user, for compatibility with legacy
43644 ** behavior.  But when the Btree needs to know the filename for matching to
43645 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
43646 ** participate in shared-cache.
43647 */
43648 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
43649   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
43650 }
43651
43652 /*
43653 ** Return the VFS structure for the pager.
43654 */
43655 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43656   return pPager->pVfs;
43657 }
43658
43659 /*
43660 ** Return the file handle for the database file associated
43661 ** with the pager.  This might return NULL if the file has
43662 ** not yet been opened.
43663 */
43664 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43665   return pPager->fd;
43666 }
43667
43668 /*
43669 ** Return the full pathname of the journal file.
43670 */
43671 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43672   return pPager->zJournal;
43673 }
43674
43675 /*
43676 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43677 ** if fsync()s are executed normally.
43678 */
43679 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43680   return pPager->noSync;
43681 }
43682
43683 #ifdef SQLITE_HAS_CODEC
43684 /*
43685 ** Set or retrieve the codec for this pager
43686 */
43687 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43688   Pager *pPager,
43689   void *(*xCodec)(void*,void*,Pgno,int),
43690   void (*xCodecSizeChng)(void*,int,int),
43691   void (*xCodecFree)(void*),
43692   void *pCodec
43693 ){
43694   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43695   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43696   pPager->xCodecSizeChng = xCodecSizeChng;
43697   pPager->xCodecFree = xCodecFree;
43698   pPager->pCodec = pCodec;
43699   pagerReportSize(pPager);
43700 }
43701 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43702   return pPager->pCodec;
43703 }
43704 #endif
43705
43706 #ifndef SQLITE_OMIT_AUTOVACUUM
43707 /*
43708 ** Move the page pPg to location pgno in the file.
43709 **
43710 ** There must be no references to the page previously located at
43711 ** pgno (which we call pPgOld) though that page is allowed to be
43712 ** in cache.  If the page previously located at pgno is not already
43713 ** in the rollback journal, it is not put there by by this routine.
43714 **
43715 ** References to the page pPg remain valid. Updating any
43716 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43717 ** allocated along with the page) is the responsibility of the caller.
43718 **
43719 ** A transaction must be active when this routine is called. It used to be
43720 ** required that a statement transaction was not active, but this restriction
43721 ** has been removed (CREATE INDEX needs to move a page when a statement
43722 ** transaction is active).
43723 **
43724 ** If the fourth argument, isCommit, is non-zero, then this page is being
43725 ** moved as part of a database reorganization just before the transaction 
43726 ** is being committed. In this case, it is guaranteed that the database page 
43727 ** pPg refers to will not be written to again within this transaction.
43728 **
43729 ** This function may return SQLITE_NOMEM or an IO error code if an error
43730 ** occurs. Otherwise, it returns SQLITE_OK.
43731 */
43732 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43733   PgHdr *pPgOld;               /* The page being overwritten. */
43734   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43735   int rc;                      /* Return code */
43736   Pgno origPgno;               /* The original page number */
43737
43738   assert( pPg->nRef>0 );
43739   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43740        || pPager->eState==PAGER_WRITER_DBMOD
43741   );
43742   assert( assert_pager_state(pPager) );
43743
43744   /* In order to be able to rollback, an in-memory database must journal
43745   ** the page we are moving from.
43746   */
43747   if( MEMDB ){
43748     rc = sqlite3PagerWrite(pPg);
43749     if( rc ) return rc;
43750   }
43751
43752   /* If the page being moved is dirty and has not been saved by the latest
43753   ** savepoint, then save the current contents of the page into the 
43754   ** sub-journal now. This is required to handle the following scenario:
43755   **
43756   **   BEGIN;
43757   **     <journal page X, then modify it in memory>
43758   **     SAVEPOINT one;
43759   **       <Move page X to location Y>
43760   **     ROLLBACK TO one;
43761   **
43762   ** If page X were not written to the sub-journal here, it would not
43763   ** be possible to restore its contents when the "ROLLBACK TO one"
43764   ** statement were is processed.
43765   **
43766   ** subjournalPage() may need to allocate space to store pPg->pgno into
43767   ** one or more savepoint bitvecs. This is the reason this function
43768   ** may return SQLITE_NOMEM.
43769   */
43770   if( pPg->flags&PGHDR_DIRTY
43771    && subjRequiresPage(pPg)
43772    && SQLITE_OK!=(rc = subjournalPage(pPg))
43773   ){
43774     return rc;
43775   }
43776
43777   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
43778       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43779   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43780
43781   /* If the journal needs to be sync()ed before page pPg->pgno can
43782   ** be written to, store pPg->pgno in local variable needSyncPgno.
43783   **
43784   ** If the isCommit flag is set, there is no need to remember that
43785   ** the journal needs to be sync()ed before database page pPg->pgno 
43786   ** can be written to. The caller has already promised not to write to it.
43787   */
43788   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43789     needSyncPgno = pPg->pgno;
43790     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43791     assert( pPg->flags&PGHDR_DIRTY );
43792   }
43793
43794   /* If the cache contains a page with page-number pgno, remove it
43795   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
43796   ** page pgno before the 'move' operation, it needs to be retained 
43797   ** for the page moved there.
43798   */
43799   pPg->flags &= ~PGHDR_NEED_SYNC;
43800   pPgOld = pager_lookup(pPager, pgno);
43801   assert( !pPgOld || pPgOld->nRef==1 );
43802   if( pPgOld ){
43803     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43804     if( MEMDB ){
43805       /* Do not discard pages from an in-memory database since we might
43806       ** need to rollback later.  Just move the page out of the way. */
43807       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43808     }else{
43809       sqlite3PcacheDrop(pPgOld);
43810     }
43811   }
43812
43813   origPgno = pPg->pgno;
43814   sqlite3PcacheMove(pPg, pgno);
43815   sqlite3PcacheMakeDirty(pPg);
43816
43817   /* For an in-memory database, make sure the original page continues
43818   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43819   ** as the original page since it has already been allocated.
43820   */
43821   if( MEMDB ){
43822     assert( pPgOld );
43823     sqlite3PcacheMove(pPgOld, origPgno);
43824     sqlite3PagerUnref(pPgOld);
43825   }
43826
43827   if( needSyncPgno ){
43828     /* If needSyncPgno is non-zero, then the journal file needs to be 
43829     ** sync()ed before any data is written to database file page needSyncPgno.
43830     ** Currently, no such page exists in the page-cache and the 
43831     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43832     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43833     ** flag.
43834     **
43835     ** If the attempt to load the page into the page-cache fails, (due
43836     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43837     ** array. Otherwise, if the page is loaded and written again in
43838     ** this transaction, it may be written to the database file before
43839     ** it is synced into the journal file. This way, it may end up in
43840     ** the journal file twice, but that is not a problem.
43841     */
43842     PgHdr *pPgHdr;
43843     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43844     if( rc!=SQLITE_OK ){
43845       if( needSyncPgno<=pPager->dbOrigSize ){
43846         assert( pPager->pTmpSpace!=0 );
43847         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43848       }
43849       return rc;
43850     }
43851     pPgHdr->flags |= PGHDR_NEED_SYNC;
43852     sqlite3PcacheMakeDirty(pPgHdr);
43853     sqlite3PagerUnref(pPgHdr);
43854   }
43855
43856   return SQLITE_OK;
43857 }
43858 #endif
43859
43860 /*
43861 ** Return a pointer to the data for the specified page.
43862 */
43863 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43864   assert( pPg->nRef>0 || pPg->pPager->memDb );
43865   return pPg->pData;
43866 }
43867
43868 /*
43869 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
43870 ** allocated along with the specified page.
43871 */
43872 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43873   return pPg->pExtra;
43874 }
43875
43876 /*
43877 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43878 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
43879 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43880 ** the locking-mode is set to the value specified.
43881 **
43882 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43883 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43884 ** locking-mode.
43885 */
43886 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43887   assert( eMode==PAGER_LOCKINGMODE_QUERY
43888             || eMode==PAGER_LOCKINGMODE_NORMAL
43889             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43890   assert( PAGER_LOCKINGMODE_QUERY<0 );
43891   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43892   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43893   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43894     pPager->exclusiveMode = (u8)eMode;
43895   }
43896   return (int)pPager->exclusiveMode;
43897 }
43898
43899 /*
43900 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43901 **
43902 **    PAGER_JOURNALMODE_DELETE
43903 **    PAGER_JOURNALMODE_TRUNCATE
43904 **    PAGER_JOURNALMODE_PERSIST
43905 **    PAGER_JOURNALMODE_OFF
43906 **    PAGER_JOURNALMODE_MEMORY
43907 **    PAGER_JOURNALMODE_WAL
43908 **
43909 ** The journalmode is set to the value specified if the change is allowed.
43910 ** The change may be disallowed for the following reasons:
43911 **
43912 **   *  An in-memory database can only have its journal_mode set to _OFF
43913 **      or _MEMORY.
43914 **
43915 **   *  Temporary databases cannot have _WAL journalmode.
43916 **
43917 ** The returned indicate the current (possibly updated) journal-mode.
43918 */
43919 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43920   u8 eOld = pPager->journalMode;    /* Prior journalmode */
43921
43922 #ifdef SQLITE_DEBUG
43923   /* The print_pager_state() routine is intended to be used by the debugger
43924   ** only.  We invoke it once here to suppress a compiler warning. */
43925   print_pager_state(pPager);
43926 #endif
43927
43928
43929   /* The eMode parameter is always valid */
43930   assert(      eMode==PAGER_JOURNALMODE_DELETE
43931             || eMode==PAGER_JOURNALMODE_TRUNCATE
43932             || eMode==PAGER_JOURNALMODE_PERSIST
43933             || eMode==PAGER_JOURNALMODE_OFF 
43934             || eMode==PAGER_JOURNALMODE_WAL 
43935             || eMode==PAGER_JOURNALMODE_MEMORY );
43936
43937   /* This routine is only called from the OP_JournalMode opcode, and
43938   ** the logic there will never allow a temporary file to be changed
43939   ** to WAL mode.
43940   */
43941   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43942
43943   /* Do allow the journalmode of an in-memory database to be set to
43944   ** anything other than MEMORY or OFF
43945   */
43946   if( MEMDB ){
43947     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43948     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43949       eMode = eOld;
43950     }
43951   }
43952
43953   if( eMode!=eOld ){
43954
43955     /* Change the journal mode. */
43956     assert( pPager->eState!=PAGER_ERROR );
43957     pPager->journalMode = (u8)eMode;
43958
43959     /* When transistioning from TRUNCATE or PERSIST to any other journal
43960     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43961     ** delete the journal file.
43962     */
43963     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43964     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43965     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43966     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43967     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43968     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43969
43970     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43971     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43972
43973       /* In this case we would like to delete the journal file. If it is
43974       ** not possible, then that is not a problem. Deleting the journal file
43975       ** here is an optimization only.
43976       **
43977       ** Before deleting the journal file, obtain a RESERVED lock on the
43978       ** database file. This ensures that the journal file is not deleted
43979       ** while it is in use by some other client.
43980       */
43981       sqlite3OsClose(pPager->jfd);
43982       if( pPager->eLock>=RESERVED_LOCK ){
43983         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43984       }else{
43985         int rc = SQLITE_OK;
43986         int state = pPager->eState;
43987         assert( state==PAGER_OPEN || state==PAGER_READER );
43988         if( state==PAGER_OPEN ){
43989           rc = sqlite3PagerSharedLock(pPager);
43990         }
43991         if( pPager->eState==PAGER_READER ){
43992           assert( rc==SQLITE_OK );
43993           rc = pagerLockDb(pPager, RESERVED_LOCK);
43994         }
43995         if( rc==SQLITE_OK ){
43996           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43997         }
43998         if( rc==SQLITE_OK && state==PAGER_READER ){
43999           pagerUnlockDb(pPager, SHARED_LOCK);
44000         }else if( state==PAGER_OPEN ){
44001           pager_unlock(pPager);
44002         }
44003         assert( state==pPager->eState );
44004       }
44005     }
44006   }
44007
44008   /* Return the new journal mode */
44009   return (int)pPager->journalMode;
44010 }
44011
44012 /*
44013 ** Return the current journal mode.
44014 */
44015 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
44016   return (int)pPager->journalMode;
44017 }
44018
44019 /*
44020 ** Return TRUE if the pager is in a state where it is OK to change the
44021 ** journalmode.  Journalmode changes can only happen when the database
44022 ** is unmodified.
44023 */
44024 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
44025   assert( assert_pager_state(pPager) );
44026   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
44027   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
44028   return 1;
44029 }
44030
44031 /*
44032 ** Get/set the size-limit used for persistent journal files.
44033 **
44034 ** Setting the size limit to -1 means no limit is enforced.
44035 ** An attempt to set a limit smaller than -1 is a no-op.
44036 */
44037 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
44038   if( iLimit>=-1 ){
44039     pPager->journalSizeLimit = iLimit;
44040     sqlite3WalLimit(pPager->pWal, iLimit);
44041   }
44042   return pPager->journalSizeLimit;
44043 }
44044
44045 /*
44046 ** Return a pointer to the pPager->pBackup variable. The backup module
44047 ** in backup.c maintains the content of this variable. This module
44048 ** uses it opaquely as an argument to sqlite3BackupRestart() and
44049 ** sqlite3BackupUpdate() only.
44050 */
44051 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
44052   return &pPager->pBackup;
44053 }
44054
44055 #ifndef SQLITE_OMIT_VACUUM
44056 /*
44057 ** Unless this is an in-memory or temporary database, clear the pager cache.
44058 */
44059 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
44060   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
44061 }
44062 #endif
44063
44064 #ifndef SQLITE_OMIT_WAL
44065 /*
44066 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
44067 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
44068 ** or wal_blocking_checkpoint() API functions.
44069 **
44070 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
44071 */
44072 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
44073   int rc = SQLITE_OK;
44074   if( pPager->pWal ){
44075     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
44076         pPager->xBusyHandler, pPager->pBusyHandlerArg,
44077         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
44078         pnLog, pnCkpt
44079     );
44080   }
44081   return rc;
44082 }
44083
44084 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
44085   return sqlite3WalCallback(pPager->pWal);
44086 }
44087
44088 /*
44089 ** Return true if the underlying VFS for the given pager supports the
44090 ** primitives necessary for write-ahead logging.
44091 */
44092 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
44093   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
44094   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
44095 }
44096
44097 /*
44098 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
44099 ** is obtained instead, immediately release it.
44100 */
44101 static int pagerExclusiveLock(Pager *pPager){
44102   int rc;                         /* Return code */
44103
44104   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44105   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44106   if( rc!=SQLITE_OK ){
44107     /* If the attempt to grab the exclusive lock failed, release the 
44108     ** pending lock that may have been obtained instead.  */
44109     pagerUnlockDb(pPager, SHARED_LOCK);
44110   }
44111
44112   return rc;
44113 }
44114
44115 /*
44116 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
44117 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
44118 ** lock on the database file and use heap-memory to store the wal-index
44119 ** in. Otherwise, use the normal shared-memory.
44120 */
44121 static int pagerOpenWal(Pager *pPager){
44122   int rc = SQLITE_OK;
44123
44124   assert( pPager->pWal==0 && pPager->tempFile==0 );
44125   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44126
44127   /* If the pager is already in exclusive-mode, the WAL module will use 
44128   ** heap-memory for the wal-index instead of the VFS shared-memory 
44129   ** implementation. Take the exclusive lock now, before opening the WAL
44130   ** file, to make sure this is safe.
44131   */
44132   if( pPager->exclusiveMode ){
44133     rc = pagerExclusiveLock(pPager);
44134   }
44135
44136   /* Open the connection to the log file. If this operation fails, 
44137   ** (e.g. due to malloc() failure), return an error code.
44138   */
44139   if( rc==SQLITE_OK ){
44140     rc = sqlite3WalOpen(pPager->pVfs, 
44141         pPager->fd, pPager->zWal, pPager->exclusiveMode,
44142         pPager->journalSizeLimit, &pPager->pWal
44143     );
44144   }
44145
44146   return rc;
44147 }
44148
44149
44150 /*
44151 ** The caller must be holding a SHARED lock on the database file to call
44152 ** this function.
44153 **
44154 ** If the pager passed as the first argument is open on a real database
44155 ** file (not a temp file or an in-memory database), and the WAL file
44156 ** is not already open, make an attempt to open it now. If successful,
44157 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
44158 ** not support the xShmXXX() methods, return an error code. *pbOpen is
44159 ** not modified in either case.
44160 **
44161 ** If the pager is open on a temp-file (or in-memory database), or if
44162 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
44163 ** without doing anything.
44164 */
44165 SQLITE_PRIVATE int sqlite3PagerOpenWal(
44166   Pager *pPager,                  /* Pager object */
44167   int *pbOpen                     /* OUT: Set to true if call is a no-op */
44168 ){
44169   int rc = SQLITE_OK;             /* Return code */
44170
44171   assert( assert_pager_state(pPager) );
44172   assert( pPager->eState==PAGER_OPEN   || pbOpen );
44173   assert( pPager->eState==PAGER_READER || !pbOpen );
44174   assert( pbOpen==0 || *pbOpen==0 );
44175   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
44176
44177   if( !pPager->tempFile && !pPager->pWal ){
44178     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
44179
44180     /* Close any rollback journal previously open */
44181     sqlite3OsClose(pPager->jfd);
44182
44183     rc = pagerOpenWal(pPager);
44184     if( rc==SQLITE_OK ){
44185       pPager->journalMode = PAGER_JOURNALMODE_WAL;
44186       pPager->eState = PAGER_OPEN;
44187     }
44188   }else{
44189     *pbOpen = 1;
44190   }
44191
44192   return rc;
44193 }
44194
44195 /*
44196 ** This function is called to close the connection to the log file prior
44197 ** to switching from WAL to rollback mode.
44198 **
44199 ** Before closing the log file, this function attempts to take an 
44200 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
44201 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
44202 ** If successful, the EXCLUSIVE lock is not released before returning.
44203 */
44204 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
44205   int rc = SQLITE_OK;
44206
44207   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
44208
44209   /* If the log file is not already open, but does exist in the file-system,
44210   ** it may need to be checkpointed before the connection can switch to
44211   ** rollback mode. Open it now so this can happen.
44212   */
44213   if( !pPager->pWal ){
44214     int logexists = 0;
44215     rc = pagerLockDb(pPager, SHARED_LOCK);
44216     if( rc==SQLITE_OK ){
44217       rc = sqlite3OsAccess(
44218           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
44219       );
44220     }
44221     if( rc==SQLITE_OK && logexists ){
44222       rc = pagerOpenWal(pPager);
44223     }
44224   }
44225     
44226   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
44227   ** the database file, the log and log-summary files will be deleted.
44228   */
44229   if( rc==SQLITE_OK && pPager->pWal ){
44230     rc = pagerExclusiveLock(pPager);
44231     if( rc==SQLITE_OK ){
44232       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
44233                            pPager->pageSize, (u8*)pPager->pTmpSpace);
44234       pPager->pWal = 0;
44235     }
44236   }
44237   return rc;
44238 }
44239
44240 #endif /* !SQLITE_OMIT_WAL */
44241
44242 #ifdef SQLITE_ENABLE_ZIPVFS
44243 /*
44244 ** A read-lock must be held on the pager when this function is called. If
44245 ** the pager is in WAL mode and the WAL file currently contains one or more
44246 ** frames, return the size in bytes of the page images stored within the
44247 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
44248 ** is empty, return 0.
44249 */
44250 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
44251   assert( pPager->eState==PAGER_READER );
44252   return sqlite3WalFramesize(pPager->pWal);
44253 }
44254 #endif
44255
44256 #ifdef SQLITE_HAS_CODEC
44257 /*
44258 ** This function is called by the wal module when writing page content
44259 ** into the log file.
44260 **
44261 ** This function returns a pointer to a buffer containing the encrypted
44262 ** page content. If a malloc fails, this function may return NULL.
44263 */
44264 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44265   void *aData = 0;
44266   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44267   return aData;
44268 }
44269 #endif /* SQLITE_HAS_CODEC */
44270
44271 #endif /* SQLITE_OMIT_DISKIO */
44272
44273 /************** End of pager.c ***********************************************/
44274 /************** Begin file wal.c *********************************************/
44275 /*
44276 ** 2010 February 1
44277 **
44278 ** The author disclaims copyright to this source code.  In place of
44279 ** a legal notice, here is a blessing:
44280 **
44281 **    May you do good and not evil.
44282 **    May you find forgiveness for yourself and forgive others.
44283 **    May you share freely, never taking more than you give.
44284 **
44285 *************************************************************************
44286 **
44287 ** This file contains the implementation of a write-ahead log (WAL) used in 
44288 ** "journal_mode=WAL" mode.
44289 **
44290 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
44291 **
44292 ** A WAL file consists of a header followed by zero or more "frames".
44293 ** Each frame records the revised content of a single page from the
44294 ** database file.  All changes to the database are recorded by writing
44295 ** frames into the WAL.  Transactions commit when a frame is written that
44296 ** contains a commit marker.  A single WAL can and usually does record 
44297 ** multiple transactions.  Periodically, the content of the WAL is
44298 ** transferred back into the database file in an operation called a
44299 ** "checkpoint".
44300 **
44301 ** A single WAL file can be used multiple times.  In other words, the
44302 ** WAL can fill up with frames and then be checkpointed and then new
44303 ** frames can overwrite the old ones.  A WAL always grows from beginning
44304 ** toward the end.  Checksums and counters attached to each frame are
44305 ** used to determine which frames within the WAL are valid and which
44306 ** are leftovers from prior checkpoints.
44307 **
44308 ** The WAL header is 32 bytes in size and consists of the following eight
44309 ** big-endian 32-bit unsigned integer values:
44310 **
44311 **     0: Magic number.  0x377f0682 or 0x377f0683
44312 **     4: File format version.  Currently 3007000
44313 **     8: Database page size.  Example: 1024
44314 **    12: Checkpoint sequence number
44315 **    16: Salt-1, random integer incremented with each checkpoint
44316 **    20: Salt-2, a different random integer changing with each ckpt
44317 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
44318 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
44319 **
44320 ** Immediately following the wal-header are zero or more frames. Each
44321 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
44322 ** of page data. The frame-header is six big-endian 32-bit unsigned 
44323 ** integer values, as follows:
44324 **
44325 **     0: Page number.
44326 **     4: For commit records, the size of the database image in pages 
44327 **        after the commit. For all other records, zero.
44328 **     8: Salt-1 (copied from the header)
44329 **    12: Salt-2 (copied from the header)
44330 **    16: Checksum-1.
44331 **    20: Checksum-2.
44332 **
44333 ** A frame is considered valid if and only if the following conditions are
44334 ** true:
44335 **
44336 **    (1) The salt-1 and salt-2 values in the frame-header match
44337 **        salt values in the wal-header
44338 **
44339 **    (2) The checksum values in the final 8 bytes of the frame-header
44340 **        exactly match the checksum computed consecutively on the
44341 **        WAL header and the first 8 bytes and the content of all frames
44342 **        up to and including the current frame.
44343 **
44344 ** The checksum is computed using 32-bit big-endian integers if the
44345 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
44346 ** is computed using little-endian if the magic number is 0x377f0682.
44347 ** The checksum values are always stored in the frame header in a
44348 ** big-endian format regardless of which byte order is used to compute
44349 ** the checksum.  The checksum is computed by interpreting the input as
44350 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
44351 ** algorithm used for the checksum is as follows:
44352 ** 
44353 **   for i from 0 to n-1 step 2:
44354 **     s0 += x[i] + s1;
44355 **     s1 += x[i+1] + s0;
44356 **   endfor
44357 **
44358 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
44359 ** in reverse order (the largest fibonacci weight occurs on the first element
44360 ** of the sequence being summed.)  The s1 value spans all 32-bit 
44361 ** terms of the sequence whereas s0 omits the final term.
44362 **
44363 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
44364 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
44365 ** The VFS.xSync operations serve as write barriers - all writes launched
44366 ** before the xSync must complete before any write that launches after the
44367 ** xSync begins.
44368 **
44369 ** After each checkpoint, the salt-1 value is incremented and the salt-2
44370 ** value is randomized.  This prevents old and new frames in the WAL from
44371 ** being considered valid at the same time and being checkpointing together
44372 ** following a crash.
44373 **
44374 ** READER ALGORITHM
44375 **
44376 ** To read a page from the database (call it page number P), a reader
44377 ** first checks the WAL to see if it contains page P.  If so, then the
44378 ** last valid instance of page P that is a followed by a commit frame
44379 ** or is a commit frame itself becomes the value read.  If the WAL
44380 ** contains no copies of page P that are valid and which are a commit
44381 ** frame or are followed by a commit frame, then page P is read from
44382 ** the database file.
44383 **
44384 ** To start a read transaction, the reader records the index of the last
44385 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
44386 ** for all subsequent read operations.  New transactions can be appended
44387 ** to the WAL, but as long as the reader uses its original mxFrame value
44388 ** and ignores the newly appended content, it will see a consistent snapshot
44389 ** of the database from a single point in time.  This technique allows
44390 ** multiple concurrent readers to view different versions of the database
44391 ** content simultaneously.
44392 **
44393 ** The reader algorithm in the previous paragraphs works correctly, but 
44394 ** because frames for page P can appear anywhere within the WAL, the
44395 ** reader has to scan the entire WAL looking for page P frames.  If the
44396 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44397 ** and read performance suffers.  To overcome this problem, a separate
44398 ** data structure called the wal-index is maintained to expedite the
44399 ** search for frames of a particular page.
44400 ** 
44401 ** WAL-INDEX FORMAT
44402 **
44403 ** Conceptually, the wal-index is shared memory, though VFS implementations
44404 ** might choose to implement the wal-index using a mmapped file.  Because
44405 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
44406 ** on a network filesystem.  All users of the database must be able to
44407 ** share memory.
44408 **
44409 ** The wal-index is transient.  After a crash, the wal-index can (and should
44410 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
44411 ** to either truncate or zero the header of the wal-index when the last
44412 ** connection to it closes.  Because the wal-index is transient, it can
44413 ** use an architecture-specific format; it does not have to be cross-platform.
44414 ** Hence, unlike the database and WAL file formats which store all values
44415 ** as big endian, the wal-index can store multi-byte values in the native
44416 ** byte order of the host computer.
44417 **
44418 ** The purpose of the wal-index is to answer this question quickly:  Given
44419 ** a page number P and a maximum frame index M, return the index of the 
44420 ** last frame in the wal before frame M for page P in the WAL, or return
44421 ** NULL if there are no frames for page P in the WAL prior to M.
44422 **
44423 ** The wal-index consists of a header region, followed by an one or
44424 ** more index blocks.  
44425 **
44426 ** The wal-index header contains the total number of frames within the WAL
44427 ** in the mxFrame field.
44428 **
44429 ** Each index block except for the first contains information on 
44430 ** HASHTABLE_NPAGE frames. The first index block contains information on
44431 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
44432 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44433 ** first index block are the same size as all other index blocks in the
44434 ** wal-index.
44435 **
44436 ** Each index block contains two sections, a page-mapping that contains the
44437 ** database page number associated with each wal frame, and a hash-table 
44438 ** that allows readers to query an index block for a specific page number.
44439 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44440 ** for the first index block) 32-bit page numbers. The first entry in the 
44441 ** first index-block contains the database page number corresponding to the
44442 ** first frame in the WAL file. The first entry in the second index block
44443 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44444 ** the log, and so on.
44445 **
44446 ** The last index block in a wal-index usually contains less than the full
44447 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44448 ** depending on the contents of the WAL file. This does not change the
44449 ** allocated size of the page-mapping array - the page-mapping array merely
44450 ** contains unused entries.
44451 **
44452 ** Even without using the hash table, the last frame for page P
44453 ** can be found by scanning the page-mapping sections of each index block
44454 ** starting with the last index block and moving toward the first, and
44455 ** within each index block, starting at the end and moving toward the
44456 ** beginning.  The first entry that equals P corresponds to the frame
44457 ** holding the content for that page.
44458 **
44459 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44460 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44461 ** hash table for each page number in the mapping section, so the hash 
44462 ** table is never more than half full.  The expected number of collisions 
44463 ** prior to finding a match is 1.  Each entry of the hash table is an
44464 ** 1-based index of an entry in the mapping section of the same
44465 ** index block.   Let K be the 1-based index of the largest entry in
44466 ** the mapping section.  (For index blocks other than the last, K will
44467 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44468 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
44469 ** contain a value of 0.
44470 **
44471 ** To look for page P in the hash table, first compute a hash iKey on
44472 ** P as follows:
44473 **
44474 **      iKey = (P * 383) % HASHTABLE_NSLOT
44475 **
44476 ** Then start scanning entries of the hash table, starting with iKey
44477 ** (wrapping around to the beginning when the end of the hash table is
44478 ** reached) until an unused hash slot is found. Let the first unused slot
44479 ** be at index iUnused.  (iUnused might be less than iKey if there was
44480 ** wrap-around.) Because the hash table is never more than half full,
44481 ** the search is guaranteed to eventually hit an unused entry.  Let 
44482 ** iMax be the value between iKey and iUnused, closest to iUnused,
44483 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
44484 ** no hash slot such that aHash[i]==p) then page P is not in the
44485 ** current index block.  Otherwise the iMax-th mapping entry of the
44486 ** current index block corresponds to the last entry that references 
44487 ** page P.
44488 **
44489 ** A hash search begins with the last index block and moves toward the
44490 ** first index block, looking for entries corresponding to page P.  On
44491 ** average, only two or three slots in each index block need to be
44492 ** examined in order to either find the last entry for page P, or to
44493 ** establish that no such entry exists in the block.  Each index block
44494 ** holds over 4000 entries.  So two or three index blocks are sufficient
44495 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
44496 ** comparisons (on average) suffice to either locate a frame in the
44497 ** WAL or to establish that the frame does not exist in the WAL.  This
44498 ** is much faster than scanning the entire 10MB WAL.
44499 **
44500 ** Note that entries are added in order of increasing K.  Hence, one
44501 ** reader might be using some value K0 and a second reader that started
44502 ** at a later time (after additional transactions were added to the WAL
44503 ** and to the wal-index) might be using a different value K1, where K1>K0.
44504 ** Both readers can use the same hash table and mapping section to get
44505 ** the correct result.  There may be entries in the hash table with
44506 ** K>K0 but to the first reader, those entries will appear to be unused
44507 ** slots in the hash table and so the first reader will get an answer as
44508 ** if no values greater than K0 had ever been inserted into the hash table
44509 ** in the first place - which is what reader one wants.  Meanwhile, the
44510 ** second reader using K1 will see additional values that were inserted
44511 ** later, which is exactly what reader two wants.  
44512 **
44513 ** When a rollback occurs, the value of K is decreased. Hash table entries
44514 ** that correspond to frames greater than the new K value are removed
44515 ** from the hash table at this point.
44516 */
44517 #ifndef SQLITE_OMIT_WAL
44518
44519
44520 /*
44521 ** Trace output macros
44522 */
44523 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44524 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44525 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
44526 #else
44527 # define WALTRACE(X)
44528 #endif
44529
44530 /*
44531 ** The maximum (and only) versions of the wal and wal-index formats
44532 ** that may be interpreted by this version of SQLite.
44533 **
44534 ** If a client begins recovering a WAL file and finds that (a) the checksum
44535 ** values in the wal-header are correct and (b) the version field is not
44536 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44537 **
44538 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
44539 ** checksum test is successful) and finds that the version field is not
44540 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44541 ** returns SQLITE_CANTOPEN.
44542 */
44543 #define WAL_MAX_VERSION      3007000
44544 #define WALINDEX_MAX_VERSION 3007000
44545
44546 /*
44547 ** Indices of various locking bytes.   WAL_NREADER is the number
44548 ** of available reader locks and should be at least 3.
44549 */
44550 #define WAL_WRITE_LOCK         0
44551 #define WAL_ALL_BUT_WRITE      1
44552 #define WAL_CKPT_LOCK          1
44553 #define WAL_RECOVER_LOCK       2
44554 #define WAL_READ_LOCK(I)       (3+(I))
44555 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
44556
44557
44558 /* Object declarations */
44559 typedef struct WalIndexHdr WalIndexHdr;
44560 typedef struct WalIterator WalIterator;
44561 typedef struct WalCkptInfo WalCkptInfo;
44562
44563
44564 /*
44565 ** The following object holds a copy of the wal-index header content.
44566 **
44567 ** The actual header in the wal-index consists of two copies of this
44568 ** object.
44569 **
44570 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44571 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
44572 ** added in 3.7.1 when support for 64K pages was added.  
44573 */
44574 struct WalIndexHdr {
44575   u32 iVersion;                   /* Wal-index version */
44576   u32 unused;                     /* Unused (padding) field */
44577   u32 iChange;                    /* Counter incremented each transaction */
44578   u8 isInit;                      /* 1 when initialized */
44579   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
44580   u16 szPage;                     /* Database page size in bytes. 1==64K */
44581   u32 mxFrame;                    /* Index of last valid frame in the WAL */
44582   u32 nPage;                      /* Size of database in pages */
44583   u32 aFrameCksum[2];             /* Checksum of last frame in log */
44584   u32 aSalt[2];                   /* Two salt values copied from WAL header */
44585   u32 aCksum[2];                  /* Checksum over all prior fields */
44586 };
44587
44588 /*
44589 ** A copy of the following object occurs in the wal-index immediately
44590 ** following the second copy of the WalIndexHdr.  This object stores
44591 ** information used by checkpoint.
44592 **
44593 ** nBackfill is the number of frames in the WAL that have been written
44594 ** back into the database. (We call the act of moving content from WAL to
44595 ** database "backfilling".)  The nBackfill number is never greater than
44596 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
44597 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44598 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44599 ** mxFrame back to zero when the WAL is reset.
44600 **
44601 ** There is one entry in aReadMark[] for each reader lock.  If a reader
44602 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44603 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
44604 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
44605 ** a special case; its value is never used and it exists as a place-holder
44606 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
44607 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44608 ** directly from the database.
44609 **
44610 ** The value of aReadMark[K] may only be changed by a thread that
44611 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
44612 ** aReadMark[K] cannot changed while there is a reader is using that mark
44613 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44614 **
44615 ** The checkpointer may only transfer frames from WAL to database where
44616 ** the frame numbers are less than or equal to every aReadMark[] that is
44617 ** in use (that is, every aReadMark[j] for which there is a corresponding
44618 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
44619 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44620 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
44621 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44622 ** in the WAL has been backfilled into the database) then new readers
44623 ** will choose aReadMark[0] which has value 0 and hence such reader will
44624 ** get all their all content directly from the database file and ignore 
44625 ** the WAL.
44626 **
44627 ** Writers normally append new frames to the end of the WAL.  However,
44628 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44629 ** written back into the database) and if no readers are using the WAL
44630 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44631 ** the writer will first "reset" the WAL back to the beginning and start
44632 ** writing new content beginning at frame 1.
44633 **
44634 ** We assume that 32-bit loads are atomic and so no locks are needed in
44635 ** order to read from any aReadMark[] entries.
44636 */
44637 struct WalCkptInfo {
44638   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
44639   u32 aReadMark[WAL_NREADER];     /* Reader marks */
44640 };
44641 #define READMARK_NOT_USED  0xffffffff
44642
44643
44644 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44645 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44646 ** only support mandatory file-locks, we do not read or write data
44647 ** from the region of the file on which locks are applied.
44648 */
44649 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44650 #define WALINDEX_LOCK_RESERVED 16
44651 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44652
44653 /* Size of header before each frame in wal */
44654 #define WAL_FRAME_HDRSIZE 24
44655
44656 /* Size of write ahead log header, including checksum. */
44657 /* #define WAL_HDRSIZE 24 */
44658 #define WAL_HDRSIZE 32
44659
44660 /* WAL magic value. Either this value, or the same value with the least
44661 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44662 ** big-endian format in the first 4 bytes of a WAL file.
44663 **
44664 ** If the LSB is set, then the checksums for each frame within the WAL
44665 ** file are calculated by treating all data as an array of 32-bit 
44666 ** big-endian words. Otherwise, they are calculated by interpreting 
44667 ** all data as 32-bit little-endian words.
44668 */
44669 #define WAL_MAGIC 0x377f0682
44670
44671 /*
44672 ** Return the offset of frame iFrame in the write-ahead log file, 
44673 ** assuming a database page size of szPage bytes. The offset returned
44674 ** is to the start of the write-ahead log frame-header.
44675 */
44676 #define walFrameOffset(iFrame, szPage) (                               \
44677   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44678 )
44679
44680 /*
44681 ** An open write-ahead log file is represented by an instance of the
44682 ** following object.
44683 */
44684 struct Wal {
44685   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44686   sqlite3_file *pDbFd;       /* File handle for the database file */
44687   sqlite3_file *pWalFd;      /* File handle for WAL file */
44688   u32 iCallback;             /* Value to pass to log callback (or 0) */
44689   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44690   int nWiData;               /* Size of array apWiData */
44691   int szFirstBlock;          /* Size of first block written to WAL file */
44692   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44693   u32 szPage;                /* Database page size */
44694   i16 readLock;              /* Which read lock is being held.  -1 for none */
44695   u8 syncFlags;              /* Flags to use to sync header writes */
44696   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44697   u8 writeLock;              /* True if in a write transaction */
44698   u8 ckptLock;               /* True if holding a checkpoint lock */
44699   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44700   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
44701   u8 syncHeader;             /* Fsync the WAL header if true */
44702   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
44703   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44704   const char *zWalName;      /* Name of WAL file */
44705   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44706 #ifdef SQLITE_DEBUG
44707   u8 lockError;              /* True if a locking error has occurred */
44708 #endif
44709 };
44710
44711 /*
44712 ** Candidate values for Wal.exclusiveMode.
44713 */
44714 #define WAL_NORMAL_MODE     0
44715 #define WAL_EXCLUSIVE_MODE  1     
44716 #define WAL_HEAPMEMORY_MODE 2
44717
44718 /*
44719 ** Possible values for WAL.readOnly
44720 */
44721 #define WAL_RDWR        0    /* Normal read/write connection */
44722 #define WAL_RDONLY      1    /* The WAL file is readonly */
44723 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44724
44725 /*
44726 ** Each page of the wal-index mapping contains a hash-table made up of
44727 ** an array of HASHTABLE_NSLOT elements of the following type.
44728 */
44729 typedef u16 ht_slot;
44730
44731 /*
44732 ** This structure is used to implement an iterator that loops through
44733 ** all frames in the WAL in database page order. Where two or more frames
44734 ** correspond to the same database page, the iterator visits only the 
44735 ** frame most recently written to the WAL (in other words, the frame with
44736 ** the largest index).
44737 **
44738 ** The internals of this structure are only accessed by:
44739 **
44740 **   walIteratorInit() - Create a new iterator,
44741 **   walIteratorNext() - Step an iterator,
44742 **   walIteratorFree() - Free an iterator.
44743 **
44744 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44745 */
44746 struct WalIterator {
44747   int iPrior;                     /* Last result returned from the iterator */
44748   int nSegment;                   /* Number of entries in aSegment[] */
44749   struct WalSegment {
44750     int iNext;                    /* Next slot in aIndex[] not yet returned */
44751     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44752     u32 *aPgno;                   /* Array of page numbers. */
44753     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44754     int iZero;                    /* Frame number associated with aPgno[0] */
44755   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44756 };
44757
44758 /*
44759 ** Define the parameters of the hash tables in the wal-index file. There
44760 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44761 ** wal-index.
44762 **
44763 ** Changing any of these constants will alter the wal-index format and
44764 ** create incompatibilities.
44765 */
44766 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44767 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44768 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44769
44770 /* 
44771 ** The block of page numbers associated with the first hash-table in a
44772 ** wal-index is smaller than usual. This is so that there is a complete
44773 ** hash-table on each aligned 32KB page of the wal-index.
44774 */
44775 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44776
44777 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44778 #define WALINDEX_PGSZ   (                                         \
44779     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44780 )
44781
44782 /*
44783 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44784 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44785 ** numbered from zero.
44786 **
44787 ** If this call is successful, *ppPage is set to point to the wal-index
44788 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44789 ** then an SQLite error code is returned and *ppPage is set to 0.
44790 */
44791 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44792   int rc = SQLITE_OK;
44793
44794   /* Enlarge the pWal->apWiData[] array if required */
44795   if( pWal->nWiData<=iPage ){
44796     int nByte = sizeof(u32*)*(iPage+1);
44797     volatile u32 **apNew;
44798     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44799     if( !apNew ){
44800       *ppPage = 0;
44801       return SQLITE_NOMEM;
44802     }
44803     memset((void*)&apNew[pWal->nWiData], 0,
44804            sizeof(u32*)*(iPage+1-pWal->nWiData));
44805     pWal->apWiData = apNew;
44806     pWal->nWiData = iPage+1;
44807   }
44808
44809   /* Request a pointer to the required page from the VFS */
44810   if( pWal->apWiData[iPage]==0 ){
44811     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44812       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44813       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44814     }else{
44815       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
44816           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44817       );
44818       if( rc==SQLITE_READONLY ){
44819         pWal->readOnly |= WAL_SHM_RDONLY;
44820         rc = SQLITE_OK;
44821       }
44822     }
44823   }
44824
44825   *ppPage = pWal->apWiData[iPage];
44826   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44827   return rc;
44828 }
44829
44830 /*
44831 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44832 */
44833 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44834   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44835   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44836 }
44837
44838 /*
44839 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44840 */
44841 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44842   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44843   return (volatile WalIndexHdr*)pWal->apWiData[0];
44844 }
44845
44846 /*
44847 ** The argument to this macro must be of type u32. On a little-endian
44848 ** architecture, it returns the u32 value that results from interpreting
44849 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44850 ** returns the value that would be produced by intepreting the 4 bytes
44851 ** of the input value as a little-endian integer.
44852 */
44853 #define BYTESWAP32(x) ( \
44854     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44855   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44856 )
44857
44858 /*
44859 ** Generate or extend an 8 byte checksum based on the data in 
44860 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44861 ** initial values of 0 and 0 if aIn==NULL).
44862 **
44863 ** The checksum is written back into aOut[] before returning.
44864 **
44865 ** nByte must be a positive multiple of 8.
44866 */
44867 static void walChecksumBytes(
44868   int nativeCksum, /* True for native byte-order, false for non-native */
44869   u8 *a,           /* Content to be checksummed */
44870   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44871   const u32 *aIn,  /* Initial checksum value input */
44872   u32 *aOut        /* OUT: Final checksum value output */
44873 ){
44874   u32 s1, s2;
44875   u32 *aData = (u32 *)a;
44876   u32 *aEnd = (u32 *)&a[nByte];
44877
44878   if( aIn ){
44879     s1 = aIn[0];
44880     s2 = aIn[1];
44881   }else{
44882     s1 = s2 = 0;
44883   }
44884
44885   assert( nByte>=8 );
44886   assert( (nByte&0x00000007)==0 );
44887
44888   if( nativeCksum ){
44889     do {
44890       s1 += *aData++ + s2;
44891       s2 += *aData++ + s1;
44892     }while( aData<aEnd );
44893   }else{
44894     do {
44895       s1 += BYTESWAP32(aData[0]) + s2;
44896       s2 += BYTESWAP32(aData[1]) + s1;
44897       aData += 2;
44898     }while( aData<aEnd );
44899   }
44900
44901   aOut[0] = s1;
44902   aOut[1] = s2;
44903 }
44904
44905 static void walShmBarrier(Wal *pWal){
44906   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44907     sqlite3OsShmBarrier(pWal->pDbFd);
44908   }
44909 }
44910
44911 /*
44912 ** Write the header information in pWal->hdr into the wal-index.
44913 **
44914 ** The checksum on pWal->hdr is updated before it is written.
44915 */
44916 static void walIndexWriteHdr(Wal *pWal){
44917   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44918   const int nCksum = offsetof(WalIndexHdr, aCksum);
44919
44920   assert( pWal->writeLock );
44921   pWal->hdr.isInit = 1;
44922   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44923   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44924   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44925   walShmBarrier(pWal);
44926   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44927 }
44928
44929 /*
44930 ** This function encodes a single frame header and writes it to a buffer
44931 ** supplied by the caller. A frame-header is made up of a series of 
44932 ** 4-byte big-endian integers, as follows:
44933 **
44934 **     0: Page number.
44935 **     4: For commit records, the size of the database image in pages 
44936 **        after the commit. For all other records, zero.
44937 **     8: Salt-1 (copied from the wal-header)
44938 **    12: Salt-2 (copied from the wal-header)
44939 **    16: Checksum-1.
44940 **    20: Checksum-2.
44941 */
44942 static void walEncodeFrame(
44943   Wal *pWal,                      /* The write-ahead log */
44944   u32 iPage,                      /* Database page number for frame */
44945   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
44946   u8 *aData,                      /* Pointer to page data */
44947   u8 *aFrame                      /* OUT: Write encoded frame here */
44948 ){
44949   int nativeCksum;                /* True for native byte-order checksums */
44950   u32 *aCksum = pWal->hdr.aFrameCksum;
44951   assert( WAL_FRAME_HDRSIZE==24 );
44952   sqlite3Put4byte(&aFrame[0], iPage);
44953   sqlite3Put4byte(&aFrame[4], nTruncate);
44954   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44955
44956   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44957   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44958   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44959
44960   sqlite3Put4byte(&aFrame[16], aCksum[0]);
44961   sqlite3Put4byte(&aFrame[20], aCksum[1]);
44962 }
44963
44964 /*
44965 ** Check to see if the frame with header in aFrame[] and content
44966 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
44967 ** *pnTruncate and return true.  Return if the frame is not valid.
44968 */
44969 static int walDecodeFrame(
44970   Wal *pWal,                      /* The write-ahead log */
44971   u32 *piPage,                    /* OUT: Database page number for frame */
44972   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
44973   u8 *aData,                      /* Pointer to page data (for checksum) */
44974   u8 *aFrame                      /* Frame data */
44975 ){
44976   int nativeCksum;                /* True for native byte-order checksums */
44977   u32 *aCksum = pWal->hdr.aFrameCksum;
44978   u32 pgno;                       /* Page number of the frame */
44979   assert( WAL_FRAME_HDRSIZE==24 );
44980
44981   /* A frame is only valid if the salt values in the frame-header
44982   ** match the salt values in the wal-header. 
44983   */
44984   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44985     return 0;
44986   }
44987
44988   /* A frame is only valid if the page number is creater than zero.
44989   */
44990   pgno = sqlite3Get4byte(&aFrame[0]);
44991   if( pgno==0 ){
44992     return 0;
44993   }
44994
44995   /* A frame is only valid if a checksum of the WAL header,
44996   ** all prior frams, the first 16 bytes of this frame-header, 
44997   ** and the frame-data matches the checksum in the last 8 
44998   ** bytes of this frame-header.
44999   */
45000   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45001   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45002   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45003   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
45004    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
45005   ){
45006     /* Checksum failed. */
45007     return 0;
45008   }
45009
45010   /* If we reach this point, the frame is valid.  Return the page number
45011   ** and the new database size.
45012   */
45013   *piPage = pgno;
45014   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
45015   return 1;
45016 }
45017
45018
45019 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45020 /*
45021 ** Names of locks.  This routine is used to provide debugging output and is not
45022 ** a part of an ordinary build.
45023 */
45024 static const char *walLockName(int lockIdx){
45025   if( lockIdx==WAL_WRITE_LOCK ){
45026     return "WRITE-LOCK";
45027   }else if( lockIdx==WAL_CKPT_LOCK ){
45028     return "CKPT-LOCK";
45029   }else if( lockIdx==WAL_RECOVER_LOCK ){
45030     return "RECOVER-LOCK";
45031   }else{
45032     static char zName[15];
45033     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
45034                      lockIdx-WAL_READ_LOCK(0));
45035     return zName;
45036   }
45037 }
45038 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
45039     
45040
45041 /*
45042 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
45043 ** A lock cannot be moved directly between shared and exclusive - it must go
45044 ** through the unlocked state first.
45045 **
45046 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
45047 */
45048 static int walLockShared(Wal *pWal, int lockIdx){
45049   int rc;
45050   if( pWal->exclusiveMode ) return SQLITE_OK;
45051   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45052                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
45053   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
45054             walLockName(lockIdx), rc ? "failed" : "ok"));
45055   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45056   return rc;
45057 }
45058 static void walUnlockShared(Wal *pWal, int lockIdx){
45059   if( pWal->exclusiveMode ) return;
45060   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45061                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
45062   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
45063 }
45064 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
45065   int rc;
45066   if( pWal->exclusiveMode ) return SQLITE_OK;
45067   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45068                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
45069   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
45070             walLockName(lockIdx), n, rc ? "failed" : "ok"));
45071   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45072   return rc;
45073 }
45074 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
45075   if( pWal->exclusiveMode ) return;
45076   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45077                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
45078   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
45079              walLockName(lockIdx), n));
45080 }
45081
45082 /*
45083 ** Compute a hash on a page number.  The resulting hash value must land
45084 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
45085 ** the hash to the next value in the event of a collision.
45086 */
45087 static int walHash(u32 iPage){
45088   assert( iPage>0 );
45089   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
45090   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
45091 }
45092 static int walNextHash(int iPriorHash){
45093   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
45094 }
45095
45096 /* 
45097 ** Return pointers to the hash table and page number array stored on
45098 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
45099 ** numbered starting from 0.
45100 **
45101 ** Set output variable *paHash to point to the start of the hash table
45102 ** in the wal-index file. Set *piZero to one less than the frame 
45103 ** number of the first frame indexed by this hash table. If a
45104 ** slot in the hash table is set to N, it refers to frame number 
45105 ** (*piZero+N) in the log.
45106 **
45107 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
45108 ** first frame indexed by the hash table, frame (*piZero+1).
45109 */
45110 static int walHashGet(
45111   Wal *pWal,                      /* WAL handle */
45112   int iHash,                      /* Find the iHash'th table */
45113   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
45114   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
45115   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
45116 ){
45117   int rc;                         /* Return code */
45118   volatile u32 *aPgno;
45119
45120   rc = walIndexPage(pWal, iHash, &aPgno);
45121   assert( rc==SQLITE_OK || iHash>0 );
45122
45123   if( rc==SQLITE_OK ){
45124     u32 iZero;
45125     volatile ht_slot *aHash;
45126
45127     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
45128     if( iHash==0 ){
45129       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
45130       iZero = 0;
45131     }else{
45132       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
45133     }
45134   
45135     *paPgno = &aPgno[-1];
45136     *paHash = aHash;
45137     *piZero = iZero;
45138   }
45139   return rc;
45140 }
45141
45142 /*
45143 ** Return the number of the wal-index page that contains the hash-table
45144 ** and page-number array that contain entries corresponding to WAL frame
45145 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
45146 ** are numbered starting from 0.
45147 */
45148 static int walFramePage(u32 iFrame){
45149   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
45150   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
45151        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
45152        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
45153        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
45154        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
45155   );
45156   return iHash;
45157 }
45158
45159 /*
45160 ** Return the page number associated with frame iFrame in this WAL.
45161 */
45162 static u32 walFramePgno(Wal *pWal, u32 iFrame){
45163   int iHash = walFramePage(iFrame);
45164   if( iHash==0 ){
45165     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
45166   }
45167   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
45168 }
45169
45170 /*
45171 ** Remove entries from the hash table that point to WAL slots greater
45172 ** than pWal->hdr.mxFrame.
45173 **
45174 ** This function is called whenever pWal->hdr.mxFrame is decreased due
45175 ** to a rollback or savepoint.
45176 **
45177 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
45178 ** updated.  Any later hash tables will be automatically cleared when
45179 ** pWal->hdr.mxFrame advances to the point where those hash tables are
45180 ** actually needed.
45181 */
45182 static void walCleanupHash(Wal *pWal){
45183   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
45184   volatile u32 *aPgno = 0;        /* Page number array for hash table */
45185   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
45186   int iLimit = 0;                 /* Zero values greater than this */
45187   int nByte;                      /* Number of bytes to zero in aPgno[] */
45188   int i;                          /* Used to iterate through aHash[] */
45189
45190   assert( pWal->writeLock );
45191   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
45192   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
45193   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
45194
45195   if( pWal->hdr.mxFrame==0 ) return;
45196
45197   /* Obtain pointers to the hash-table and page-number array containing 
45198   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
45199   ** that the page said hash-table and array reside on is already mapped.
45200   */
45201   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
45202   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
45203   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
45204
45205   /* Zero all hash-table entries that correspond to frame numbers greater
45206   ** than pWal->hdr.mxFrame.
45207   */
45208   iLimit = pWal->hdr.mxFrame - iZero;
45209   assert( iLimit>0 );
45210   for(i=0; i<HASHTABLE_NSLOT; i++){
45211     if( aHash[i]>iLimit ){
45212       aHash[i] = 0;
45213     }
45214   }
45215   
45216   /* Zero the entries in the aPgno array that correspond to frames with
45217   ** frame numbers greater than pWal->hdr.mxFrame. 
45218   */
45219   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
45220   memset((void *)&aPgno[iLimit+1], 0, nByte);
45221
45222 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45223   /* Verify that the every entry in the mapping region is still reachable
45224   ** via the hash table even after the cleanup.
45225   */
45226   if( iLimit ){
45227     int i;           /* Loop counter */
45228     int iKey;        /* Hash key */
45229     for(i=1; i<=iLimit; i++){
45230       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45231         if( aHash[iKey]==i ) break;
45232       }
45233       assert( aHash[iKey]==i );
45234     }
45235   }
45236 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45237 }
45238
45239
45240 /*
45241 ** Set an entry in the wal-index that will map database page number
45242 ** pPage into WAL frame iFrame.
45243 */
45244 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
45245   int rc;                         /* Return code */
45246   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
45247   volatile u32 *aPgno = 0;        /* Page number array */
45248   volatile ht_slot *aHash = 0;    /* Hash table */
45249
45250   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
45251
45252   /* Assuming the wal-index file was successfully mapped, populate the
45253   ** page number array and hash table entry.
45254   */
45255   if( rc==SQLITE_OK ){
45256     int iKey;                     /* Hash table key */
45257     int idx;                      /* Value to write to hash-table slot */
45258     int nCollide;                 /* Number of hash collisions */
45259
45260     idx = iFrame - iZero;
45261     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
45262     
45263     /* If this is the first entry to be added to this hash-table, zero the
45264     ** entire hash table and aPgno[] array before proceding. 
45265     */
45266     if( idx==1 ){
45267       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
45268       memset((void*)&aPgno[1], 0, nByte);
45269     }
45270
45271     /* If the entry in aPgno[] is already set, then the previous writer
45272     ** must have exited unexpectedly in the middle of a transaction (after
45273     ** writing one or more dirty pages to the WAL to free up memory). 
45274     ** Remove the remnants of that writers uncommitted transaction from 
45275     ** the hash-table before writing any new entries.
45276     */
45277     if( aPgno[idx] ){
45278       walCleanupHash(pWal);
45279       assert( !aPgno[idx] );
45280     }
45281
45282     /* Write the aPgno[] array entry and the hash-table slot. */
45283     nCollide = idx;
45284     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
45285       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
45286     }
45287     aPgno[idx] = iPage;
45288     aHash[iKey] = (ht_slot)idx;
45289
45290 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45291     /* Verify that the number of entries in the hash table exactly equals
45292     ** the number of entries in the mapping region.
45293     */
45294     {
45295       int i;           /* Loop counter */
45296       int nEntry = 0;  /* Number of entries in the hash table */
45297       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
45298       assert( nEntry==idx );
45299     }
45300
45301     /* Verify that the every entry in the mapping region is reachable
45302     ** via the hash table.  This turns out to be a really, really expensive
45303     ** thing to check, so only do this occasionally - not on every
45304     ** iteration.
45305     */
45306     if( (idx&0x3ff)==0 ){
45307       int i;           /* Loop counter */
45308       for(i=1; i<=idx; i++){
45309         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45310           if( aHash[iKey]==i ) break;
45311         }
45312         assert( aHash[iKey]==i );
45313       }
45314     }
45315 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45316   }
45317
45318
45319   return rc;
45320 }
45321
45322
45323 /*
45324 ** Recover the wal-index by reading the write-ahead log file. 
45325 **
45326 ** This routine first tries to establish an exclusive lock on the
45327 ** wal-index to prevent other threads/processes from doing anything
45328 ** with the WAL or wal-index while recovery is running.  The
45329 ** WAL_RECOVER_LOCK is also held so that other threads will know
45330 ** that this thread is running recovery.  If unable to establish
45331 ** the necessary locks, this routine returns SQLITE_BUSY.
45332 */
45333 static int walIndexRecover(Wal *pWal){
45334   int rc;                         /* Return Code */
45335   i64 nSize;                      /* Size of log file */
45336   u32 aFrameCksum[2] = {0, 0};
45337   int iLock;                      /* Lock offset to lock for checkpoint */
45338   int nLock;                      /* Number of locks to hold */
45339
45340   /* Obtain an exclusive lock on all byte in the locking range not already
45341   ** locked by the caller. The caller is guaranteed to have locked the
45342   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
45343   ** If successful, the same bytes that are locked here are unlocked before
45344   ** this function returns.
45345   */
45346   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
45347   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
45348   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
45349   assert( pWal->writeLock );
45350   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
45351   nLock = SQLITE_SHM_NLOCK - iLock;
45352   rc = walLockExclusive(pWal, iLock, nLock);
45353   if( rc ){
45354     return rc;
45355   }
45356   WALTRACE(("WAL%p: recovery begin...\n", pWal));
45357
45358   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45359
45360   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
45361   if( rc!=SQLITE_OK ){
45362     goto recovery_error;
45363   }
45364
45365   if( nSize>WAL_HDRSIZE ){
45366     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
45367     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
45368     int szFrame;                  /* Number of bytes in buffer aFrame[] */
45369     u8 *aData;                    /* Pointer to data part of aFrame buffer */
45370     int iFrame;                   /* Index of last frame read */
45371     i64 iOffset;                  /* Next offset to read from log file */
45372     int szPage;                   /* Page size according to the log */
45373     u32 magic;                    /* Magic value read from WAL header */
45374     u32 version;                  /* Magic value read from WAL header */
45375     int isValid;                  /* True if this frame is valid */
45376
45377     /* Read in the WAL header. */
45378     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
45379     if( rc!=SQLITE_OK ){
45380       goto recovery_error;
45381     }
45382
45383     /* If the database page size is not a power of two, or is greater than
45384     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
45385     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
45386     ** WAL file.
45387     */
45388     magic = sqlite3Get4byte(&aBuf[0]);
45389     szPage = sqlite3Get4byte(&aBuf[8]);
45390     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
45391      || szPage&(szPage-1) 
45392      || szPage>SQLITE_MAX_PAGE_SIZE 
45393      || szPage<512 
45394     ){
45395       goto finished;
45396     }
45397     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45398     pWal->szPage = szPage;
45399     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45400     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45401
45402     /* Verify that the WAL header checksum is correct */
45403     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
45404         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45405     );
45406     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45407      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45408     ){
45409       goto finished;
45410     }
45411
45412     /* Verify that the version number on the WAL format is one that
45413     ** are able to understand */
45414     version = sqlite3Get4byte(&aBuf[4]);
45415     if( version!=WAL_MAX_VERSION ){
45416       rc = SQLITE_CANTOPEN_BKPT;
45417       goto finished;
45418     }
45419
45420     /* Malloc a buffer to read frames into. */
45421     szFrame = szPage + WAL_FRAME_HDRSIZE;
45422     aFrame = (u8 *)sqlite3_malloc(szFrame);
45423     if( !aFrame ){
45424       rc = SQLITE_NOMEM;
45425       goto recovery_error;
45426     }
45427     aData = &aFrame[WAL_FRAME_HDRSIZE];
45428
45429     /* Read all frames from the log file. */
45430     iFrame = 0;
45431     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45432       u32 pgno;                   /* Database page number for frame */
45433       u32 nTruncate;              /* dbsize field from frame header */
45434
45435       /* Read and decode the next log frame. */
45436       iFrame++;
45437       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45438       if( rc!=SQLITE_OK ) break;
45439       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45440       if( !isValid ) break;
45441       rc = walIndexAppend(pWal, iFrame, pgno);
45442       if( rc!=SQLITE_OK ) break;
45443
45444       /* If nTruncate is non-zero, this is a commit record. */
45445       if( nTruncate ){
45446         pWal->hdr.mxFrame = iFrame;
45447         pWal->hdr.nPage = nTruncate;
45448         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45449         testcase( szPage<=32768 );
45450         testcase( szPage>=65536 );
45451         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45452         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45453       }
45454     }
45455
45456     sqlite3_free(aFrame);
45457   }
45458
45459 finished:
45460   if( rc==SQLITE_OK ){
45461     volatile WalCkptInfo *pInfo;
45462     int i;
45463     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45464     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45465     walIndexWriteHdr(pWal);
45466
45467     /* Reset the checkpoint-header. This is safe because this thread is 
45468     ** currently holding locks that exclude all other readers, writers and
45469     ** checkpointers.
45470     */
45471     pInfo = walCkptInfo(pWal);
45472     pInfo->nBackfill = 0;
45473     pInfo->aReadMark[0] = 0;
45474     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45475     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
45476
45477     /* If more than one frame was recovered from the log file, report an
45478     ** event via sqlite3_log(). This is to help with identifying performance
45479     ** problems caused by applications routinely shutting down without
45480     ** checkpointing the log file.
45481     */
45482     if( pWal->hdr.nPage ){
45483       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45484           pWal->hdr.nPage, pWal->zWalName
45485       );
45486     }
45487   }
45488
45489 recovery_error:
45490   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45491   walUnlockExclusive(pWal, iLock, nLock);
45492   return rc;
45493 }
45494
45495 /*
45496 ** Close an open wal-index.
45497 */
45498 static void walIndexClose(Wal *pWal, int isDelete){
45499   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45500     int i;
45501     for(i=0; i<pWal->nWiData; i++){
45502       sqlite3_free((void *)pWal->apWiData[i]);
45503       pWal->apWiData[i] = 0;
45504     }
45505   }else{
45506     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45507   }
45508 }
45509
45510 /* 
45511 ** Open a connection to the WAL file zWalName. The database file must 
45512 ** already be opened on connection pDbFd. The buffer that zWalName points
45513 ** to must remain valid for the lifetime of the returned Wal* handle.
45514 **
45515 ** A SHARED lock should be held on the database file when this function
45516 ** is called. The purpose of this SHARED lock is to prevent any other
45517 ** client from unlinking the WAL or wal-index file. If another process
45518 ** were to do this just after this client opened one of these files, the
45519 ** system would be badly broken.
45520 **
45521 ** If the log file is successfully opened, SQLITE_OK is returned and 
45522 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45523 ** an SQLite error code is returned and *ppWal is left unmodified.
45524 */
45525 SQLITE_PRIVATE int sqlite3WalOpen(
45526   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
45527   sqlite3_file *pDbFd,            /* The open database file */
45528   const char *zWalName,           /* Name of the WAL file */
45529   int bNoShm,                     /* True to run in heap-memory mode */
45530   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
45531   Wal **ppWal                     /* OUT: Allocated Wal handle */
45532 ){
45533   int rc;                         /* Return Code */
45534   Wal *pRet;                      /* Object to allocate and return */
45535   int flags;                      /* Flags passed to OsOpen() */
45536
45537   assert( zWalName && zWalName[0] );
45538   assert( pDbFd );
45539
45540   /* In the amalgamation, the os_unix.c and os_win.c source files come before
45541   ** this source file.  Verify that the #defines of the locking byte offsets
45542   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45543   */
45544 #ifdef WIN_SHM_BASE
45545   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45546 #endif
45547 #ifdef UNIX_SHM_BASE
45548   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45549 #endif
45550
45551
45552   /* Allocate an instance of struct Wal to return. */
45553   *ppWal = 0;
45554   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45555   if( !pRet ){
45556     return SQLITE_NOMEM;
45557   }
45558
45559   pRet->pVfs = pVfs;
45560   pRet->pWalFd = (sqlite3_file *)&pRet[1];
45561   pRet->pDbFd = pDbFd;
45562   pRet->readLock = -1;
45563   pRet->mxWalSize = mxWalSize;
45564   pRet->zWalName = zWalName;
45565   pRet->syncHeader = 1;
45566   pRet->padToSectorBoundary = 1;
45567   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45568
45569   /* Open file handle on the write-ahead log file. */
45570   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45571   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45572   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45573     pRet->readOnly = WAL_RDONLY;
45574   }
45575
45576   if( rc!=SQLITE_OK ){
45577     walIndexClose(pRet, 0);
45578     sqlite3OsClose(pRet->pWalFd);
45579     sqlite3_free(pRet);
45580   }else{
45581     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
45582     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
45583     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
45584       pRet->padToSectorBoundary = 0;
45585     }
45586     *ppWal = pRet;
45587     WALTRACE(("WAL%d: opened\n", pRet));
45588   }
45589   return rc;
45590 }
45591
45592 /*
45593 ** Change the size to which the WAL file is trucated on each reset.
45594 */
45595 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45596   if( pWal ) pWal->mxWalSize = iLimit;
45597 }
45598
45599 /*
45600 ** Find the smallest page number out of all pages held in the WAL that
45601 ** has not been returned by any prior invocation of this method on the
45602 ** same WalIterator object.   Write into *piFrame the frame index where
45603 ** that page was last written into the WAL.  Write into *piPage the page
45604 ** number.
45605 **
45606 ** Return 0 on success.  If there are no pages in the WAL with a page
45607 ** number larger than *piPage, then return 1.
45608 */
45609 static int walIteratorNext(
45610   WalIterator *p,               /* Iterator */
45611   u32 *piPage,                  /* OUT: The page number of the next page */
45612   u32 *piFrame                  /* OUT: Wal frame index of next page */
45613 ){
45614   u32 iMin;                     /* Result pgno must be greater than iMin */
45615   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
45616   int i;                        /* For looping through segments */
45617
45618   iMin = p->iPrior;
45619   assert( iMin<0xffffffff );
45620   for(i=p->nSegment-1; i>=0; i--){
45621     struct WalSegment *pSegment = &p->aSegment[i];
45622     while( pSegment->iNext<pSegment->nEntry ){
45623       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45624       if( iPg>iMin ){
45625         if( iPg<iRet ){
45626           iRet = iPg;
45627           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45628         }
45629         break;
45630       }
45631       pSegment->iNext++;
45632     }
45633   }
45634
45635   *piPage = p->iPrior = iRet;
45636   return (iRet==0xFFFFFFFF);
45637 }
45638
45639 /*
45640 ** This function merges two sorted lists into a single sorted list.
45641 **
45642 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
45643 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
45644 ** is guaranteed for all J<K:
45645 **
45646 **        aContent[aLeft[J]] < aContent[aLeft[K]]
45647 **        aContent[aRight[J]] < aContent[aRight[K]]
45648 **
45649 ** This routine overwrites aRight[] with a new (probably longer) sequence
45650 ** of indices such that the aRight[] contains every index that appears in
45651 ** either aLeft[] or the old aRight[] and such that the second condition
45652 ** above is still met.
45653 **
45654 ** The aContent[aLeft[X]] values will be unique for all X.  And the
45655 ** aContent[aRight[X]] values will be unique too.  But there might be
45656 ** one or more combinations of X and Y such that
45657 **
45658 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
45659 **
45660 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45661 */
45662 static void walMerge(
45663   const u32 *aContent,            /* Pages in wal - keys for the sort */
45664   ht_slot *aLeft,                 /* IN: Left hand input list */
45665   int nLeft,                      /* IN: Elements in array *paLeft */
45666   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45667   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45668   ht_slot *aTmp                   /* Temporary buffer */
45669 ){
45670   int iLeft = 0;                  /* Current index in aLeft */
45671   int iRight = 0;                 /* Current index in aRight */
45672   int iOut = 0;                   /* Current index in output buffer */
45673   int nRight = *pnRight;
45674   ht_slot *aRight = *paRight;
45675
45676   assert( nLeft>0 && nRight>0 );
45677   while( iRight<nRight || iLeft<nLeft ){
45678     ht_slot logpage;
45679     Pgno dbpage;
45680
45681     if( (iLeft<nLeft) 
45682      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45683     ){
45684       logpage = aLeft[iLeft++];
45685     }else{
45686       logpage = aRight[iRight++];
45687     }
45688     dbpage = aContent[logpage];
45689
45690     aTmp[iOut++] = logpage;
45691     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45692
45693     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45694     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45695   }
45696
45697   *paRight = aLeft;
45698   *pnRight = iOut;
45699   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45700 }
45701
45702 /*
45703 ** Sort the elements in list aList using aContent[] as the sort key.
45704 ** Remove elements with duplicate keys, preferring to keep the
45705 ** larger aList[] values.
45706 **
45707 ** The aList[] entries are indices into aContent[].  The values in
45708 ** aList[] are to be sorted so that for all J<K:
45709 **
45710 **      aContent[aList[J]] < aContent[aList[K]]
45711 **
45712 ** For any X and Y such that
45713 **
45714 **      aContent[aList[X]] == aContent[aList[Y]]
45715 **
45716 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45717 ** the smaller.
45718 */
45719 static void walMergesort(
45720   const u32 *aContent,            /* Pages in wal */
45721   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45722   ht_slot *aList,                 /* IN/OUT: List to sort */
45723   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45724 ){
45725   struct Sublist {
45726     int nList;                    /* Number of elements in aList */
45727     ht_slot *aList;               /* Pointer to sub-list content */
45728   };
45729
45730   const int nList = *pnList;      /* Size of input list */
45731   int nMerge = 0;                 /* Number of elements in list aMerge */
45732   ht_slot *aMerge = 0;            /* List to be merged */
45733   int iList;                      /* Index into input list */
45734   int iSub = 0;                   /* Index into aSub array */
45735   struct Sublist aSub[13];        /* Array of sub-lists */
45736
45737   memset(aSub, 0, sizeof(aSub));
45738   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45739   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45740
45741   for(iList=0; iList<nList; iList++){
45742     nMerge = 1;
45743     aMerge = &aList[iList];
45744     for(iSub=0; iList & (1<<iSub); iSub++){
45745       struct Sublist *p = &aSub[iSub];
45746       assert( p->aList && p->nList<=(1<<iSub) );
45747       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45748       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45749     }
45750     aSub[iSub].aList = aMerge;
45751     aSub[iSub].nList = nMerge;
45752   }
45753
45754   for(iSub++; iSub<ArraySize(aSub); iSub++){
45755     if( nList & (1<<iSub) ){
45756       struct Sublist *p = &aSub[iSub];
45757       assert( p->nList<=(1<<iSub) );
45758       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45759       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45760     }
45761   }
45762   assert( aMerge==aList );
45763   *pnList = nMerge;
45764
45765 #ifdef SQLITE_DEBUG
45766   {
45767     int i;
45768     for(i=1; i<*pnList; i++){
45769       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45770     }
45771   }
45772 #endif
45773 }
45774
45775 /* 
45776 ** Free an iterator allocated by walIteratorInit().
45777 */
45778 static void walIteratorFree(WalIterator *p){
45779   sqlite3ScratchFree(p);
45780 }
45781
45782 /*
45783 ** Construct a WalInterator object that can be used to loop over all 
45784 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45785 ** lock.
45786 **
45787 ** On success, make *pp point to the newly allocated WalInterator object
45788 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45789 ** returns an error, the value of *pp is undefined.
45790 **
45791 ** The calling routine should invoke walIteratorFree() to destroy the
45792 ** WalIterator object when it has finished with it.
45793 */
45794 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45795   WalIterator *p;                 /* Return value */
45796   int nSegment;                   /* Number of segments to merge */
45797   u32 iLast;                      /* Last frame in log */
45798   int nByte;                      /* Number of bytes to allocate */
45799   int i;                          /* Iterator variable */
45800   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45801   int rc = SQLITE_OK;             /* Return Code */
45802
45803   /* This routine only runs while holding the checkpoint lock. And
45804   ** it only runs if there is actually content in the log (mxFrame>0).
45805   */
45806   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45807   iLast = pWal->hdr.mxFrame;
45808
45809   /* Allocate space for the WalIterator object. */
45810   nSegment = walFramePage(iLast) + 1;
45811   nByte = sizeof(WalIterator) 
45812         + (nSegment-1)*sizeof(struct WalSegment)
45813         + iLast*sizeof(ht_slot);
45814   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45815   if( !p ){
45816     return SQLITE_NOMEM;
45817   }
45818   memset(p, 0, nByte);
45819   p->nSegment = nSegment;
45820
45821   /* Allocate temporary space used by the merge-sort routine. This block
45822   ** of memory will be freed before this function returns.
45823   */
45824   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45825       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45826   );
45827   if( !aTmp ){
45828     rc = SQLITE_NOMEM;
45829   }
45830
45831   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45832     volatile ht_slot *aHash;
45833     u32 iZero;
45834     volatile u32 *aPgno;
45835
45836     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45837     if( rc==SQLITE_OK ){
45838       int j;                      /* Counter variable */
45839       int nEntry;                 /* Number of entries in this segment */
45840       ht_slot *aIndex;            /* Sorted index for this segment */
45841
45842       aPgno++;
45843       if( (i+1)==nSegment ){
45844         nEntry = (int)(iLast - iZero);
45845       }else{
45846         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45847       }
45848       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45849       iZero++;
45850   
45851       for(j=0; j<nEntry; j++){
45852         aIndex[j] = (ht_slot)j;
45853       }
45854       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45855       p->aSegment[i].iZero = iZero;
45856       p->aSegment[i].nEntry = nEntry;
45857       p->aSegment[i].aIndex = aIndex;
45858       p->aSegment[i].aPgno = (u32 *)aPgno;
45859     }
45860   }
45861   sqlite3ScratchFree(aTmp);
45862
45863   if( rc!=SQLITE_OK ){
45864     walIteratorFree(p);
45865   }
45866   *pp = p;
45867   return rc;
45868 }
45869
45870 /*
45871 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45872 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45873 ** busy-handler function. Invoke it and retry the lock until either the
45874 ** lock is successfully obtained or the busy-handler returns 0.
45875 */
45876 static int walBusyLock(
45877   Wal *pWal,                      /* WAL connection */
45878   int (*xBusy)(void*),            /* Function to call when busy */
45879   void *pBusyArg,                 /* Context argument for xBusyHandler */
45880   int lockIdx,                    /* Offset of first byte to lock */
45881   int n                           /* Number of bytes to lock */
45882 ){
45883   int rc;
45884   do {
45885     rc = walLockExclusive(pWal, lockIdx, n);
45886   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45887   return rc;
45888 }
45889
45890 /*
45891 ** The cache of the wal-index header must be valid to call this function.
45892 ** Return the page-size in bytes used by the database.
45893 */
45894 static int walPagesize(Wal *pWal){
45895   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45896 }
45897
45898 /*
45899 ** Copy as much content as we can from the WAL back into the database file
45900 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45901 **
45902 ** The amount of information copies from WAL to database might be limited
45903 ** by active readers.  This routine will never overwrite a database page
45904 ** that a concurrent reader might be using.
45905 **
45906 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45907 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
45908 ** checkpoints are always run by a background thread or background 
45909 ** process, foreground threads will never block on a lengthy fsync call.
45910 **
45911 ** Fsync is called on the WAL before writing content out of the WAL and
45912 ** into the database.  This ensures that if the new content is persistent
45913 ** in the WAL and can be recovered following a power-loss or hard reset.
45914 **
45915 ** Fsync is also called on the database file if (and only if) the entire
45916 ** WAL content is copied into the database file.  This second fsync makes
45917 ** it safe to delete the WAL since the new content will persist in the
45918 ** database file.
45919 **
45920 ** This routine uses and updates the nBackfill field of the wal-index header.
45921 ** This is the only routine tha will increase the value of nBackfill.  
45922 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45923 ** its value.)
45924 **
45925 ** The caller must be holding sufficient locks to ensure that no other
45926 ** checkpoint is running (in any other thread or process) at the same
45927 ** time.
45928 */
45929 static int walCheckpoint(
45930   Wal *pWal,                      /* Wal connection */
45931   int eMode,                      /* One of PASSIVE, FULL or RESTART */
45932   int (*xBusyCall)(void*),        /* Function to call when busy */
45933   void *pBusyArg,                 /* Context argument for xBusyHandler */
45934   int sync_flags,                 /* Flags for OsSync() (or 0) */
45935   u8 *zBuf                        /* Temporary buffer to use */
45936 ){
45937   int rc;                         /* Return code */
45938   int szPage;                     /* Database page-size */
45939   WalIterator *pIter = 0;         /* Wal iterator context */
45940   u32 iDbpage = 0;                /* Next database page to write */
45941   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
45942   u32 mxSafeFrame;                /* Max frame that can be backfilled */
45943   u32 mxPage;                     /* Max database page to write */
45944   int i;                          /* Loop counter */
45945   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
45946   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
45947
45948   szPage = walPagesize(pWal);
45949   testcase( szPage<=32768 );
45950   testcase( szPage>=65536 );
45951   pInfo = walCkptInfo(pWal);
45952   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45953
45954   /* Allocate the iterator */
45955   rc = walIteratorInit(pWal, &pIter);
45956   if( rc!=SQLITE_OK ){
45957     return rc;
45958   }
45959   assert( pIter );
45960
45961   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45962
45963   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45964   ** safe to write into the database.  Frames beyond mxSafeFrame might
45965   ** overwrite database pages that are in use by active readers and thus
45966   ** cannot be backfilled from the WAL.
45967   */
45968   mxSafeFrame = pWal->hdr.mxFrame;
45969   mxPage = pWal->hdr.nPage;
45970   for(i=1; i<WAL_NREADER; i++){
45971     u32 y = pInfo->aReadMark[i];
45972     if( mxSafeFrame>y ){
45973       assert( y<=pWal->hdr.mxFrame );
45974       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45975       if( rc==SQLITE_OK ){
45976         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
45977         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45978       }else if( rc==SQLITE_BUSY ){
45979         mxSafeFrame = y;
45980         xBusy = 0;
45981       }else{
45982         goto walcheckpoint_out;
45983       }
45984     }
45985   }
45986
45987   if( pInfo->nBackfill<mxSafeFrame
45988    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45989   ){
45990     i64 nSize;                    /* Current size of database file */
45991     u32 nBackfill = pInfo->nBackfill;
45992
45993     /* Sync the WAL to disk */
45994     if( sync_flags ){
45995       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45996     }
45997
45998     /* If the database file may grow as a result of this checkpoint, hint
45999     ** about the eventual size of the db file to the VFS layer. 
46000     */
46001     if( rc==SQLITE_OK ){
46002       i64 nReq = ((i64)mxPage * szPage);
46003       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
46004       if( rc==SQLITE_OK && nSize<nReq ){
46005         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
46006       }
46007     }
46008
46009     /* Iterate through the contents of the WAL, copying data to the db file. */
46010     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
46011       i64 iOffset;
46012       assert( walFramePgno(pWal, iFrame)==iDbpage );
46013       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
46014       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
46015       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
46016       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
46017       if( rc!=SQLITE_OK ) break;
46018       iOffset = (iDbpage-1)*(i64)szPage;
46019       testcase( IS_BIG_INT(iOffset) );
46020       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
46021       if( rc!=SQLITE_OK ) break;
46022     }
46023
46024     /* If work was actually accomplished... */
46025     if( rc==SQLITE_OK ){
46026       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
46027         i64 szDb = pWal->hdr.nPage*(i64)szPage;
46028         testcase( IS_BIG_INT(szDb) );
46029         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
46030         if( rc==SQLITE_OK && sync_flags ){
46031           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
46032         }
46033       }
46034       if( rc==SQLITE_OK ){
46035         pInfo->nBackfill = mxSafeFrame;
46036       }
46037     }
46038
46039     /* Release the reader lock held while backfilling */
46040     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
46041   }
46042
46043   if( rc==SQLITE_BUSY ){
46044     /* Reset the return code so as not to report a checkpoint failure
46045     ** just because there are active readers.  */
46046     rc = SQLITE_OK;
46047   }
46048
46049   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
46050   ** file has been copied into the database file, then block until all
46051   ** readers have finished using the wal file. This ensures that the next
46052   ** process to write to the database restarts the wal file.
46053   */
46054   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46055     assert( pWal->writeLock );
46056     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
46057       rc = SQLITE_BUSY;
46058     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
46059       assert( mxSafeFrame==pWal->hdr.mxFrame );
46060       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
46061       if( rc==SQLITE_OK ){
46062         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46063       }
46064     }
46065   }
46066
46067  walcheckpoint_out:
46068   walIteratorFree(pIter);
46069   return rc;
46070 }
46071
46072 /*
46073 ** If the WAL file is currently larger than nMax bytes in size, truncate
46074 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
46075 */
46076 static void walLimitSize(Wal *pWal, i64 nMax){
46077   i64 sz;
46078   int rx;
46079   sqlite3BeginBenignMalloc();
46080   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46081   if( rx==SQLITE_OK && (sz > nMax ) ){
46082     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
46083   }
46084   sqlite3EndBenignMalloc();
46085   if( rx ){
46086     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46087   }
46088 }
46089
46090 /*
46091 ** Close a connection to a log file.
46092 */
46093 SQLITE_PRIVATE int sqlite3WalClose(
46094   Wal *pWal,                      /* Wal to close */
46095   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
46096   int nBuf,
46097   u8 *zBuf                        /* Buffer of at least nBuf bytes */
46098 ){
46099   int rc = SQLITE_OK;
46100   if( pWal ){
46101     int isDelete = 0;             /* True to unlink wal and wal-index files */
46102
46103     /* If an EXCLUSIVE lock can be obtained on the database file (using the
46104     ** ordinary, rollback-mode locking methods, this guarantees that the
46105     ** connection associated with this log file is the only connection to
46106     ** the database. In this case checkpoint the database and unlink both
46107     ** the wal and wal-index files.
46108     **
46109     ** The EXCLUSIVE lock is not released before returning.
46110     */
46111     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
46112     if( rc==SQLITE_OK ){
46113       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
46114         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
46115       }
46116       rc = sqlite3WalCheckpoint(
46117           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
46118       );
46119       if( rc==SQLITE_OK ){
46120         int bPersist = -1;
46121         sqlite3OsFileControlHint(
46122             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
46123         );
46124         if( bPersist!=1 ){
46125           /* Try to delete the WAL file if the checkpoint completed and
46126           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
46127           ** mode (!bPersist) */
46128           isDelete = 1;
46129         }else if( pWal->mxWalSize>=0 ){
46130           /* Try to truncate the WAL file to zero bytes if the checkpoint
46131           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
46132           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
46133           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
46134           ** to zero bytes as truncating to the journal_size_limit might
46135           ** leave a corrupt WAL file on disk. */
46136           walLimitSize(pWal, 0);
46137         }
46138       }
46139     }
46140
46141     walIndexClose(pWal, isDelete);
46142     sqlite3OsClose(pWal->pWalFd);
46143     if( isDelete ){
46144       sqlite3BeginBenignMalloc();
46145       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
46146       sqlite3EndBenignMalloc();
46147     }
46148     WALTRACE(("WAL%p: closed\n", pWal));
46149     sqlite3_free((void *)pWal->apWiData);
46150     sqlite3_free(pWal);
46151   }
46152   return rc;
46153 }
46154
46155 /*
46156 ** Try to read the wal-index header.  Return 0 on success and 1 if
46157 ** there is a problem.
46158 **
46159 ** The wal-index is in shared memory.  Another thread or process might
46160 ** be writing the header at the same time this procedure is trying to
46161 ** read it, which might result in inconsistency.  A dirty read is detected
46162 ** by verifying that both copies of the header are the same and also by
46163 ** a checksum on the header.
46164 **
46165 ** If and only if the read is consistent and the header is different from
46166 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
46167 ** and *pChanged is set to 1.
46168 **
46169 ** If the checksum cannot be verified return non-zero. If the header
46170 ** is read successfully and the checksum verified, return zero.
46171 */
46172 static int walIndexTryHdr(Wal *pWal, int *pChanged){
46173   u32 aCksum[2];                  /* Checksum on the header content */
46174   WalIndexHdr h1, h2;             /* Two copies of the header content */
46175   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
46176
46177   /* The first page of the wal-index must be mapped at this point. */
46178   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46179
46180   /* Read the header. This might happen concurrently with a write to the
46181   ** same area of shared memory on a different CPU in a SMP,
46182   ** meaning it is possible that an inconsistent snapshot is read
46183   ** from the file. If this happens, return non-zero.
46184   **
46185   ** There are two copies of the header at the beginning of the wal-index.
46186   ** When reading, read [0] first then [1].  Writes are in the reverse order.
46187   ** Memory barriers are used to prevent the compiler or the hardware from
46188   ** reordering the reads and writes.
46189   */
46190   aHdr = walIndexHdr(pWal);
46191   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
46192   walShmBarrier(pWal);
46193   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
46194
46195   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
46196     return 1;   /* Dirty read */
46197   }  
46198   if( h1.isInit==0 ){
46199     return 1;   /* Malformed header - probably all zeros */
46200   }
46201   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
46202   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
46203     return 1;   /* Checksum does not match */
46204   }
46205
46206   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
46207     *pChanged = 1;
46208     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
46209     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46210     testcase( pWal->szPage<=32768 );
46211     testcase( pWal->szPage>=65536 );
46212   }
46213
46214   /* The header was successfully read. Return zero. */
46215   return 0;
46216 }
46217
46218 /*
46219 ** Read the wal-index header from the wal-index and into pWal->hdr.
46220 ** If the wal-header appears to be corrupt, try to reconstruct the
46221 ** wal-index from the WAL before returning.
46222 **
46223 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
46224 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
46225 ** to 0.
46226 **
46227 ** If the wal-index header is successfully read, return SQLITE_OK. 
46228 ** Otherwise an SQLite error code.
46229 */
46230 static int walIndexReadHdr(Wal *pWal, int *pChanged){
46231   int rc;                         /* Return code */
46232   int badHdr;                     /* True if a header read failed */
46233   volatile u32 *page0;            /* Chunk of wal-index containing header */
46234
46235   /* Ensure that page 0 of the wal-index (the page that contains the 
46236   ** wal-index header) is mapped. Return early if an error occurs here.
46237   */
46238   assert( pChanged );
46239   rc = walIndexPage(pWal, 0, &page0);
46240   if( rc!=SQLITE_OK ){
46241     return rc;
46242   };
46243   assert( page0 || pWal->writeLock==0 );
46244
46245   /* If the first page of the wal-index has been mapped, try to read the
46246   ** wal-index header immediately, without holding any lock. This usually
46247   ** works, but may fail if the wal-index header is corrupt or currently 
46248   ** being modified by another thread or process.
46249   */
46250   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
46251
46252   /* If the first attempt failed, it might have been due to a race
46253   ** with a writer.  So get a WRITE lock and try again.
46254   */
46255   assert( badHdr==0 || pWal->writeLock==0 );
46256   if( badHdr ){
46257     if( pWal->readOnly & WAL_SHM_RDONLY ){
46258       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
46259         walUnlockShared(pWal, WAL_WRITE_LOCK);
46260         rc = SQLITE_READONLY_RECOVERY;
46261       }
46262     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
46263       pWal->writeLock = 1;
46264       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
46265         badHdr = walIndexTryHdr(pWal, pChanged);
46266         if( badHdr ){
46267           /* If the wal-index header is still malformed even while holding
46268           ** a WRITE lock, it can only mean that the header is corrupted and
46269           ** needs to be reconstructed.  So run recovery to do exactly that.
46270           */
46271           rc = walIndexRecover(pWal);
46272           *pChanged = 1;
46273         }
46274       }
46275       pWal->writeLock = 0;
46276       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46277     }
46278   }
46279
46280   /* If the header is read successfully, check the version number to make
46281   ** sure the wal-index was not constructed with some future format that
46282   ** this version of SQLite cannot understand.
46283   */
46284   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
46285     rc = SQLITE_CANTOPEN_BKPT;
46286   }
46287
46288   return rc;
46289 }
46290
46291 /*
46292 ** This is the value that walTryBeginRead returns when it needs to
46293 ** be retried.
46294 */
46295 #define WAL_RETRY  (-1)
46296
46297 /*
46298 ** Attempt to start a read transaction.  This might fail due to a race or
46299 ** other transient condition.  When that happens, it returns WAL_RETRY to
46300 ** indicate to the caller that it is safe to retry immediately.
46301 **
46302 ** On success return SQLITE_OK.  On a permanent failure (such an
46303 ** I/O error or an SQLITE_BUSY because another process is running
46304 ** recovery) return a positive error code.
46305 **
46306 ** The useWal parameter is true to force the use of the WAL and disable
46307 ** the case where the WAL is bypassed because it has been completely
46308 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
46309 ** to make a copy of the wal-index header into pWal->hdr.  If the 
46310 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
46311 ** to the caller that the local paget cache is obsolete and needs to be 
46312 ** flushed.)  When useWal==1, the wal-index header is assumed to already
46313 ** be loaded and the pChanged parameter is unused.
46314 **
46315 ** The caller must set the cnt parameter to the number of prior calls to
46316 ** this routine during the current read attempt that returned WAL_RETRY.
46317 ** This routine will start taking more aggressive measures to clear the
46318 ** race conditions after multiple WAL_RETRY returns, and after an excessive
46319 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
46320 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
46321 ** and is not honoring the locking protocol.  There is a vanishingly small
46322 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
46323 ** bad luck when there is lots of contention for the wal-index, but that
46324 ** possibility is so small that it can be safely neglected, we believe.
46325 **
46326 ** On success, this routine obtains a read lock on 
46327 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
46328 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
46329 ** that means the Wal does not hold any read lock.  The reader must not
46330 ** access any database page that is modified by a WAL frame up to and
46331 ** including frame number aReadMark[pWal->readLock].  The reader will
46332 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
46333 ** Or if pWal->readLock==0, then the reader will ignore the WAL
46334 ** completely and get all content directly from the database file.
46335 ** If the useWal parameter is 1 then the WAL will never be ignored and
46336 ** this routine will always set pWal->readLock>0 on success.
46337 ** When the read transaction is completed, the caller must release the
46338 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
46339 **
46340 ** This routine uses the nBackfill and aReadMark[] fields of the header
46341 ** to select a particular WAL_READ_LOCK() that strives to let the
46342 ** checkpoint process do as much work as possible.  This routine might
46343 ** update values of the aReadMark[] array in the header, but if it does
46344 ** so it takes care to hold an exclusive lock on the corresponding
46345 ** WAL_READ_LOCK() while changing values.
46346 */
46347 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
46348   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
46349   u32 mxReadMark;                 /* Largest aReadMark[] value */
46350   int mxI;                        /* Index of largest aReadMark[] value */
46351   int i;                          /* Loop counter */
46352   int rc = SQLITE_OK;             /* Return code  */
46353
46354   assert( pWal->readLock<0 );     /* Not currently locked */
46355
46356   /* Take steps to avoid spinning forever if there is a protocol error.
46357   **
46358   ** Circumstances that cause a RETRY should only last for the briefest
46359   ** instances of time.  No I/O or other system calls are done while the
46360   ** locks are held, so the locks should not be held for very long. But 
46361   ** if we are unlucky, another process that is holding a lock might get
46362   ** paged out or take a page-fault that is time-consuming to resolve, 
46363   ** during the few nanoseconds that it is holding the lock.  In that case,
46364   ** it might take longer than normal for the lock to free.
46365   **
46366   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
46367   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
46368   ** is more of a scheduler yield than an actual delay.  But on the 10th
46369   ** an subsequent retries, the delays start becoming longer and longer, 
46370   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
46371   ** The total delay time before giving up is less than 1 second.
46372   */
46373   if( cnt>5 ){
46374     int nDelay = 1;                      /* Pause time in microseconds */
46375     if( cnt>100 ){
46376       VVA_ONLY( pWal->lockError = 1; )
46377       return SQLITE_PROTOCOL;
46378     }
46379     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
46380     sqlite3OsSleep(pWal->pVfs, nDelay);
46381   }
46382
46383   if( !useWal ){
46384     rc = walIndexReadHdr(pWal, pChanged);
46385     if( rc==SQLITE_BUSY ){
46386       /* If there is not a recovery running in another thread or process
46387       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
46388       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
46389       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46390       ** would be technically correct.  But the race is benign since with
46391       ** WAL_RETRY this routine will be called again and will probably be
46392       ** right on the second iteration.
46393       */
46394       if( pWal->apWiData[0]==0 ){
46395         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46396         ** We assume this is a transient condition, so return WAL_RETRY. The
46397         ** xShmMap() implementation used by the default unix and win32 VFS 
46398         ** modules may return SQLITE_BUSY due to a race condition in the 
46399         ** code that determines whether or not the shared-memory region 
46400         ** must be zeroed before the requested page is returned.
46401         */
46402         rc = WAL_RETRY;
46403       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46404         walUnlockShared(pWal, WAL_RECOVER_LOCK);
46405         rc = WAL_RETRY;
46406       }else if( rc==SQLITE_BUSY ){
46407         rc = SQLITE_BUSY_RECOVERY;
46408       }
46409     }
46410     if( rc!=SQLITE_OK ){
46411       return rc;
46412     }
46413   }
46414
46415   pInfo = walCkptInfo(pWal);
46416   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46417     /* The WAL has been completely backfilled (or it is empty).
46418     ** and can be safely ignored.
46419     */
46420     rc = walLockShared(pWal, WAL_READ_LOCK(0));
46421     walShmBarrier(pWal);
46422     if( rc==SQLITE_OK ){
46423       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46424         /* It is not safe to allow the reader to continue here if frames
46425         ** may have been appended to the log before READ_LOCK(0) was obtained.
46426         ** When holding READ_LOCK(0), the reader ignores the entire log file,
46427         ** which implies that the database file contains a trustworthy
46428         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46429         ** happening, this is usually correct.
46430         **
46431         ** However, if frames have been appended to the log (or if the log 
46432         ** is wrapped and written for that matter) before the READ_LOCK(0)
46433         ** is obtained, that is not necessarily true. A checkpointer may
46434         ** have started to backfill the appended frames but crashed before
46435         ** it finished. Leaving a corrupt image in the database file.
46436         */
46437         walUnlockShared(pWal, WAL_READ_LOCK(0));
46438         return WAL_RETRY;
46439       }
46440       pWal->readLock = 0;
46441       return SQLITE_OK;
46442     }else if( rc!=SQLITE_BUSY ){
46443       return rc;
46444     }
46445   }
46446
46447   /* If we get this far, it means that the reader will want to use
46448   ** the WAL to get at content from recent commits.  The job now is
46449   ** to select one of the aReadMark[] entries that is closest to
46450   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46451   */
46452   mxReadMark = 0;
46453   mxI = 0;
46454   for(i=1; i<WAL_NREADER; i++){
46455     u32 thisMark = pInfo->aReadMark[i];
46456     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46457       assert( thisMark!=READMARK_NOT_USED );
46458       mxReadMark = thisMark;
46459       mxI = i;
46460     }
46461   }
46462   /* There was once an "if" here. The extra "{" is to preserve indentation. */
46463   {
46464     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46465      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46466     ){
46467       for(i=1; i<WAL_NREADER; i++){
46468         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46469         if( rc==SQLITE_OK ){
46470           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46471           mxI = i;
46472           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46473           break;
46474         }else if( rc!=SQLITE_BUSY ){
46475           return rc;
46476         }
46477       }
46478     }
46479     if( mxI==0 ){
46480       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46481       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46482     }
46483
46484     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46485     if( rc ){
46486       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46487     }
46488     /* Now that the read-lock has been obtained, check that neither the
46489     ** value in the aReadMark[] array or the contents of the wal-index
46490     ** header have changed.
46491     **
46492     ** It is necessary to check that the wal-index header did not change
46493     ** between the time it was read and when the shared-lock was obtained
46494     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46495     ** that the log file may have been wrapped by a writer, or that frames
46496     ** that occur later in the log than pWal->hdr.mxFrame may have been
46497     ** copied into the database by a checkpointer. If either of these things
46498     ** happened, then reading the database with the current value of
46499     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46500     ** instead.
46501     **
46502     ** This does not guarantee that the copy of the wal-index header is up to
46503     ** date before proceeding. That would not be possible without somehow
46504     ** blocking writers. It only guarantees that a dangerous checkpoint or 
46505     ** log-wrap (either of which would require an exclusive lock on
46506     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46507     */
46508     walShmBarrier(pWal);
46509     if( pInfo->aReadMark[mxI]!=mxReadMark
46510      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46511     ){
46512       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46513       return WAL_RETRY;
46514     }else{
46515       assert( mxReadMark<=pWal->hdr.mxFrame );
46516       pWal->readLock = (i16)mxI;
46517     }
46518   }
46519   return rc;
46520 }
46521
46522 /*
46523 ** Begin a read transaction on the database.
46524 **
46525 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46526 ** it takes a snapshot of the state of the WAL and wal-index for the current
46527 ** instant in time.  The current thread will continue to use this snapshot.
46528 ** Other threads might append new content to the WAL and wal-index but
46529 ** that extra content is ignored by the current thread.
46530 **
46531 ** If the database contents have changes since the previous read
46532 ** transaction, then *pChanged is set to 1 before returning.  The
46533 ** Pager layer will use this to know that is cache is stale and
46534 ** needs to be flushed.
46535 */
46536 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46537   int rc;                         /* Return code */
46538   int cnt = 0;                    /* Number of TryBeginRead attempts */
46539
46540   do{
46541     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46542   }while( rc==WAL_RETRY );
46543   testcase( (rc&0xff)==SQLITE_BUSY );
46544   testcase( (rc&0xff)==SQLITE_IOERR );
46545   testcase( rc==SQLITE_PROTOCOL );
46546   testcase( rc==SQLITE_OK );
46547   return rc;
46548 }
46549
46550 /*
46551 ** Finish with a read transaction.  All this does is release the
46552 ** read-lock.
46553 */
46554 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46555   sqlite3WalEndWriteTransaction(pWal);
46556   if( pWal->readLock>=0 ){
46557     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46558     pWal->readLock = -1;
46559   }
46560 }
46561
46562 /*
46563 ** Read a page from the WAL, if it is present in the WAL and if the 
46564 ** current read transaction is configured to use the WAL.  
46565 **
46566 ** The *pInWal is set to 1 if the requested page is in the WAL and
46567 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
46568 ** the WAL and needs to be read out of the database.
46569 */
46570 SQLITE_PRIVATE int sqlite3WalRead(
46571   Wal *pWal,                      /* WAL handle */
46572   Pgno pgno,                      /* Database page number to read data for */
46573   int *pInWal,                    /* OUT: True if data is read from WAL */
46574   int nOut,                       /* Size of buffer pOut in bytes */
46575   u8 *pOut                        /* Buffer to write page data to */
46576 ){
46577   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
46578   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
46579   int iHash;                      /* Used to loop through N hash tables */
46580
46581   /* This routine is only be called from within a read transaction. */
46582   assert( pWal->readLock>=0 || pWal->lockError );
46583
46584   /* If the "last page" field of the wal-index header snapshot is 0, then
46585   ** no data will be read from the wal under any circumstances. Return early
46586   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
46587   ** then the WAL is ignored by the reader so return early, as if the 
46588   ** WAL were empty.
46589   */
46590   if( iLast==0 || pWal->readLock==0 ){
46591     *pInWal = 0;
46592     return SQLITE_OK;
46593   }
46594
46595   /* Search the hash table or tables for an entry matching page number
46596   ** pgno. Each iteration of the following for() loop searches one
46597   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46598   **
46599   ** This code might run concurrently to the code in walIndexAppend()
46600   ** that adds entries to the wal-index (and possibly to this hash 
46601   ** table). This means the value just read from the hash 
46602   ** slot (aHash[iKey]) may have been added before or after the 
46603   ** current read transaction was opened. Values added after the
46604   ** read transaction was opened may have been written incorrectly -
46605   ** i.e. these slots may contain garbage data. However, we assume
46606   ** that any slots written before the current read transaction was
46607   ** opened remain unmodified.
46608   **
46609   ** For the reasons above, the if(...) condition featured in the inner
46610   ** loop of the following block is more stringent that would be required 
46611   ** if we had exclusive access to the hash-table:
46612   **
46613   **   (aPgno[iFrame]==pgno): 
46614   **     This condition filters out normal hash-table collisions.
46615   **
46616   **   (iFrame<=iLast): 
46617   **     This condition filters out entries that were added to the hash
46618   **     table after the current read-transaction had started.
46619   */
46620   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46621     volatile ht_slot *aHash;      /* Pointer to hash table */
46622     volatile u32 *aPgno;          /* Pointer to array of page numbers */
46623     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
46624     int iKey;                     /* Hash slot index */
46625     int nCollide;                 /* Number of hash collisions remaining */
46626     int rc;                       /* Error code */
46627
46628     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46629     if( rc!=SQLITE_OK ){
46630       return rc;
46631     }
46632     nCollide = HASHTABLE_NSLOT;
46633     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46634       u32 iFrame = aHash[iKey] + iZero;
46635       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46636         /* assert( iFrame>iRead ); -- not true if there is corruption */
46637         iRead = iFrame;
46638       }
46639       if( (nCollide--)==0 ){
46640         return SQLITE_CORRUPT_BKPT;
46641       }
46642     }
46643   }
46644
46645 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46646   /* If expensive assert() statements are available, do a linear search
46647   ** of the wal-index file content. Make sure the results agree with the
46648   ** result obtained using the hash indexes above.  */
46649   {
46650     u32 iRead2 = 0;
46651     u32 iTest;
46652     for(iTest=iLast; iTest>0; iTest--){
46653       if( walFramePgno(pWal, iTest)==pgno ){
46654         iRead2 = iTest;
46655         break;
46656       }
46657     }
46658     assert( iRead==iRead2 );
46659   }
46660 #endif
46661
46662   /* If iRead is non-zero, then it is the log frame number that contains the
46663   ** required page. Read and return data from the log file.
46664   */
46665   if( iRead ){
46666     int sz;
46667     i64 iOffset;
46668     sz = pWal->hdr.szPage;
46669     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
46670     testcase( sz<=32768 );
46671     testcase( sz>=65536 );
46672     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46673     *pInWal = 1;
46674     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46675     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
46676   }
46677
46678   *pInWal = 0;
46679   return SQLITE_OK;
46680 }
46681
46682
46683 /* 
46684 ** Return the size of the database in pages (or zero, if unknown).
46685 */
46686 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46687   if( pWal && ALWAYS(pWal->readLock>=0) ){
46688     return pWal->hdr.nPage;
46689   }
46690   return 0;
46691 }
46692
46693
46694 /* 
46695 ** This function starts a write transaction on the WAL.
46696 **
46697 ** A read transaction must have already been started by a prior call
46698 ** to sqlite3WalBeginReadTransaction().
46699 **
46700 ** If another thread or process has written into the database since
46701 ** the read transaction was started, then it is not possible for this
46702 ** thread to write as doing so would cause a fork.  So this routine
46703 ** returns SQLITE_BUSY in that case and no write transaction is started.
46704 **
46705 ** There can only be a single writer active at a time.
46706 */
46707 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46708   int rc;
46709
46710   /* Cannot start a write transaction without first holding a read
46711   ** transaction. */
46712   assert( pWal->readLock>=0 );
46713
46714   if( pWal->readOnly ){
46715     return SQLITE_READONLY;
46716   }
46717
46718   /* Only one writer allowed at a time.  Get the write lock.  Return
46719   ** SQLITE_BUSY if unable.
46720   */
46721   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46722   if( rc ){
46723     return rc;
46724   }
46725   pWal->writeLock = 1;
46726
46727   /* If another connection has written to the database file since the
46728   ** time the read transaction on this connection was started, then
46729   ** the write is disallowed.
46730   */
46731   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46732     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46733     pWal->writeLock = 0;
46734     rc = SQLITE_BUSY;
46735   }
46736
46737   return rc;
46738 }
46739
46740 /*
46741 ** End a write transaction.  The commit has already been done.  This
46742 ** routine merely releases the lock.
46743 */
46744 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46745   if( pWal->writeLock ){
46746     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46747     pWal->writeLock = 0;
46748     pWal->truncateOnCommit = 0;
46749   }
46750   return SQLITE_OK;
46751 }
46752
46753 /*
46754 ** If any data has been written (but not committed) to the log file, this
46755 ** function moves the write-pointer back to the start of the transaction.
46756 **
46757 ** Additionally, the callback function is invoked for each frame written
46758 ** to the WAL since the start of the transaction. If the callback returns
46759 ** other than SQLITE_OK, it is not invoked again and the error code is
46760 ** returned to the caller.
46761 **
46762 ** Otherwise, if the callback function does not return an error, this
46763 ** function returns SQLITE_OK.
46764 */
46765 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46766   int rc = SQLITE_OK;
46767   if( ALWAYS(pWal->writeLock) ){
46768     Pgno iMax = pWal->hdr.mxFrame;
46769     Pgno iFrame;
46770   
46771     /* Restore the clients cache of the wal-index header to the state it
46772     ** was in before the client began writing to the database. 
46773     */
46774     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46775
46776     for(iFrame=pWal->hdr.mxFrame+1; 
46777         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
46778         iFrame++
46779     ){
46780       /* This call cannot fail. Unless the page for which the page number
46781       ** is passed as the second argument is (a) in the cache and 
46782       ** (b) has an outstanding reference, then xUndo is either a no-op
46783       ** (if (a) is false) or simply expels the page from the cache (if (b)
46784       ** is false).
46785       **
46786       ** If the upper layer is doing a rollback, it is guaranteed that there
46787       ** are no outstanding references to any page other than page 1. And
46788       ** page 1 is never written to the log until the transaction is
46789       ** committed. As a result, the call to xUndo may not fail.
46790       */
46791       assert( walFramePgno(pWal, iFrame)!=1 );
46792       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46793     }
46794     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
46795   }
46796   assert( rc==SQLITE_OK );
46797   return rc;
46798 }
46799
46800 /* 
46801 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
46802 ** values. This function populates the array with values required to 
46803 ** "rollback" the write position of the WAL handle back to the current 
46804 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46805 */
46806 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46807   assert( pWal->writeLock );
46808   aWalData[0] = pWal->hdr.mxFrame;
46809   aWalData[1] = pWal->hdr.aFrameCksum[0];
46810   aWalData[2] = pWal->hdr.aFrameCksum[1];
46811   aWalData[3] = pWal->nCkpt;
46812 }
46813
46814 /* 
46815 ** Move the write position of the WAL back to the point identified by
46816 ** the values in the aWalData[] array. aWalData must point to an array
46817 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46818 ** by a call to WalSavepoint().
46819 */
46820 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46821   int rc = SQLITE_OK;
46822
46823   assert( pWal->writeLock );
46824   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46825
46826   if( aWalData[3]!=pWal->nCkpt ){
46827     /* This savepoint was opened immediately after the write-transaction
46828     ** was started. Right after that, the writer decided to wrap around
46829     ** to the start of the log. Update the savepoint values to match.
46830     */
46831     aWalData[0] = 0;
46832     aWalData[3] = pWal->nCkpt;
46833   }
46834
46835   if( aWalData[0]<pWal->hdr.mxFrame ){
46836     pWal->hdr.mxFrame = aWalData[0];
46837     pWal->hdr.aFrameCksum[0] = aWalData[1];
46838     pWal->hdr.aFrameCksum[1] = aWalData[2];
46839     walCleanupHash(pWal);
46840   }
46841
46842   return rc;
46843 }
46844
46845
46846 /*
46847 ** This function is called just before writing a set of frames to the log
46848 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46849 ** to the current log file, it is possible to overwrite the start of the
46850 ** existing log file with the new frames (i.e. "reset" the log). If so,
46851 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46852 ** unchanged.
46853 **
46854 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46855 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46856 ** if an error occurs.
46857 */
46858 static int walRestartLog(Wal *pWal){
46859   int rc = SQLITE_OK;
46860   int cnt;
46861
46862   if( pWal->readLock==0 ){
46863     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46864     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46865     if( pInfo->nBackfill>0 ){
46866       u32 salt1;
46867       sqlite3_randomness(4, &salt1);
46868       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46869       if( rc==SQLITE_OK ){
46870         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46871         ** readers are currently using the WAL), then the transactions
46872         ** frames will overwrite the start of the existing log. Update the
46873         ** wal-index header to reflect this.
46874         **
46875         ** In theory it would be Ok to update the cache of the header only
46876         ** at this point. But updating the actual wal-index header is also
46877         ** safe and means there is no special case for sqlite3WalUndo()
46878         ** to handle if this transaction is rolled back.
46879         */
46880         int i;                    /* Loop counter */
46881         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46882
46883         pWal->nCkpt++;
46884         pWal->hdr.mxFrame = 0;
46885         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46886         aSalt[1] = salt1;
46887         walIndexWriteHdr(pWal);
46888         pInfo->nBackfill = 0;
46889         pInfo->aReadMark[1] = 0;
46890         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46891         assert( pInfo->aReadMark[0]==0 );
46892         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46893       }else if( rc!=SQLITE_BUSY ){
46894         return rc;
46895       }
46896     }
46897     walUnlockShared(pWal, WAL_READ_LOCK(0));
46898     pWal->readLock = -1;
46899     cnt = 0;
46900     do{
46901       int notUsed;
46902       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46903     }while( rc==WAL_RETRY );
46904     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46905     testcase( (rc&0xff)==SQLITE_IOERR );
46906     testcase( rc==SQLITE_PROTOCOL );
46907     testcase( rc==SQLITE_OK );
46908   }
46909   return rc;
46910 }
46911
46912 /*
46913 ** Information about the current state of the WAL file and where
46914 ** the next fsync should occur - passed from sqlite3WalFrames() into
46915 ** walWriteToLog().
46916 */
46917 typedef struct WalWriter {
46918   Wal *pWal;                   /* The complete WAL information */
46919   sqlite3_file *pFd;           /* The WAL file to which we write */
46920   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
46921   int syncFlags;               /* Flags for the fsync */
46922   int szPage;                  /* Size of one page */
46923 } WalWriter;
46924
46925 /*
46926 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
46927 ** Do a sync when crossing the p->iSyncPoint boundary.
46928 **
46929 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
46930 ** first write the part before iSyncPoint, then sync, then write the
46931 ** rest.
46932 */
46933 static int walWriteToLog(
46934   WalWriter *p,              /* WAL to write to */
46935   void *pContent,            /* Content to be written */
46936   int iAmt,                  /* Number of bytes to write */
46937   sqlite3_int64 iOffset      /* Start writing at this offset */
46938 ){
46939   int rc;
46940   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
46941     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
46942     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
46943     if( rc ) return rc;
46944     iOffset += iFirstAmt;
46945     iAmt -= iFirstAmt;
46946     pContent = (void*)(iFirstAmt + (char*)pContent);
46947     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
46948     rc = sqlite3OsSync(p->pFd, p->syncFlags);
46949     if( iAmt==0 || rc ) return rc;
46950   }
46951   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
46952   return rc;
46953 }
46954
46955 /*
46956 ** Write out a single frame of the WAL
46957 */
46958 static int walWriteOneFrame(
46959   WalWriter *p,               /* Where to write the frame */
46960   PgHdr *pPage,               /* The page of the frame to be written */
46961   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
46962   sqlite3_int64 iOffset       /* Byte offset at which to write */
46963 ){
46964   int rc;                         /* Result code from subfunctions */
46965   void *pData;                    /* Data actually written */
46966   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
46967 #if defined(SQLITE_HAS_CODEC)
46968   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
46969 #else
46970   pData = pPage->pData;
46971 #endif
46972   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
46973   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
46974   if( rc ) return rc;
46975   /* Write the page data */
46976   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
46977   return rc;
46978 }
46979
46980 /* 
46981 ** Write a set of frames to the log. The caller must hold the write-lock
46982 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46983 */
46984 SQLITE_PRIVATE int sqlite3WalFrames(
46985   Wal *pWal,                      /* Wal handle to write to */
46986   int szPage,                     /* Database page-size in bytes */
46987   PgHdr *pList,                   /* List of dirty pages to write */
46988   Pgno nTruncate,                 /* Database size after this commit */
46989   int isCommit,                   /* True if this is a commit */
46990   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
46991 ){
46992   int rc;                         /* Used to catch return codes */
46993   u32 iFrame;                     /* Next frame address */
46994   PgHdr *p;                       /* Iterator to run through pList with. */
46995   PgHdr *pLast = 0;               /* Last frame in list */
46996   int nExtra = 0;                 /* Number of extra copies of last page */
46997   int szFrame;                    /* The size of a single frame */
46998   i64 iOffset;                    /* Next byte to write in WAL file */
46999   WalWriter w;                    /* The writer */
47000
47001   assert( pList );
47002   assert( pWal->writeLock );
47003
47004   /* If this frame set completes a transaction, then nTruncate>0.  If
47005   ** nTruncate==0 then this frame set does not complete the transaction. */
47006   assert( (isCommit!=0)==(nTruncate!=0) );
47007
47008 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47009   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
47010     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
47011               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
47012   }
47013 #endif
47014
47015   /* See if it is possible to write these frames into the start of the
47016   ** log file, instead of appending to it at pWal->hdr.mxFrame.
47017   */
47018   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
47019     return rc;
47020   }
47021
47022   /* If this is the first frame written into the log, write the WAL
47023   ** header to the start of the WAL file. See comments at the top of
47024   ** this source file for a description of the WAL header format.
47025   */
47026   iFrame = pWal->hdr.mxFrame;
47027   if( iFrame==0 ){
47028     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
47029     u32 aCksum[2];                /* Checksum for wal-header */
47030
47031     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
47032     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
47033     sqlite3Put4byte(&aWalHdr[8], szPage);
47034     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
47035     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
47036     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
47037     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
47038     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
47039     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
47040     
47041     pWal->szPage = szPage;
47042     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
47043     pWal->hdr.aFrameCksum[0] = aCksum[0];
47044     pWal->hdr.aFrameCksum[1] = aCksum[1];
47045     pWal->truncateOnCommit = 1;
47046
47047     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
47048     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
47049     if( rc!=SQLITE_OK ){
47050       return rc;
47051     }
47052
47053     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
47054     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
47055     ** an out-of-order write following a WAL restart could result in
47056     ** database corruption.  See the ticket:
47057     **
47058     **     http://localhost:591/sqlite/info/ff5be73dee
47059     */
47060     if( pWal->syncHeader && sync_flags ){
47061       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
47062       if( rc ) return rc;
47063     }
47064   }
47065   assert( (int)pWal->szPage==szPage );
47066
47067   /* Setup information needed to write frames into the WAL */
47068   w.pWal = pWal;
47069   w.pFd = pWal->pWalFd;
47070   w.iSyncPoint = 0;
47071   w.syncFlags = sync_flags;
47072   w.szPage = szPage;
47073   iOffset = walFrameOffset(iFrame+1, szPage);
47074   szFrame = szPage + WAL_FRAME_HDRSIZE;
47075
47076   /* Write all frames into the log file exactly once */
47077   for(p=pList; p; p=p->pDirty){
47078     int nDbSize;   /* 0 normally.  Positive == commit flag */
47079     iFrame++;
47080     assert( iOffset==walFrameOffset(iFrame, szPage) );
47081     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
47082     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
47083     if( rc ) return rc;
47084     pLast = p;
47085     iOffset += szFrame;
47086   }
47087
47088   /* If this is the end of a transaction, then we might need to pad
47089   ** the transaction and/or sync the WAL file.
47090   **
47091   ** Padding and syncing only occur if this set of frames complete a
47092   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
47093   ** or synchonous==OFF, then no padding or syncing are needed.
47094   **
47095   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
47096   ** needed and only the sync is done.  If padding is needed, then the
47097   ** final frame is repeated (with its commit mark) until the next sector
47098   ** boundary is crossed.  Only the part of the WAL prior to the last
47099   ** sector boundary is synced; the part of the last frame that extends
47100   ** past the sector boundary is written after the sync.
47101   */
47102   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
47103     if( pWal->padToSectorBoundary ){
47104       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
47105       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
47106       while( iOffset<w.iSyncPoint ){
47107         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
47108         if( rc ) return rc;
47109         iOffset += szFrame;
47110         nExtra++;
47111       }
47112     }else{
47113       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
47114     }
47115   }
47116
47117   /* If this frame set completes the first transaction in the WAL and
47118   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
47119   ** journal size limit, if possible.
47120   */
47121   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
47122     i64 sz = pWal->mxWalSize;
47123     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
47124       sz = walFrameOffset(iFrame+nExtra+1, szPage);
47125     }
47126     walLimitSize(pWal, sz);
47127     pWal->truncateOnCommit = 0;
47128   }
47129
47130   /* Append data to the wal-index. It is not necessary to lock the 
47131   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
47132   ** guarantees that there are no other writers, and no data that may
47133   ** be in use by existing readers is being overwritten.
47134   */
47135   iFrame = pWal->hdr.mxFrame;
47136   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
47137     iFrame++;
47138     rc = walIndexAppend(pWal, iFrame, p->pgno);
47139   }
47140   while( rc==SQLITE_OK && nExtra>0 ){
47141     iFrame++;
47142     nExtra--;
47143     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
47144   }
47145
47146   if( rc==SQLITE_OK ){
47147     /* Update the private copy of the header. */
47148     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47149     testcase( szPage<=32768 );
47150     testcase( szPage>=65536 );
47151     pWal->hdr.mxFrame = iFrame;
47152     if( isCommit ){
47153       pWal->hdr.iChange++;
47154       pWal->hdr.nPage = nTruncate;
47155     }
47156     /* If this is a commit, update the wal-index header too. */
47157     if( isCommit ){
47158       walIndexWriteHdr(pWal);
47159       pWal->iCallback = iFrame;
47160     }
47161   }
47162
47163   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
47164   return rc;
47165 }
47166
47167 /* 
47168 ** This routine is called to implement sqlite3_wal_checkpoint() and
47169 ** related interfaces.
47170 **
47171 ** Obtain a CHECKPOINT lock and then backfill as much information as
47172 ** we can from WAL into the database.
47173 **
47174 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
47175 ** callback. In this case this function runs a blocking checkpoint.
47176 */
47177 SQLITE_PRIVATE int sqlite3WalCheckpoint(
47178   Wal *pWal,                      /* Wal connection */
47179   int eMode,                      /* PASSIVE, FULL or RESTART */
47180   int (*xBusy)(void*),            /* Function to call when busy */
47181   void *pBusyArg,                 /* Context argument for xBusyHandler */
47182   int sync_flags,                 /* Flags to sync db file with (or 0) */
47183   int nBuf,                       /* Size of temporary buffer */
47184   u8 *zBuf,                       /* Temporary buffer to use */
47185   int *pnLog,                     /* OUT: Number of frames in WAL */
47186   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
47187 ){
47188   int rc;                         /* Return code */
47189   int isChanged = 0;              /* True if a new wal-index header is loaded */
47190   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
47191
47192   assert( pWal->ckptLock==0 );
47193   assert( pWal->writeLock==0 );
47194
47195   if( pWal->readOnly ) return SQLITE_READONLY;
47196   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
47197   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
47198   if( rc ){
47199     /* Usually this is SQLITE_BUSY meaning that another thread or process
47200     ** is already running a checkpoint, or maybe a recovery.  But it might
47201     ** also be SQLITE_IOERR. */
47202     return rc;
47203   }
47204   pWal->ckptLock = 1;
47205
47206   /* If this is a blocking-checkpoint, then obtain the write-lock as well
47207   ** to prevent any writers from running while the checkpoint is underway.
47208   ** This has to be done before the call to walIndexReadHdr() below.
47209   **
47210   ** If the writer lock cannot be obtained, then a passive checkpoint is
47211   ** run instead. Since the checkpointer is not holding the writer lock,
47212   ** there is no point in blocking waiting for any readers. Assuming no 
47213   ** other error occurs, this function will return SQLITE_BUSY to the caller.
47214   */
47215   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47216     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
47217     if( rc==SQLITE_OK ){
47218       pWal->writeLock = 1;
47219     }else if( rc==SQLITE_BUSY ){
47220       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
47221       rc = SQLITE_OK;
47222     }
47223   }
47224
47225   /* Read the wal-index header. */
47226   if( rc==SQLITE_OK ){
47227     rc = walIndexReadHdr(pWal, &isChanged);
47228   }
47229
47230   /* Copy data from the log to the database file. */
47231   if( rc==SQLITE_OK ){
47232     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
47233       rc = SQLITE_CORRUPT_BKPT;
47234     }else{
47235       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
47236     }
47237
47238     /* If no error occurred, set the output variables. */
47239     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
47240       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
47241       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
47242     }
47243   }
47244
47245   if( isChanged ){
47246     /* If a new wal-index header was loaded before the checkpoint was 
47247     ** performed, then the pager-cache associated with pWal is now
47248     ** out of date. So zero the cached wal-index header to ensure that
47249     ** next time the pager opens a snapshot on this database it knows that
47250     ** the cache needs to be reset.
47251     */
47252     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47253   }
47254
47255   /* Release the locks. */
47256   sqlite3WalEndWriteTransaction(pWal);
47257   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
47258   pWal->ckptLock = 0;
47259   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
47260   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
47261 }
47262
47263 /* Return the value to pass to a sqlite3_wal_hook callback, the
47264 ** number of frames in the WAL at the point of the last commit since
47265 ** sqlite3WalCallback() was called.  If no commits have occurred since
47266 ** the last call, then return 0.
47267 */
47268 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
47269   u32 ret = 0;
47270   if( pWal ){
47271     ret = pWal->iCallback;
47272     pWal->iCallback = 0;
47273   }
47274   return (int)ret;
47275 }
47276
47277 /*
47278 ** This function is called to change the WAL subsystem into or out
47279 ** of locking_mode=EXCLUSIVE.
47280 **
47281 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
47282 ** into locking_mode=NORMAL.  This means that we must acquire a lock
47283 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
47284 ** or if the acquisition of the lock fails, then return 0.  If the
47285 ** transition out of exclusive-mode is successful, return 1.  This
47286 ** operation must occur while the pager is still holding the exclusive
47287 ** lock on the main database file.
47288 **
47289 ** If op is one, then change from locking_mode=NORMAL into 
47290 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
47291 ** be released.  Return 1 if the transition is made and 0 if the
47292 ** WAL is already in exclusive-locking mode - meaning that this
47293 ** routine is a no-op.  The pager must already hold the exclusive lock
47294 ** on the main database file before invoking this operation.
47295 **
47296 ** If op is negative, then do a dry-run of the op==1 case but do
47297 ** not actually change anything. The pager uses this to see if it
47298 ** should acquire the database exclusive lock prior to invoking
47299 ** the op==1 case.
47300 */
47301 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
47302   int rc;
47303   assert( pWal->writeLock==0 );
47304   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
47305
47306   /* pWal->readLock is usually set, but might be -1 if there was a 
47307   ** prior error while attempting to acquire are read-lock. This cannot 
47308   ** happen if the connection is actually in exclusive mode (as no xShmLock
47309   ** locks are taken in this case). Nor should the pager attempt to
47310   ** upgrade to exclusive-mode following such an error.
47311   */
47312   assert( pWal->readLock>=0 || pWal->lockError );
47313   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
47314
47315   if( op==0 ){
47316     if( pWal->exclusiveMode ){
47317       pWal->exclusiveMode = 0;
47318       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
47319         pWal->exclusiveMode = 1;
47320       }
47321       rc = pWal->exclusiveMode==0;
47322     }else{
47323       /* Already in locking_mode=NORMAL */
47324       rc = 0;
47325     }
47326   }else if( op>0 ){
47327     assert( pWal->exclusiveMode==0 );
47328     assert( pWal->readLock>=0 );
47329     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47330     pWal->exclusiveMode = 1;
47331     rc = 1;
47332   }else{
47333     rc = pWal->exclusiveMode==0;
47334   }
47335   return rc;
47336 }
47337
47338 /* 
47339 ** Return true if the argument is non-NULL and the WAL module is using
47340 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47341 ** WAL module is using shared-memory, return false. 
47342 */
47343 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
47344   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
47345 }
47346
47347 #ifdef SQLITE_ENABLE_ZIPVFS
47348 /*
47349 ** If the argument is not NULL, it points to a Wal object that holds a
47350 ** read-lock. This function returns the database page-size if it is known,
47351 ** or zero if it is not (or if pWal is NULL).
47352 */
47353 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
47354   assert( pWal==0 || pWal->readLock>=0 );
47355   return (pWal ? pWal->szPage : 0);
47356 }
47357 #endif
47358
47359 #endif /* #ifndef SQLITE_OMIT_WAL */
47360
47361 /************** End of wal.c *************************************************/
47362 /************** Begin file btmutex.c *****************************************/
47363 /*
47364 ** 2007 August 27
47365 **
47366 ** The author disclaims copyright to this source code.  In place of
47367 ** a legal notice, here is a blessing:
47368 **
47369 **    May you do good and not evil.
47370 **    May you find forgiveness for yourself and forgive others.
47371 **    May you share freely, never taking more than you give.
47372 **
47373 *************************************************************************
47374 **
47375 ** This file contains code used to implement mutexes on Btree objects.
47376 ** This code really belongs in btree.c.  But btree.c is getting too
47377 ** big and we want to break it down some.  This packaged seemed like
47378 ** a good breakout.
47379 */
47380 /************** Include btreeInt.h in the middle of btmutex.c ****************/
47381 /************** Begin file btreeInt.h ****************************************/
47382 /*
47383 ** 2004 April 6
47384 **
47385 ** The author disclaims copyright to this source code.  In place of
47386 ** a legal notice, here is a blessing:
47387 **
47388 **    May you do good and not evil.
47389 **    May you find forgiveness for yourself and forgive others.
47390 **    May you share freely, never taking more than you give.
47391 **
47392 *************************************************************************
47393 ** This file implements a external (disk-based) database using BTrees.
47394 ** For a detailed discussion of BTrees, refer to
47395 **
47396 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47397 **     "Sorting And Searching", pages 473-480. Addison-Wesley
47398 **     Publishing Company, Reading, Massachusetts.
47399 **
47400 ** The basic idea is that each page of the file contains N database
47401 ** entries and N+1 pointers to subpages.
47402 **
47403 **   ----------------------------------------------------------------
47404 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47405 **   ----------------------------------------------------------------
47406 **
47407 ** All of the keys on the page that Ptr(0) points to have values less
47408 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
47409 ** values greater than Key(0) and less than Key(1).  All of the keys
47410 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
47411 ** so forth.
47412 **
47413 ** Finding a particular key requires reading O(log(M)) pages from the 
47414 ** disk where M is the number of entries in the tree.
47415 **
47416 ** In this implementation, a single file can hold one or more separate 
47417 ** BTrees.  Each BTree is identified by the index of its root page.  The
47418 ** key and data for any entry are combined to form the "payload".  A
47419 ** fixed amount of payload can be carried directly on the database
47420 ** page.  If the payload is larger than the preset amount then surplus
47421 ** bytes are stored on overflow pages.  The payload for an entry
47422 ** and the preceding pointer are combined to form a "Cell".  Each 
47423 ** page has a small header which contains the Ptr(N) pointer and other
47424 ** information such as the size of key and data.
47425 **
47426 ** FORMAT DETAILS
47427 **
47428 ** The file is divided into pages.  The first page is called page 1,
47429 ** the second is page 2, and so forth.  A page number of zero indicates
47430 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
47431 ** Each page can be either a btree page, a freelist page, an overflow
47432 ** page, or a pointer-map page.
47433 **
47434 ** The first page is always a btree page.  The first 100 bytes of the first
47435 ** page contain a special header (the "file header") that describes the file.
47436 ** The format of the file header is as follows:
47437 **
47438 **   OFFSET   SIZE    DESCRIPTION
47439 **      0      16     Header string: "SQLite format 3\000"
47440 **     16       2     Page size in bytes.  
47441 **     18       1     File format write version
47442 **     19       1     File format read version
47443 **     20       1     Bytes of unused space at the end of each page
47444 **     21       1     Max embedded payload fraction
47445 **     22       1     Min embedded payload fraction
47446 **     23       1     Min leaf payload fraction
47447 **     24       4     File change counter
47448 **     28       4     Reserved for future use
47449 **     32       4     First freelist page
47450 **     36       4     Number of freelist pages in the file
47451 **     40      60     15 4-byte meta values passed to higher layers
47452 **
47453 **     40       4     Schema cookie
47454 **     44       4     File format of schema layer
47455 **     48       4     Size of page cache
47456 **     52       4     Largest root-page (auto/incr_vacuum)
47457 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
47458 **     60       4     User version
47459 **     64       4     Incremental vacuum mode
47460 **     68       4     unused
47461 **     72       4     unused
47462 **     76       4     unused
47463 **
47464 ** All of the integer values are big-endian (most significant byte first).
47465 **
47466 ** The file change counter is incremented when the database is changed
47467 ** This counter allows other processes to know when the file has changed
47468 ** and thus when they need to flush their cache.
47469 **
47470 ** The max embedded payload fraction is the amount of the total usable
47471 ** space in a page that can be consumed by a single cell for standard
47472 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
47473 ** is to limit the maximum cell size so that at least 4 cells will fit
47474 ** on one page.  Thus the default max embedded payload fraction is 64.
47475 **
47476 ** If the payload for a cell is larger than the max payload, then extra
47477 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
47478 ** as many bytes as possible are moved into the overflow pages without letting
47479 ** the cell size drop below the min embedded payload fraction.
47480 **
47481 ** The min leaf payload fraction is like the min embedded payload fraction
47482 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
47483 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47484 ** not specified in the header.
47485 **
47486 ** Each btree pages is divided into three sections:  The header, the
47487 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
47488 ** file header that occurs before the page header.
47489 **
47490 **      |----------------|
47491 **      | file header    |   100 bytes.  Page 1 only.
47492 **      |----------------|
47493 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
47494 **      |----------------|
47495 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
47496 **      | array          |   |  Grows downward
47497 **      |                |   v
47498 **      |----------------|
47499 **      | unallocated    |
47500 **      | space          |
47501 **      |----------------|   ^  Grows upwards
47502 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
47503 **      | area           |   |  and free space fragments.
47504 **      |----------------|
47505 **
47506 ** The page headers looks like this:
47507 **
47508 **   OFFSET   SIZE     DESCRIPTION
47509 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47510 **      1       2      byte offset to the first freeblock
47511 **      3       2      number of cells on this page
47512 **      5       2      first byte of the cell content area
47513 **      7       1      number of fragmented free bytes
47514 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
47515 **
47516 ** The flags define the format of this btree page.  The leaf flag means that
47517 ** this page has no children.  The zerodata flag means that this page carries
47518 ** only keys and no data.  The intkey flag means that the key is a integer
47519 ** which is stored in the key size entry of the cell header rather than in
47520 ** the payload area.
47521 **
47522 ** The cell pointer array begins on the first byte after the page header.
47523 ** The cell pointer array contains zero or more 2-byte numbers which are
47524 ** offsets from the beginning of the page to the cell content in the cell
47525 ** content area.  The cell pointers occur in sorted order.  The system strives
47526 ** to keep free space after the last cell pointer so that new cells can
47527 ** be easily added without having to defragment the page.
47528 **
47529 ** Cell content is stored at the very end of the page and grows toward the
47530 ** beginning of the page.
47531 **
47532 ** Unused space within the cell content area is collected into a linked list of
47533 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
47534 ** to the first freeblock is given in the header.  Freeblocks occur in
47535 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
47536 ** any group of 3 or fewer unused bytes in the cell content area cannot
47537 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
47538 ** a fragment.  The total number of bytes in all fragments is recorded.
47539 ** in the page header at offset 7.
47540 **
47541 **    SIZE    DESCRIPTION
47542 **      2     Byte offset of the next freeblock
47543 **      2     Bytes in this freeblock
47544 **
47545 ** Cells are of variable length.  Cells are stored in the cell content area at
47546 ** the end of the page.  Pointers to the cells are in the cell pointer array
47547 ** that immediately follows the page header.  Cells is not necessarily
47548 ** contiguous or in order, but cell pointers are contiguous and in order.
47549 **
47550 ** Cell content makes use of variable length integers.  A variable
47551 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
47552 ** byte are used.  The integer consists of all bytes that have bit 8 set and
47553 ** the first byte with bit 8 clear.  The most significant byte of the integer
47554 ** appears first.  A variable-length integer may not be more than 9 bytes long.
47555 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
47556 ** allows a 64-bit integer to be encoded in 9 bytes.
47557 **
47558 **    0x00                      becomes  0x00000000
47559 **    0x7f                      becomes  0x0000007f
47560 **    0x81 0x00                 becomes  0x00000080
47561 **    0x82 0x00                 becomes  0x00000100
47562 **    0x80 0x7f                 becomes  0x0000007f
47563 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
47564 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
47565 **
47566 ** Variable length integers are used for rowids and to hold the number of
47567 ** bytes of key and data in a btree cell.
47568 **
47569 ** The content of a cell looks like this:
47570 **
47571 **    SIZE    DESCRIPTION
47572 **      4     Page number of the left child. Omitted if leaf flag is set.
47573 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
47574 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
47575 **      *     Payload
47576 **      4     First page of the overflow chain.  Omitted if no overflow
47577 **
47578 ** Overflow pages form a linked list.  Each page except the last is completely
47579 ** filled with data (pagesize - 4 bytes).  The last page can have as little
47580 ** as 1 byte of data.
47581 **
47582 **    SIZE    DESCRIPTION
47583 **      4     Page number of next overflow page
47584 **      *     Data
47585 **
47586 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
47587 ** file header points to the first in a linked list of trunk page.  Each trunk
47588 ** page points to multiple leaf pages.  The content of a leaf page is
47589 ** unspecified.  A trunk page looks like this:
47590 **
47591 **    SIZE    DESCRIPTION
47592 **      4     Page number of next trunk page
47593 **      4     Number of leaf pointers on this page
47594 **      *     zero or more pages numbers of leaves
47595 */
47596
47597
47598 /* The following value is the maximum cell size assuming a maximum page
47599 ** size give above.
47600 */
47601 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
47602
47603 /* The maximum number of cells on a single page of the database.  This
47604 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
47605 ** plus 2 bytes for the index to the cell in the page header).  Such
47606 ** small cells will be rare, but they are possible.
47607 */
47608 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47609
47610 /* Forward declarations */
47611 typedef struct MemPage MemPage;
47612 typedef struct BtLock BtLock;
47613
47614 /*
47615 ** This is a magic string that appears at the beginning of every
47616 ** SQLite database in order to identify the file as a real database.
47617 **
47618 ** You can change this value at compile-time by specifying a
47619 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
47620 ** header must be exactly 16 bytes including the zero-terminator so
47621 ** the string itself should be 15 characters long.  If you change
47622 ** the header, then your custom library will not be able to read 
47623 ** databases generated by the standard tools and the standard tools
47624 ** will not be able to read databases created by your custom library.
47625 */
47626 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47627 #  define SQLITE_FILE_HEADER "SQLite format 3"
47628 #endif
47629
47630 /*
47631 ** Page type flags.  An ORed combination of these flags appear as the
47632 ** first byte of on-disk image of every BTree page.
47633 */
47634 #define PTF_INTKEY    0x01
47635 #define PTF_ZERODATA  0x02
47636 #define PTF_LEAFDATA  0x04
47637 #define PTF_LEAF      0x08
47638
47639 /*
47640 ** As each page of the file is loaded into memory, an instance of the following
47641 ** structure is appended and initialized to zero.  This structure stores
47642 ** information about the page that is decoded from the raw file page.
47643 **
47644 ** The pParent field points back to the parent page.  This allows us to
47645 ** walk up the BTree from any leaf to the root.  Care must be taken to
47646 ** unref() the parent page pointer when this page is no longer referenced.
47647 ** The pageDestructor() routine handles that chore.
47648 **
47649 ** Access to all fields of this structure is controlled by the mutex
47650 ** stored in MemPage.pBt->mutex.
47651 */
47652 struct MemPage {
47653   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
47654   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
47655   u8 intKey;           /* True if intkey flag is set */
47656   u8 leaf;             /* True if leaf flag is set */
47657   u8 hasData;          /* True if this page stores data */
47658   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
47659   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
47660   u8 max1bytePayload;  /* min(maxLocal,127) */
47661   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47662   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
47663   u16 cellOffset;      /* Index in aData of first cell pointer */
47664   u16 nFree;           /* Number of free bytes on the page */
47665   u16 nCell;           /* Number of cells on this page, local and ovfl */
47666   u16 maskPage;        /* Mask for page offset */
47667   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
47668                        ** non-overflow cell */
47669   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
47670   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
47671   u8 *aData;           /* Pointer to disk image of the page data */
47672   u8 *aDataEnd;        /* One byte past the end of usable data */
47673   u8 *aCellIdx;        /* The cell index area */
47674   DbPage *pDbPage;     /* Pager page handle */
47675   Pgno pgno;           /* Page number for this page */
47676 };
47677
47678 /*
47679 ** The in-memory image of a disk page has the auxiliary information appended
47680 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
47681 ** that extra information.
47682 */
47683 #define EXTRA_SIZE sizeof(MemPage)
47684
47685 /*
47686 ** A linked list of the following structures is stored at BtShared.pLock.
47687 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
47688 ** is opened on the table with root page BtShared.iTable. Locks are removed
47689 ** from this list when a transaction is committed or rolled back, or when
47690 ** a btree handle is closed.
47691 */
47692 struct BtLock {
47693   Btree *pBtree;        /* Btree handle holding this lock */
47694   Pgno iTable;          /* Root page of table */
47695   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
47696   BtLock *pNext;        /* Next in BtShared.pLock list */
47697 };
47698
47699 /* Candidate values for BtLock.eLock */
47700 #define READ_LOCK     1
47701 #define WRITE_LOCK    2
47702
47703 /* A Btree handle
47704 **
47705 ** A database connection contains a pointer to an instance of
47706 ** this object for every database file that it has open.  This structure
47707 ** is opaque to the database connection.  The database connection cannot
47708 ** see the internals of this structure and only deals with pointers to
47709 ** this structure.
47710 **
47711 ** For some database files, the same underlying database cache might be 
47712 ** shared between multiple connections.  In that case, each connection
47713 ** has it own instance of this object.  But each instance of this object
47714 ** points to the same BtShared object.  The database cache and the
47715 ** schema associated with the database file are all contained within
47716 ** the BtShared object.
47717 **
47718 ** All fields in this structure are accessed under sqlite3.mutex.
47719 ** The pBt pointer itself may not be changed while there exists cursors 
47720 ** in the referenced BtShared that point back to this Btree since those
47721 ** cursors have to go through this Btree to find their BtShared and
47722 ** they often do so without holding sqlite3.mutex.
47723 */
47724 struct Btree {
47725   sqlite3 *db;       /* The database connection holding this btree */
47726   BtShared *pBt;     /* Sharable content of this btree */
47727   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47728   u8 sharable;       /* True if we can share pBt with another db */
47729   u8 locked;         /* True if db currently has pBt locked */
47730   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
47731   int nBackup;       /* Number of backup operations reading this btree */
47732   Btree *pNext;      /* List of other sharable Btrees from the same db */
47733   Btree *pPrev;      /* Back pointer of the same list */
47734 #ifndef SQLITE_OMIT_SHARED_CACHE
47735   BtLock lock;       /* Object used to lock page 1 */
47736 #endif
47737 };
47738
47739 /*
47740 ** Btree.inTrans may take one of the following values.
47741 **
47742 ** If the shared-data extension is enabled, there may be multiple users
47743 ** of the Btree structure. At most one of these may open a write transaction,
47744 ** but any number may have active read transactions.
47745 */
47746 #define TRANS_NONE  0
47747 #define TRANS_READ  1
47748 #define TRANS_WRITE 2
47749
47750 /*
47751 ** An instance of this object represents a single database file.
47752 ** 
47753 ** A single database file can be in use at the same time by two
47754 ** or more database connections.  When two or more connections are
47755 ** sharing the same database file, each connection has it own
47756 ** private Btree object for the file and each of those Btrees points
47757 ** to this one BtShared object.  BtShared.nRef is the number of
47758 ** connections currently sharing this database file.
47759 **
47760 ** Fields in this structure are accessed under the BtShared.mutex
47761 ** mutex, except for nRef and pNext which are accessed under the
47762 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
47763 ** may not be modified once it is initially set as long as nRef>0.
47764 ** The pSchema field may be set once under BtShared.mutex and
47765 ** thereafter is unchanged as long as nRef>0.
47766 **
47767 ** isPending:
47768 **
47769 **   If a BtShared client fails to obtain a write-lock on a database
47770 **   table (because there exists one or more read-locks on the table),
47771 **   the shared-cache enters 'pending-lock' state and isPending is
47772 **   set to true.
47773 **
47774 **   The shared-cache leaves the 'pending lock' state when either of
47775 **   the following occur:
47776 **
47777 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
47778 **     2) The number of locks held by other connections drops to zero.
47779 **
47780 **   while in the 'pending-lock' state, no connection may start a new
47781 **   transaction.
47782 **
47783 **   This feature is included to help prevent writer-starvation.
47784 */
47785 struct BtShared {
47786   Pager *pPager;        /* The page cache */
47787   sqlite3 *db;          /* Database connection currently using this Btree */
47788   BtCursor *pCursor;    /* A list of all open cursors */
47789   MemPage *pPage1;      /* First page of the database */
47790   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47791 #ifndef SQLITE_OMIT_AUTOVACUUM
47792   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47793   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47794 #endif
47795   u8 inTransaction;     /* Transaction state */
47796   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
47797   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
47798   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47799   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47800   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47801   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47802   u32 pageSize;         /* Total number of bytes on a page */
47803   u32 usableSize;       /* Number of usable bytes on each page */
47804   int nTransaction;     /* Number of open transactions (read + write) */
47805   u32 nPage;            /* Number of pages in the database */
47806   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47807   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47808   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47809   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47810 #ifndef SQLITE_OMIT_SHARED_CACHE
47811   int nRef;             /* Number of references to this structure */
47812   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47813   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47814   Btree *pWriter;       /* Btree with currently open write transaction */
47815 #endif
47816   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47817 };
47818
47819 /*
47820 ** Allowed values for BtShared.btsFlags
47821 */
47822 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
47823 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
47824 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
47825 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
47826 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
47827 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
47828 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
47829
47830 /*
47831 ** An instance of the following structure is used to hold information
47832 ** about a cell.  The parseCellPtr() function fills in this structure
47833 ** based on information extract from the raw disk page.
47834 */
47835 typedef struct CellInfo CellInfo;
47836 struct CellInfo {
47837   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47838   u8 *pCell;     /* Pointer to the start of cell content */
47839   u32 nData;     /* Number of bytes of data */
47840   u32 nPayload;  /* Total amount of payload */
47841   u16 nHeader;   /* Size of the cell content header in bytes */
47842   u16 nLocal;    /* Amount of payload held locally */
47843   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47844   u16 nSize;     /* Size of the cell content on the main b-tree page */
47845 };
47846
47847 /*
47848 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47849 ** this will be declared corrupt. This value is calculated based on a
47850 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47851 ** root-node and 3 for all other internal nodes.
47852 **
47853 ** If a tree that appears to be taller than this is encountered, it is
47854 ** assumed that the database is corrupt.
47855 */
47856 #define BTCURSOR_MAX_DEPTH 20
47857
47858 /*
47859 ** A cursor is a pointer to a particular entry within a particular
47860 ** b-tree within a database file.
47861 **
47862 ** The entry is identified by its MemPage and the index in
47863 ** MemPage.aCell[] of the entry.
47864 **
47865 ** A single database file can be shared by two more database connections,
47866 ** but cursors cannot be shared.  Each cursor is associated with a
47867 ** particular database connection identified BtCursor.pBtree.db.
47868 **
47869 ** Fields in this structure are accessed under the BtShared.mutex
47870 ** found at self->pBt->mutex. 
47871 */
47872 struct BtCursor {
47873   Btree *pBtree;            /* The Btree to which this cursor belongs */
47874   BtShared *pBt;            /* The BtShared this cursor points to */
47875   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47876   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47877 #ifndef SQLITE_OMIT_INCRBLOB
47878   Pgno *aOverflow;          /* Cache of overflow page locations */
47879 #endif
47880   Pgno pgnoRoot;            /* The root page of this tree */
47881   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47882   CellInfo info;            /* A parse of the cell we are pointing at */
47883   i64 nKey;        /* Size of pKey, or last integer key */
47884   void *pKey;      /* Saved key that was cursor's last known position */
47885   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47886   u8 wrFlag;                /* True if writable */
47887   u8 atLast;                /* Cursor pointing to the last entry */
47888   u8 validNKey;             /* True if info.nKey is valid */
47889   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47890 #ifndef SQLITE_OMIT_INCRBLOB
47891   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47892 #endif
47893   u8 hints;                             /* As configured by CursorSetHints() */
47894   i16 iPage;                            /* Index of current page in apPage */
47895   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47896   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47897 };
47898
47899 /*
47900 ** Potential values for BtCursor.eState.
47901 **
47902 ** CURSOR_VALID:
47903 **   Cursor points to a valid entry. getPayload() etc. may be called.
47904 **
47905 ** CURSOR_INVALID:
47906 **   Cursor does not point to a valid entry. This can happen (for example) 
47907 **   because the table is empty or because BtreeCursorFirst() has not been
47908 **   called.
47909 **
47910 ** CURSOR_REQUIRESEEK:
47911 **   The table that this cursor was opened on still exists, but has been 
47912 **   modified since the cursor was last used. The cursor position is saved
47913 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
47914 **   this state, restoreCursorPosition() can be called to attempt to
47915 **   seek the cursor to the saved position.
47916 **
47917 ** CURSOR_FAULT:
47918 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47919 **   on a different connection that shares the BtShared cache with this
47920 **   cursor.  The error has left the cache in an inconsistent state.
47921 **   Do nothing else with this cursor.  Any attempt to use the cursor
47922 **   should return the error code stored in BtCursor.skip
47923 */
47924 #define CURSOR_INVALID           0
47925 #define CURSOR_VALID             1
47926 #define CURSOR_REQUIRESEEK       2
47927 #define CURSOR_FAULT             3
47928
47929 /* 
47930 ** The database page the PENDING_BYTE occupies. This page is never used.
47931 */
47932 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
47933
47934 /*
47935 ** These macros define the location of the pointer-map entry for a 
47936 ** database page. The first argument to each is the number of usable
47937 ** bytes on each page of the database (often 1024). The second is the
47938 ** page number to look up in the pointer map.
47939 **
47940 ** PTRMAP_PAGENO returns the database page number of the pointer-map
47941 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
47942 ** the offset of the requested map entry.
47943 **
47944 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
47945 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
47946 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
47947 ** this test.
47948 */
47949 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
47950 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
47951 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
47952
47953 /*
47954 ** The pointer map is a lookup table that identifies the parent page for
47955 ** each child page in the database file.  The parent page is the page that
47956 ** contains a pointer to the child.  Every page in the database contains
47957 ** 0 or 1 parent pages.  (In this context 'database page' refers
47958 ** to any page that is not part of the pointer map itself.)  Each pointer map
47959 ** entry consists of a single byte 'type' and a 4 byte parent page number.
47960 ** The PTRMAP_XXX identifiers below are the valid types.
47961 **
47962 ** The purpose of the pointer map is to facility moving pages from one
47963 ** position in the file to another as part of autovacuum.  When a page
47964 ** is moved, the pointer in its parent must be updated to point to the
47965 ** new location.  The pointer map is used to locate the parent page quickly.
47966 **
47967 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
47968 **                  used in this case.
47969 **
47970 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
47971 **                  is not used in this case.
47972 **
47973 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
47974 **                   overflow pages. The page number identifies the page that
47975 **                   contains the cell with a pointer to this overflow page.
47976 **
47977 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
47978 **                   overflow pages. The page-number identifies the previous
47979 **                   page in the overflow page list.
47980 **
47981 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
47982 **               identifies the parent page in the btree.
47983 */
47984 #define PTRMAP_ROOTPAGE 1
47985 #define PTRMAP_FREEPAGE 2
47986 #define PTRMAP_OVERFLOW1 3
47987 #define PTRMAP_OVERFLOW2 4
47988 #define PTRMAP_BTREE 5
47989
47990 /* A bunch of assert() statements to check the transaction state variables
47991 ** of handle p (type Btree*) are internally consistent.
47992 */
47993 #define btreeIntegrity(p) \
47994   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
47995   assert( p->pBt->inTransaction>=p->inTrans ); 
47996
47997
47998 /*
47999 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
48000 ** if the database supports auto-vacuum or not. Because it is used
48001 ** within an expression that is an argument to another macro 
48002 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
48003 ** So, this macro is defined instead.
48004 */
48005 #ifndef SQLITE_OMIT_AUTOVACUUM
48006 #define ISAUTOVACUUM (pBt->autoVacuum)
48007 #else
48008 #define ISAUTOVACUUM 0
48009 #endif
48010
48011
48012 /*
48013 ** This structure is passed around through all the sanity checking routines
48014 ** in order to keep track of some global state information.
48015 **
48016 ** The aRef[] array is allocated so that there is 1 bit for each page in
48017 ** the database. As the integrity-check proceeds, for each page used in
48018 ** the database the corresponding bit is set. This allows integrity-check to 
48019 ** detect pages that are used twice and orphaned pages (both of which 
48020 ** indicate corruption).
48021 */
48022 typedef struct IntegrityCk IntegrityCk;
48023 struct IntegrityCk {
48024   BtShared *pBt;    /* The tree being checked out */
48025   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
48026   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
48027   Pgno nPage;       /* Number of pages in the database */
48028   int mxErr;        /* Stop accumulating errors when this reaches zero */
48029   int nErr;         /* Number of messages written to zErrMsg so far */
48030   int mallocFailed; /* A memory allocation error has occurred */
48031   StrAccum errMsg;  /* Accumulate the error message text here */
48032 };
48033
48034 /*
48035 ** Routines to read or write a two- and four-byte big-endian integer values.
48036 */
48037 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
48038 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
48039 #define get4byte sqlite3Get4byte
48040 #define put4byte sqlite3Put4byte
48041
48042 /************** End of btreeInt.h ********************************************/
48043 /************** Continuing where we left off in btmutex.c ********************/
48044 #ifndef SQLITE_OMIT_SHARED_CACHE
48045 #if SQLITE_THREADSAFE
48046
48047 /*
48048 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
48049 ** set BtShared.db to the database handle associated with p and the
48050 ** p->locked boolean to true.
48051 */
48052 static void lockBtreeMutex(Btree *p){
48053   assert( p->locked==0 );
48054   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
48055   assert( sqlite3_mutex_held(p->db->mutex) );
48056
48057   sqlite3_mutex_enter(p->pBt->mutex);
48058   p->pBt->db = p->db;
48059   p->locked = 1;
48060 }
48061
48062 /*
48063 ** Release the BtShared mutex associated with B-Tree handle p and
48064 ** clear the p->locked boolean.
48065 */
48066 static void unlockBtreeMutex(Btree *p){
48067   BtShared *pBt = p->pBt;
48068   assert( p->locked==1 );
48069   assert( sqlite3_mutex_held(pBt->mutex) );
48070   assert( sqlite3_mutex_held(p->db->mutex) );
48071   assert( p->db==pBt->db );
48072
48073   sqlite3_mutex_leave(pBt->mutex);
48074   p->locked = 0;
48075 }
48076
48077 /*
48078 ** Enter a mutex on the given BTree object.
48079 **
48080 ** If the object is not sharable, then no mutex is ever required
48081 ** and this routine is a no-op.  The underlying mutex is non-recursive.
48082 ** But we keep a reference count in Btree.wantToLock so the behavior
48083 ** of this interface is recursive.
48084 **
48085 ** To avoid deadlocks, multiple Btrees are locked in the same order
48086 ** by all database connections.  The p->pNext is a list of other
48087 ** Btrees belonging to the same database connection as the p Btree
48088 ** which need to be locked after p.  If we cannot get a lock on
48089 ** p, then first unlock all of the others on p->pNext, then wait
48090 ** for the lock to become available on p, then relock all of the
48091 ** subsequent Btrees that desire a lock.
48092 */
48093 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48094   Btree *pLater;
48095
48096   /* Some basic sanity checking on the Btree.  The list of Btrees
48097   ** connected by pNext and pPrev should be in sorted order by
48098   ** Btree.pBt value. All elements of the list should belong to
48099   ** the same connection. Only shared Btrees are on the list. */
48100   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
48101   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
48102   assert( p->pNext==0 || p->pNext->db==p->db );
48103   assert( p->pPrev==0 || p->pPrev->db==p->db );
48104   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
48105
48106   /* Check for locking consistency */
48107   assert( !p->locked || p->wantToLock>0 );
48108   assert( p->sharable || p->wantToLock==0 );
48109
48110   /* We should already hold a lock on the database connection */
48111   assert( sqlite3_mutex_held(p->db->mutex) );
48112
48113   /* Unless the database is sharable and unlocked, then BtShared.db
48114   ** should already be set correctly. */
48115   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
48116
48117   if( !p->sharable ) return;
48118   p->wantToLock++;
48119   if( p->locked ) return;
48120
48121   /* In most cases, we should be able to acquire the lock we
48122   ** want without having to go throught the ascending lock
48123   ** procedure that follows.  Just be sure not to block.
48124   */
48125   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
48126     p->pBt->db = p->db;
48127     p->locked = 1;
48128     return;
48129   }
48130
48131   /* To avoid deadlock, first release all locks with a larger
48132   ** BtShared address.  Then acquire our lock.  Then reacquire
48133   ** the other BtShared locks that we used to hold in ascending
48134   ** order.
48135   */
48136   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48137     assert( pLater->sharable );
48138     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
48139     assert( !pLater->locked || pLater->wantToLock>0 );
48140     if( pLater->locked ){
48141       unlockBtreeMutex(pLater);
48142     }
48143   }
48144   lockBtreeMutex(p);
48145   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48146     if( pLater->wantToLock ){
48147       lockBtreeMutex(pLater);
48148     }
48149   }
48150 }
48151
48152 /*
48153 ** Exit the recursive mutex on a Btree.
48154 */
48155 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
48156   if( p->sharable ){
48157     assert( p->wantToLock>0 );
48158     p->wantToLock--;
48159     if( p->wantToLock==0 ){
48160       unlockBtreeMutex(p);
48161     }
48162   }
48163 }
48164
48165 #ifndef NDEBUG
48166 /*
48167 ** Return true if the BtShared mutex is held on the btree, or if the
48168 ** B-Tree is not marked as sharable.
48169 **
48170 ** This routine is used only from within assert() statements.
48171 */
48172 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
48173   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
48174   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
48175   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
48176   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
48177
48178   return (p->sharable==0 || p->locked);
48179 }
48180 #endif
48181
48182
48183 #ifndef SQLITE_OMIT_INCRBLOB
48184 /*
48185 ** Enter and leave a mutex on a Btree given a cursor owned by that
48186 ** Btree.  These entry points are used by incremental I/O and can be
48187 ** omitted if that module is not used.
48188 */
48189 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
48190   sqlite3BtreeEnter(pCur->pBtree);
48191 }
48192 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
48193   sqlite3BtreeLeave(pCur->pBtree);
48194 }
48195 #endif /* SQLITE_OMIT_INCRBLOB */
48196
48197
48198 /*
48199 ** Enter the mutex on every Btree associated with a database
48200 ** connection.  This is needed (for example) prior to parsing
48201 ** a statement since we will be comparing table and column names
48202 ** against all schemas and we do not want those schemas being
48203 ** reset out from under us.
48204 **
48205 ** There is a corresponding leave-all procedures.
48206 **
48207 ** Enter the mutexes in accending order by BtShared pointer address
48208 ** to avoid the possibility of deadlock when two threads with
48209 ** two or more btrees in common both try to lock all their btrees
48210 ** at the same instant.
48211 */
48212 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48213   int i;
48214   Btree *p;
48215   assert( sqlite3_mutex_held(db->mutex) );
48216   for(i=0; i<db->nDb; i++){
48217     p = db->aDb[i].pBt;
48218     if( p ) sqlite3BtreeEnter(p);
48219   }
48220 }
48221 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
48222   int i;
48223   Btree *p;
48224   assert( sqlite3_mutex_held(db->mutex) );
48225   for(i=0; i<db->nDb; i++){
48226     p = db->aDb[i].pBt;
48227     if( p ) sqlite3BtreeLeave(p);
48228   }
48229 }
48230
48231 /*
48232 ** Return true if a particular Btree requires a lock.  Return FALSE if
48233 ** no lock is ever required since it is not sharable.
48234 */
48235 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
48236   return p->sharable;
48237 }
48238
48239 #ifndef NDEBUG
48240 /*
48241 ** Return true if the current thread holds the database connection
48242 ** mutex and all required BtShared mutexes.
48243 **
48244 ** This routine is used inside assert() statements only.
48245 */
48246 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
48247   int i;
48248   if( !sqlite3_mutex_held(db->mutex) ){
48249     return 0;
48250   }
48251   for(i=0; i<db->nDb; i++){
48252     Btree *p;
48253     p = db->aDb[i].pBt;
48254     if( p && p->sharable &&
48255          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
48256       return 0;
48257     }
48258   }
48259   return 1;
48260 }
48261 #endif /* NDEBUG */
48262
48263 #ifndef NDEBUG
48264 /*
48265 ** Return true if the correct mutexes are held for accessing the
48266 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
48267 ** access are:
48268 **
48269 **   (1) The mutex on db
48270 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
48271 **
48272 ** If pSchema is not NULL, then iDb is computed from pSchema and
48273 ** db using sqlite3SchemaToIndex().
48274 */
48275 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
48276   Btree *p;
48277   assert( db!=0 );
48278   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
48279   assert( iDb>=0 && iDb<db->nDb );
48280   if( !sqlite3_mutex_held(db->mutex) ) return 0;
48281   if( iDb==1 ) return 1;
48282   p = db->aDb[iDb].pBt;
48283   assert( p!=0 );
48284   return p->sharable==0 || p->locked==1;
48285 }
48286 #endif /* NDEBUG */
48287
48288 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
48289 /*
48290 ** The following are special cases for mutex enter routines for use
48291 ** in single threaded applications that use shared cache.  Except for
48292 ** these two routines, all mutex operations are no-ops in that case and
48293 ** are null #defines in btree.h.
48294 **
48295 ** If shared cache is disabled, then all btree mutex routines, including
48296 ** the ones below, are no-ops and are null #defines in btree.h.
48297 */
48298
48299 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48300   p->pBt->db = p->db;
48301 }
48302 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48303   int i;
48304   for(i=0; i<db->nDb; i++){
48305     Btree *p = db->aDb[i].pBt;
48306     if( p ){
48307       p->pBt->db = p->db;
48308     }
48309   }
48310 }
48311 #endif /* if SQLITE_THREADSAFE */
48312 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
48313
48314 /************** End of btmutex.c *********************************************/
48315 /************** Begin file btree.c *******************************************/
48316 /*
48317 ** 2004 April 6
48318 **
48319 ** The author disclaims copyright to this source code.  In place of
48320 ** a legal notice, here is a blessing:
48321 **
48322 **    May you do good and not evil.
48323 **    May you find forgiveness for yourself and forgive others.
48324 **    May you share freely, never taking more than you give.
48325 **
48326 *************************************************************************
48327 ** This file implements a external (disk-based) database using BTrees.
48328 ** See the header comment on "btreeInt.h" for additional information.
48329 ** Including a description of file format and an overview of operation.
48330 */
48331
48332 /*
48333 ** The header string that appears at the beginning of every
48334 ** SQLite database.
48335 */
48336 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
48337
48338 /*
48339 ** Set this global variable to 1 to enable tracing using the TRACE
48340 ** macro.
48341 */
48342 #if 0
48343 int sqlite3BtreeTrace=1;  /* True to enable tracing */
48344 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
48345 #else
48346 # define TRACE(X)
48347 #endif
48348
48349 /*
48350 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
48351 ** But if the value is zero, make it 65536.
48352 **
48353 ** This routine is used to extract the "offset to cell content area" value
48354 ** from the header of a btree page.  If the page size is 65536 and the page
48355 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
48356 ** This routine makes the necessary adjustment to 65536.
48357 */
48358 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
48359
48360 #ifndef SQLITE_OMIT_SHARED_CACHE
48361 /*
48362 ** A list of BtShared objects that are eligible for participation
48363 ** in shared cache.  This variable has file scope during normal builds,
48364 ** but the test harness needs to access it so we make it global for 
48365 ** test builds.
48366 **
48367 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
48368 */
48369 #ifdef SQLITE_TEST
48370 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48371 #else
48372 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48373 #endif
48374 #endif /* SQLITE_OMIT_SHARED_CACHE */
48375
48376 #ifndef SQLITE_OMIT_SHARED_CACHE
48377 /*
48378 ** Enable or disable the shared pager and schema features.
48379 **
48380 ** This routine has no effect on existing database connections.
48381 ** The shared cache setting effects only future calls to
48382 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
48383 */
48384 SQLITE_API int sqlite3_enable_shared_cache(int enable){
48385   sqlite3GlobalConfig.sharedCacheEnabled = enable;
48386   return SQLITE_OK;
48387 }
48388 #endif
48389
48390
48391
48392 #ifdef SQLITE_OMIT_SHARED_CACHE
48393   /*
48394   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48395   ** and clearAllSharedCacheTableLocks()
48396   ** manipulate entries in the BtShared.pLock linked list used to store
48397   ** shared-cache table level locks. If the library is compiled with the
48398   ** shared-cache feature disabled, then there is only ever one user
48399   ** of each BtShared structure and so this locking is not necessary. 
48400   ** So define the lock related functions as no-ops.
48401   */
48402   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48403   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48404   #define clearAllSharedCacheTableLocks(a)
48405   #define downgradeAllSharedCacheTableLocks(a)
48406   #define hasSharedCacheTableLock(a,b,c,d) 1
48407   #define hasReadConflicts(a, b) 0
48408 #endif
48409
48410 #ifndef SQLITE_OMIT_SHARED_CACHE
48411
48412 #ifdef SQLITE_DEBUG
48413 /*
48414 **** This function is only used as part of an assert() statement. ***
48415 **
48416 ** Check to see if pBtree holds the required locks to read or write to the 
48417 ** table with root page iRoot.   Return 1 if it does and 0 if not.
48418 **
48419 ** For example, when writing to a table with root-page iRoot via 
48420 ** Btree connection pBtree:
48421 **
48422 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48423 **
48424 ** When writing to an index that resides in a sharable database, the 
48425 ** caller should have first obtained a lock specifying the root page of
48426 ** the corresponding table. This makes things a bit more complicated,
48427 ** as this module treats each table as a separate structure. To determine
48428 ** the table corresponding to the index being written, this
48429 ** function has to search through the database schema.
48430 **
48431 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48432 ** hold a write-lock on the schema table (root page 1). This is also
48433 ** acceptable.
48434 */
48435 static int hasSharedCacheTableLock(
48436   Btree *pBtree,         /* Handle that must hold lock */
48437   Pgno iRoot,            /* Root page of b-tree */
48438   int isIndex,           /* True if iRoot is the root of an index b-tree */
48439   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
48440 ){
48441   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48442   Pgno iTab = 0;
48443   BtLock *pLock;
48444
48445   /* If this database is not shareable, or if the client is reading
48446   ** and has the read-uncommitted flag set, then no lock is required. 
48447   ** Return true immediately.
48448   */
48449   if( (pBtree->sharable==0)
48450    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48451   ){
48452     return 1;
48453   }
48454
48455   /* If the client is reading  or writing an index and the schema is
48456   ** not loaded, then it is too difficult to actually check to see if
48457   ** the correct locks are held.  So do not bother - just return true.
48458   ** This case does not come up very often anyhow.
48459   */
48460   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48461     return 1;
48462   }
48463
48464   /* Figure out the root-page that the lock should be held on. For table
48465   ** b-trees, this is just the root page of the b-tree being read or
48466   ** written. For index b-trees, it is the root page of the associated
48467   ** table.  */
48468   if( isIndex ){
48469     HashElem *p;
48470     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48471       Index *pIdx = (Index *)sqliteHashData(p);
48472       if( pIdx->tnum==(int)iRoot ){
48473         iTab = pIdx->pTable->tnum;
48474       }
48475     }
48476   }else{
48477     iTab = iRoot;
48478   }
48479
48480   /* Search for the required lock. Either a write-lock on root-page iTab, a 
48481   ** write-lock on the schema table, or (if the client is reading) a
48482   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
48483   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48484     if( pLock->pBtree==pBtree 
48485      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48486      && pLock->eLock>=eLockType 
48487     ){
48488       return 1;
48489     }
48490   }
48491
48492   /* Failed to find the required lock. */
48493   return 0;
48494 }
48495 #endif /* SQLITE_DEBUG */
48496
48497 #ifdef SQLITE_DEBUG
48498 /*
48499 **** This function may be used as part of assert() statements only. ****
48500 **
48501 ** Return true if it would be illegal for pBtree to write into the
48502 ** table or index rooted at iRoot because other shared connections are
48503 ** simultaneously reading that same table or index.
48504 **
48505 ** It is illegal for pBtree to write if some other Btree object that
48506 ** shares the same BtShared object is currently reading or writing
48507 ** the iRoot table.  Except, if the other Btree object has the
48508 ** read-uncommitted flag set, then it is OK for the other object to
48509 ** have a read cursor.
48510 **
48511 ** For example, before writing to any part of the table or index
48512 ** rooted at page iRoot, one should call:
48513 **
48514 **    assert( !hasReadConflicts(pBtree, iRoot) );
48515 */
48516 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48517   BtCursor *p;
48518   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48519     if( p->pgnoRoot==iRoot 
48520      && p->pBtree!=pBtree
48521      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48522     ){
48523       return 1;
48524     }
48525   }
48526   return 0;
48527 }
48528 #endif    /* #ifdef SQLITE_DEBUG */
48529
48530 /*
48531 ** Query to see if Btree handle p may obtain a lock of type eLock 
48532 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48533 ** SQLITE_OK if the lock may be obtained (by calling
48534 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48535 */
48536 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48537   BtShared *pBt = p->pBt;
48538   BtLock *pIter;
48539
48540   assert( sqlite3BtreeHoldsMutex(p) );
48541   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48542   assert( p->db!=0 );
48543   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48544   
48545   /* If requesting a write-lock, then the Btree must have an open write
48546   ** transaction on this file. And, obviously, for this to be so there 
48547   ** must be an open write transaction on the file itself.
48548   */
48549   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48550   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48551   
48552   /* This routine is a no-op if the shared-cache is not enabled */
48553   if( !p->sharable ){
48554     return SQLITE_OK;
48555   }
48556
48557   /* If some other connection is holding an exclusive lock, the
48558   ** requested lock may not be obtained.
48559   */
48560   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
48561     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48562     return SQLITE_LOCKED_SHAREDCACHE;
48563   }
48564
48565   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48566     /* The condition (pIter->eLock!=eLock) in the following if(...) 
48567     ** statement is a simplification of:
48568     **
48569     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48570     **
48571     ** since we know that if eLock==WRITE_LOCK, then no other connection
48572     ** may hold a WRITE_LOCK on any table in this file (since there can
48573     ** only be a single writer).
48574     */
48575     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48576     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48577     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48578       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48579       if( eLock==WRITE_LOCK ){
48580         assert( p==pBt->pWriter );
48581         pBt->btsFlags |= BTS_PENDING;
48582       }
48583       return SQLITE_LOCKED_SHAREDCACHE;
48584     }
48585   }
48586   return SQLITE_OK;
48587 }
48588 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48589
48590 #ifndef SQLITE_OMIT_SHARED_CACHE
48591 /*
48592 ** Add a lock on the table with root-page iTable to the shared-btree used
48593 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
48594 ** WRITE_LOCK.
48595 **
48596 ** This function assumes the following:
48597 **
48598 **   (a) The specified Btree object p is connected to a sharable
48599 **       database (one with the BtShared.sharable flag set), and
48600 **
48601 **   (b) No other Btree objects hold a lock that conflicts
48602 **       with the requested lock (i.e. querySharedCacheTableLock() has
48603 **       already been called and returned SQLITE_OK).
48604 **
48605 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
48606 ** is returned if a malloc attempt fails.
48607 */
48608 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48609   BtShared *pBt = p->pBt;
48610   BtLock *pLock = 0;
48611   BtLock *pIter;
48612
48613   assert( sqlite3BtreeHoldsMutex(p) );
48614   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48615   assert( p->db!=0 );
48616
48617   /* A connection with the read-uncommitted flag set will never try to
48618   ** obtain a read-lock using this function. The only read-lock obtained
48619   ** by a connection in read-uncommitted mode is on the sqlite_master 
48620   ** table, and that lock is obtained in BtreeBeginTrans().  */
48621   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48622
48623   /* This function should only be called on a sharable b-tree after it 
48624   ** has been determined that no other b-tree holds a conflicting lock.  */
48625   assert( p->sharable );
48626   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48627
48628   /* First search the list for an existing lock on this table. */
48629   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48630     if( pIter->iTable==iTable && pIter->pBtree==p ){
48631       pLock = pIter;
48632       break;
48633     }
48634   }
48635
48636   /* If the above search did not find a BtLock struct associating Btree p
48637   ** with table iTable, allocate one and link it into the list.
48638   */
48639   if( !pLock ){
48640     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48641     if( !pLock ){
48642       return SQLITE_NOMEM;
48643     }
48644     pLock->iTable = iTable;
48645     pLock->pBtree = p;
48646     pLock->pNext = pBt->pLock;
48647     pBt->pLock = pLock;
48648   }
48649
48650   /* Set the BtLock.eLock variable to the maximum of the current lock
48651   ** and the requested lock. This means if a write-lock was already held
48652   ** and a read-lock requested, we don't incorrectly downgrade the lock.
48653   */
48654   assert( WRITE_LOCK>READ_LOCK );
48655   if( eLock>pLock->eLock ){
48656     pLock->eLock = eLock;
48657   }
48658
48659   return SQLITE_OK;
48660 }
48661 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48662
48663 #ifndef SQLITE_OMIT_SHARED_CACHE
48664 /*
48665 ** Release all the table locks (locks obtained via calls to
48666 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48667 **
48668 ** This function assumes that Btree p has an open read or write 
48669 ** transaction. If it does not, then the BTS_PENDING flag
48670 ** may be incorrectly cleared.
48671 */
48672 static void clearAllSharedCacheTableLocks(Btree *p){
48673   BtShared *pBt = p->pBt;
48674   BtLock **ppIter = &pBt->pLock;
48675
48676   assert( sqlite3BtreeHoldsMutex(p) );
48677   assert( p->sharable || 0==*ppIter );
48678   assert( p->inTrans>0 );
48679
48680   while( *ppIter ){
48681     BtLock *pLock = *ppIter;
48682     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
48683     assert( pLock->pBtree->inTrans>=pLock->eLock );
48684     if( pLock->pBtree==p ){
48685       *ppIter = pLock->pNext;
48686       assert( pLock->iTable!=1 || pLock==&p->lock );
48687       if( pLock->iTable!=1 ){
48688         sqlite3_free(pLock);
48689       }
48690     }else{
48691       ppIter = &pLock->pNext;
48692     }
48693   }
48694
48695   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
48696   if( pBt->pWriter==p ){
48697     pBt->pWriter = 0;
48698     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48699   }else if( pBt->nTransaction==2 ){
48700     /* This function is called when Btree p is concluding its 
48701     ** transaction. If there currently exists a writer, and p is not
48702     ** that writer, then the number of locks held by connections other
48703     ** than the writer must be about to drop to zero. In this case
48704     ** set the BTS_PENDING flag to 0.
48705     **
48706     ** If there is not currently a writer, then BTS_PENDING must
48707     ** be zero already. So this next line is harmless in that case.
48708     */
48709     pBt->btsFlags &= ~BTS_PENDING;
48710   }
48711 }
48712
48713 /*
48714 ** This function changes all write-locks held by Btree p into read-locks.
48715 */
48716 static void downgradeAllSharedCacheTableLocks(Btree *p){
48717   BtShared *pBt = p->pBt;
48718   if( pBt->pWriter==p ){
48719     BtLock *pLock;
48720     pBt->pWriter = 0;
48721     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48722     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48723       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48724       pLock->eLock = READ_LOCK;
48725     }
48726   }
48727 }
48728
48729 #endif /* SQLITE_OMIT_SHARED_CACHE */
48730
48731 static void releasePage(MemPage *pPage);  /* Forward reference */
48732
48733 /*
48734 ***** This routine is used inside of assert() only ****
48735 **
48736 ** Verify that the cursor holds the mutex on its BtShared
48737 */
48738 #ifdef SQLITE_DEBUG
48739 static int cursorHoldsMutex(BtCursor *p){
48740   return sqlite3_mutex_held(p->pBt->mutex);
48741 }
48742 #endif
48743
48744
48745 #ifndef SQLITE_OMIT_INCRBLOB
48746 /*
48747 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48748 */
48749 static void invalidateOverflowCache(BtCursor *pCur){
48750   assert( cursorHoldsMutex(pCur) );
48751   sqlite3_free(pCur->aOverflow);
48752   pCur->aOverflow = 0;
48753 }
48754
48755 /*
48756 ** Invalidate the overflow page-list cache for all cursors opened
48757 ** on the shared btree structure pBt.
48758 */
48759 static void invalidateAllOverflowCache(BtShared *pBt){
48760   BtCursor *p;
48761   assert( sqlite3_mutex_held(pBt->mutex) );
48762   for(p=pBt->pCursor; p; p=p->pNext){
48763     invalidateOverflowCache(p);
48764   }
48765 }
48766
48767 /*
48768 ** This function is called before modifying the contents of a table
48769 ** to invalidate any incrblob cursors that are open on the
48770 ** row or one of the rows being modified.
48771 **
48772 ** If argument isClearTable is true, then the entire contents of the
48773 ** table is about to be deleted. In this case invalidate all incrblob
48774 ** cursors open on any row within the table with root-page pgnoRoot.
48775 **
48776 ** Otherwise, if argument isClearTable is false, then the row with
48777 ** rowid iRow is being replaced or deleted. In this case invalidate
48778 ** only those incrblob cursors open on that specific row.
48779 */
48780 static void invalidateIncrblobCursors(
48781   Btree *pBtree,          /* The database file to check */
48782   i64 iRow,               /* The rowid that might be changing */
48783   int isClearTable        /* True if all rows are being deleted */
48784 ){
48785   BtCursor *p;
48786   BtShared *pBt = pBtree->pBt;
48787   assert( sqlite3BtreeHoldsMutex(pBtree) );
48788   for(p=pBt->pCursor; p; p=p->pNext){
48789     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48790       p->eState = CURSOR_INVALID;
48791     }
48792   }
48793 }
48794
48795 #else
48796   /* Stub functions when INCRBLOB is omitted */
48797   #define invalidateOverflowCache(x)
48798   #define invalidateAllOverflowCache(x)
48799   #define invalidateIncrblobCursors(x,y,z)
48800 #endif /* SQLITE_OMIT_INCRBLOB */
48801
48802 /*
48803 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
48804 ** when a page that previously contained data becomes a free-list leaf 
48805 ** page.
48806 **
48807 ** The BtShared.pHasContent bitvec exists to work around an obscure
48808 ** bug caused by the interaction of two useful IO optimizations surrounding
48809 ** free-list leaf pages:
48810 **
48811 **   1) When all data is deleted from a page and the page becomes
48812 **      a free-list leaf page, the page is not written to the database
48813 **      (as free-list leaf pages contain no meaningful data). Sometimes
48814 **      such a page is not even journalled (as it will not be modified,
48815 **      why bother journalling it?).
48816 **
48817 **   2) When a free-list leaf page is reused, its content is not read
48818 **      from the database or written to the journal file (why should it
48819 **      be, if it is not at all meaningful?).
48820 **
48821 ** By themselves, these optimizations work fine and provide a handy
48822 ** performance boost to bulk delete or insert operations. However, if
48823 ** a page is moved to the free-list and then reused within the same
48824 ** transaction, a problem comes up. If the page is not journalled when
48825 ** it is moved to the free-list and it is also not journalled when it
48826 ** is extracted from the free-list and reused, then the original data
48827 ** may be lost. In the event of a rollback, it may not be possible
48828 ** to restore the database to its original configuration.
48829 **
48830 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
48831 ** moved to become a free-list leaf page, the corresponding bit is
48832 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48833 ** optimization 2 above is omitted if the corresponding bit is already
48834 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48835 ** at the end of every transaction.
48836 */
48837 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48838   int rc = SQLITE_OK;
48839   if( !pBt->pHasContent ){
48840     assert( pgno<=pBt->nPage );
48841     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48842     if( !pBt->pHasContent ){
48843       rc = SQLITE_NOMEM;
48844     }
48845   }
48846   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48847     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48848   }
48849   return rc;
48850 }
48851
48852 /*
48853 ** Query the BtShared.pHasContent vector.
48854 **
48855 ** This function is called when a free-list leaf page is removed from the
48856 ** free-list for reuse. It returns false if it is safe to retrieve the
48857 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48858 */
48859 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48860   Bitvec *p = pBt->pHasContent;
48861   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48862 }
48863
48864 /*
48865 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48866 ** invoked at the conclusion of each write-transaction.
48867 */
48868 static void btreeClearHasContent(BtShared *pBt){
48869   sqlite3BitvecDestroy(pBt->pHasContent);
48870   pBt->pHasContent = 0;
48871 }
48872
48873 /*
48874 ** Save the current cursor position in the variables BtCursor.nKey 
48875 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48876 **
48877 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48878 ** prior to calling this routine.  
48879 */
48880 static int saveCursorPosition(BtCursor *pCur){
48881   int rc;
48882
48883   assert( CURSOR_VALID==pCur->eState );
48884   assert( 0==pCur->pKey );
48885   assert( cursorHoldsMutex(pCur) );
48886
48887   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48888   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48889
48890   /* If this is an intKey table, then the above call to BtreeKeySize()
48891   ** stores the integer key in pCur->nKey. In this case this value is
48892   ** all that is required. Otherwise, if pCur is not open on an intKey
48893   ** table, then malloc space for and store the pCur->nKey bytes of key 
48894   ** data.
48895   */
48896   if( 0==pCur->apPage[0]->intKey ){
48897     void *pKey = sqlite3Malloc( (int)pCur->nKey );
48898     if( pKey ){
48899       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48900       if( rc==SQLITE_OK ){
48901         pCur->pKey = pKey;
48902       }else{
48903         sqlite3_free(pKey);
48904       }
48905     }else{
48906       rc = SQLITE_NOMEM;
48907     }
48908   }
48909   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
48910
48911   if( rc==SQLITE_OK ){
48912     int i;
48913     for(i=0; i<=pCur->iPage; i++){
48914       releasePage(pCur->apPage[i]);
48915       pCur->apPage[i] = 0;
48916     }
48917     pCur->iPage = -1;
48918     pCur->eState = CURSOR_REQUIRESEEK;
48919   }
48920
48921   invalidateOverflowCache(pCur);
48922   return rc;
48923 }
48924
48925 /*
48926 ** Save the positions of all cursors (except pExcept) that are open on
48927 ** the table  with root-page iRoot. Usually, this is called just before cursor
48928 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
48929 */
48930 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
48931   BtCursor *p;
48932   assert( sqlite3_mutex_held(pBt->mutex) );
48933   assert( pExcept==0 || pExcept->pBt==pBt );
48934   for(p=pBt->pCursor; p; p=p->pNext){
48935     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
48936         p->eState==CURSOR_VALID ){
48937       int rc = saveCursorPosition(p);
48938       if( SQLITE_OK!=rc ){
48939         return rc;
48940       }
48941     }
48942   }
48943   return SQLITE_OK;
48944 }
48945
48946 /*
48947 ** Clear the current cursor position.
48948 */
48949 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
48950   assert( cursorHoldsMutex(pCur) );
48951   sqlite3_free(pCur->pKey);
48952   pCur->pKey = 0;
48953   pCur->eState = CURSOR_INVALID;
48954 }
48955
48956 /*
48957 ** In this version of BtreeMoveto, pKey is a packed index record
48958 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
48959 ** record and then call BtreeMovetoUnpacked() to do the work.
48960 */
48961 static int btreeMoveto(
48962   BtCursor *pCur,     /* Cursor open on the btree to be searched */
48963   const void *pKey,   /* Packed key if the btree is an index */
48964   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
48965   int bias,           /* Bias search to the high end */
48966   int *pRes           /* Write search results here */
48967 ){
48968   int rc;                    /* Status code */
48969   UnpackedRecord *pIdxKey;   /* Unpacked index key */
48970   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
48971   char *pFree = 0;
48972
48973   if( pKey ){
48974     assert( nKey==(i64)(int)nKey );
48975     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
48976         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
48977     );
48978     if( pIdxKey==0 ) return SQLITE_NOMEM;
48979     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
48980   }else{
48981     pIdxKey = 0;
48982   }
48983   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
48984   if( pFree ){
48985     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
48986   }
48987   return rc;
48988 }
48989
48990 /*
48991 ** Restore the cursor to the position it was in (or as close to as possible)
48992 ** when saveCursorPosition() was called. Note that this call deletes the 
48993 ** saved position info stored by saveCursorPosition(), so there can be
48994 ** at most one effective restoreCursorPosition() call after each 
48995 ** saveCursorPosition().
48996 */
48997 static int btreeRestoreCursorPosition(BtCursor *pCur){
48998   int rc;
48999   assert( cursorHoldsMutex(pCur) );
49000   assert( pCur->eState>=CURSOR_REQUIRESEEK );
49001   if( pCur->eState==CURSOR_FAULT ){
49002     return pCur->skipNext;
49003   }
49004   pCur->eState = CURSOR_INVALID;
49005   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
49006   if( rc==SQLITE_OK ){
49007     sqlite3_free(pCur->pKey);
49008     pCur->pKey = 0;
49009     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
49010   }
49011   return rc;
49012 }
49013
49014 #define restoreCursorPosition(p) \
49015   (p->eState>=CURSOR_REQUIRESEEK ? \
49016          btreeRestoreCursorPosition(p) : \
49017          SQLITE_OK)
49018
49019 /*
49020 ** Determine whether or not a cursor has moved from the position it
49021 ** was last placed at.  Cursors can move when the row they are pointing
49022 ** at is deleted out from under them.
49023 **
49024 ** This routine returns an error code if something goes wrong.  The
49025 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
49026 */
49027 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
49028   int rc;
49029
49030   rc = restoreCursorPosition(pCur);
49031   if( rc ){
49032     *pHasMoved = 1;
49033     return rc;
49034   }
49035   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
49036     *pHasMoved = 1;
49037   }else{
49038     *pHasMoved = 0;
49039   }
49040   return SQLITE_OK;
49041 }
49042
49043 #ifndef SQLITE_OMIT_AUTOVACUUM
49044 /*
49045 ** Given a page number of a regular database page, return the page
49046 ** number for the pointer-map page that contains the entry for the
49047 ** input page number.
49048 **
49049 ** Return 0 (not a valid page) for pgno==1 since there is
49050 ** no pointer map associated with page 1.  The integrity_check logic
49051 ** requires that ptrmapPageno(*,1)!=1.
49052 */
49053 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
49054   int nPagesPerMapPage;
49055   Pgno iPtrMap, ret;
49056   assert( sqlite3_mutex_held(pBt->mutex) );
49057   if( pgno<2 ) return 0;
49058   nPagesPerMapPage = (pBt->usableSize/5)+1;
49059   iPtrMap = (pgno-2)/nPagesPerMapPage;
49060   ret = (iPtrMap*nPagesPerMapPage) + 2; 
49061   if( ret==PENDING_BYTE_PAGE(pBt) ){
49062     ret++;
49063   }
49064   return ret;
49065 }
49066
49067 /*
49068 ** Write an entry into the pointer map.
49069 **
49070 ** This routine updates the pointer map entry for page number 'key'
49071 ** so that it maps to type 'eType' and parent page number 'pgno'.
49072 **
49073 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
49074 ** a no-op.  If an error occurs, the appropriate error code is written
49075 ** into *pRC.
49076 */
49077 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
49078   DbPage *pDbPage;  /* The pointer map page */
49079   u8 *pPtrmap;      /* The pointer map data */
49080   Pgno iPtrmap;     /* The pointer map page number */
49081   int offset;       /* Offset in pointer map page */
49082   int rc;           /* Return code from subfunctions */
49083
49084   if( *pRC ) return;
49085
49086   assert( sqlite3_mutex_held(pBt->mutex) );
49087   /* The master-journal page number must never be used as a pointer map page */
49088   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
49089
49090   assert( pBt->autoVacuum );
49091   if( key==0 ){
49092     *pRC = SQLITE_CORRUPT_BKPT;
49093     return;
49094   }
49095   iPtrmap = PTRMAP_PAGENO(pBt, key);
49096   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49097   if( rc!=SQLITE_OK ){
49098     *pRC = rc;
49099     return;
49100   }
49101   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49102   if( offset<0 ){
49103     *pRC = SQLITE_CORRUPT_BKPT;
49104     goto ptrmap_exit;
49105   }
49106   assert( offset <= (int)pBt->usableSize-5 );
49107   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49108
49109   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
49110     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
49111     *pRC= rc = sqlite3PagerWrite(pDbPage);
49112     if( rc==SQLITE_OK ){
49113       pPtrmap[offset] = eType;
49114       put4byte(&pPtrmap[offset+1], parent);
49115     }
49116   }
49117
49118 ptrmap_exit:
49119   sqlite3PagerUnref(pDbPage);
49120 }
49121
49122 /*
49123 ** Read an entry from the pointer map.
49124 **
49125 ** This routine retrieves the pointer map entry for page 'key', writing
49126 ** the type and parent page number to *pEType and *pPgno respectively.
49127 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
49128 */
49129 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
49130   DbPage *pDbPage;   /* The pointer map page */
49131   int iPtrmap;       /* Pointer map page index */
49132   u8 *pPtrmap;       /* Pointer map page data */
49133   int offset;        /* Offset of entry in pointer map */
49134   int rc;
49135
49136   assert( sqlite3_mutex_held(pBt->mutex) );
49137
49138   iPtrmap = PTRMAP_PAGENO(pBt, key);
49139   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49140   if( rc!=0 ){
49141     return rc;
49142   }
49143   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49144
49145   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49146   if( offset<0 ){
49147     sqlite3PagerUnref(pDbPage);
49148     return SQLITE_CORRUPT_BKPT;
49149   }
49150   assert( offset <= (int)pBt->usableSize-5 );
49151   assert( pEType!=0 );
49152   *pEType = pPtrmap[offset];
49153   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
49154
49155   sqlite3PagerUnref(pDbPage);
49156   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
49157   return SQLITE_OK;
49158 }
49159
49160 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
49161   #define ptrmapPut(w,x,y,z,rc)
49162   #define ptrmapGet(w,x,y,z) SQLITE_OK
49163   #define ptrmapPutOvflPtr(x, y, rc)
49164 #endif
49165
49166 /*
49167 ** Given a btree page and a cell index (0 means the first cell on
49168 ** the page, 1 means the second cell, and so forth) return a pointer
49169 ** to the cell content.
49170 **
49171 ** This routine works only for pages that do not contain overflow cells.
49172 */
49173 #define findCell(P,I) \
49174   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
49175 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
49176
49177
49178 /*
49179 ** This a more complex version of findCell() that works for
49180 ** pages that do contain overflow cells.
49181 */
49182 static u8 *findOverflowCell(MemPage *pPage, int iCell){
49183   int i;
49184   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49185   for(i=pPage->nOverflow-1; i>=0; i--){
49186     int k;
49187     k = pPage->aiOvfl[i];
49188     if( k<=iCell ){
49189       if( k==iCell ){
49190         return pPage->apOvfl[i];
49191       }
49192       iCell--;
49193     }
49194   }
49195   return findCell(pPage, iCell);
49196 }
49197
49198 /*
49199 ** Parse a cell content block and fill in the CellInfo structure.  There
49200 ** are two versions of this function.  btreeParseCell() takes a 
49201 ** cell index as the second argument and btreeParseCellPtr() 
49202 ** takes a pointer to the body of the cell as its second argument.
49203 **
49204 ** Within this file, the parseCell() macro can be called instead of
49205 ** btreeParseCellPtr(). Using some compilers, this will be faster.
49206 */
49207 static void btreeParseCellPtr(
49208   MemPage *pPage,         /* Page containing the cell */
49209   u8 *pCell,              /* Pointer to the cell text. */
49210   CellInfo *pInfo         /* Fill in this structure */
49211 ){
49212   u16 n;                  /* Number bytes in cell content header */
49213   u32 nPayload;           /* Number of bytes of cell payload */
49214
49215   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49216
49217   pInfo->pCell = pCell;
49218   assert( pPage->leaf==0 || pPage->leaf==1 );
49219   n = pPage->childPtrSize;
49220   assert( n==4-4*pPage->leaf );
49221   if( pPage->intKey ){
49222     if( pPage->hasData ){
49223       n += getVarint32(&pCell[n], nPayload);
49224     }else{
49225       nPayload = 0;
49226     }
49227     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
49228     pInfo->nData = nPayload;
49229   }else{
49230     pInfo->nData = 0;
49231     n += getVarint32(&pCell[n], nPayload);
49232     pInfo->nKey = nPayload;
49233   }
49234   pInfo->nPayload = nPayload;
49235   pInfo->nHeader = n;
49236   testcase( nPayload==pPage->maxLocal );
49237   testcase( nPayload==pPage->maxLocal+1 );
49238   if( likely(nPayload<=pPage->maxLocal) ){
49239     /* This is the (easy) common case where the entire payload fits
49240     ** on the local page.  No overflow is required.
49241     */
49242     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
49243     pInfo->nLocal = (u16)nPayload;
49244     pInfo->iOverflow = 0;
49245   }else{
49246     /* If the payload will not fit completely on the local page, we have
49247     ** to decide how much to store locally and how much to spill onto
49248     ** overflow pages.  The strategy is to minimize the amount of unused
49249     ** space on overflow pages while keeping the amount of local storage
49250     ** in between minLocal and maxLocal.
49251     **
49252     ** Warning:  changing the way overflow payload is distributed in any
49253     ** way will result in an incompatible file format.
49254     */
49255     int minLocal;  /* Minimum amount of payload held locally */
49256     int maxLocal;  /* Maximum amount of payload held locally */
49257     int surplus;   /* Overflow payload available for local storage */
49258
49259     minLocal = pPage->minLocal;
49260     maxLocal = pPage->maxLocal;
49261     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
49262     testcase( surplus==maxLocal );
49263     testcase( surplus==maxLocal+1 );
49264     if( surplus <= maxLocal ){
49265       pInfo->nLocal = (u16)surplus;
49266     }else{
49267       pInfo->nLocal = (u16)minLocal;
49268     }
49269     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
49270     pInfo->nSize = pInfo->iOverflow + 4;
49271   }
49272 }
49273 #define parseCell(pPage, iCell, pInfo) \
49274   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
49275 static void btreeParseCell(
49276   MemPage *pPage,         /* Page containing the cell */
49277   int iCell,              /* The cell index.  First cell is 0 */
49278   CellInfo *pInfo         /* Fill in this structure */
49279 ){
49280   parseCell(pPage, iCell, pInfo);
49281 }
49282
49283 /*
49284 ** Compute the total number of bytes that a Cell needs in the cell
49285 ** data area of the btree-page.  The return number includes the cell
49286 ** data header and the local payload, but not any overflow page or
49287 ** the space used by the cell pointer.
49288 */
49289 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
49290   u8 *pIter = &pCell[pPage->childPtrSize];
49291   u32 nSize;
49292
49293 #ifdef SQLITE_DEBUG
49294   /* The value returned by this function should always be the same as
49295   ** the (CellInfo.nSize) value found by doing a full parse of the
49296   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
49297   ** this function verifies that this invariant is not violated. */
49298   CellInfo debuginfo;
49299   btreeParseCellPtr(pPage, pCell, &debuginfo);
49300 #endif
49301
49302   if( pPage->intKey ){
49303     u8 *pEnd;
49304     if( pPage->hasData ){
49305       pIter += getVarint32(pIter, nSize);
49306     }else{
49307       nSize = 0;
49308     }
49309
49310     /* pIter now points at the 64-bit integer key value, a variable length 
49311     ** integer. The following block moves pIter to point at the first byte
49312     ** past the end of the key value. */
49313     pEnd = &pIter[9];
49314     while( (*pIter++)&0x80 && pIter<pEnd );
49315   }else{
49316     pIter += getVarint32(pIter, nSize);
49317   }
49318
49319   testcase( nSize==pPage->maxLocal );
49320   testcase( nSize==pPage->maxLocal+1 );
49321   if( nSize>pPage->maxLocal ){
49322     int minLocal = pPage->minLocal;
49323     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
49324     testcase( nSize==pPage->maxLocal );
49325     testcase( nSize==pPage->maxLocal+1 );
49326     if( nSize>pPage->maxLocal ){
49327       nSize = minLocal;
49328     }
49329     nSize += 4;
49330   }
49331   nSize += (u32)(pIter - pCell);
49332
49333   /* The minimum size of any cell is 4 bytes. */
49334   if( nSize<4 ){
49335     nSize = 4;
49336   }
49337
49338   assert( nSize==debuginfo.nSize );
49339   return (u16)nSize;
49340 }
49341
49342 #ifdef SQLITE_DEBUG
49343 /* This variation on cellSizePtr() is used inside of assert() statements
49344 ** only. */
49345 static u16 cellSize(MemPage *pPage, int iCell){
49346   return cellSizePtr(pPage, findCell(pPage, iCell));
49347 }
49348 #endif
49349
49350 #ifndef SQLITE_OMIT_AUTOVACUUM
49351 /*
49352 ** If the cell pCell, part of page pPage contains a pointer
49353 ** to an overflow page, insert an entry into the pointer-map
49354 ** for the overflow page.
49355 */
49356 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
49357   CellInfo info;
49358   if( *pRC ) return;
49359   assert( pCell!=0 );
49360   btreeParseCellPtr(pPage, pCell, &info);
49361   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
49362   if( info.iOverflow ){
49363     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
49364     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
49365   }
49366 }
49367 #endif
49368
49369
49370 /*
49371 ** Defragment the page given.  All Cells are moved to the
49372 ** end of the page and all free space is collected into one
49373 ** big FreeBlk that occurs in between the header and cell
49374 ** pointer array and the cell content area.
49375 */
49376 static int defragmentPage(MemPage *pPage){
49377   int i;                     /* Loop counter */
49378   int pc;                    /* Address of a i-th cell */
49379   int hdr;                   /* Offset to the page header */
49380   int size;                  /* Size of a cell */
49381   int usableSize;            /* Number of usable bytes on a page */
49382   int cellOffset;            /* Offset to the cell pointer array */
49383   int cbrk;                  /* Offset to the cell content area */
49384   int nCell;                 /* Number of cells on the page */
49385   unsigned char *data;       /* The page data */
49386   unsigned char *temp;       /* Temp area for cell content */
49387   int iCellFirst;            /* First allowable cell index */
49388   int iCellLast;             /* Last possible cell index */
49389
49390
49391   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49392   assert( pPage->pBt!=0 );
49393   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49394   assert( pPage->nOverflow==0 );
49395   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49396   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49397   data = pPage->aData;
49398   hdr = pPage->hdrOffset;
49399   cellOffset = pPage->cellOffset;
49400   nCell = pPage->nCell;
49401   assert( nCell==get2byte(&data[hdr+3]) );
49402   usableSize = pPage->pBt->usableSize;
49403   cbrk = get2byte(&data[hdr+5]);
49404   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49405   cbrk = usableSize;
49406   iCellFirst = cellOffset + 2*nCell;
49407   iCellLast = usableSize - 4;
49408   for(i=0; i<nCell; i++){
49409     u8 *pAddr;     /* The i-th cell pointer */
49410     pAddr = &data[cellOffset + i*2];
49411     pc = get2byte(pAddr);
49412     testcase( pc==iCellFirst );
49413     testcase( pc==iCellLast );
49414 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49415     /* These conditions have already been verified in btreeInitPage()
49416     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
49417     */
49418     if( pc<iCellFirst || pc>iCellLast ){
49419       return SQLITE_CORRUPT_BKPT;
49420     }
49421 #endif
49422     assert( pc>=iCellFirst && pc<=iCellLast );
49423     size = cellSizePtr(pPage, &temp[pc]);
49424     cbrk -= size;
49425 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49426     if( cbrk<iCellFirst ){
49427       return SQLITE_CORRUPT_BKPT;
49428     }
49429 #else
49430     if( cbrk<iCellFirst || pc+size>usableSize ){
49431       return SQLITE_CORRUPT_BKPT;
49432     }
49433 #endif
49434     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49435     testcase( cbrk+size==usableSize );
49436     testcase( pc+size==usableSize );
49437     memcpy(&data[cbrk], &temp[pc], size);
49438     put2byte(pAddr, cbrk);
49439   }
49440   assert( cbrk>=iCellFirst );
49441   put2byte(&data[hdr+5], cbrk);
49442   data[hdr+1] = 0;
49443   data[hdr+2] = 0;
49444   data[hdr+7] = 0;
49445   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49446   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49447   if( cbrk-iCellFirst!=pPage->nFree ){
49448     return SQLITE_CORRUPT_BKPT;
49449   }
49450   return SQLITE_OK;
49451 }
49452
49453 /*
49454 ** Allocate nByte bytes of space from within the B-Tree page passed
49455 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49456 ** of the first byte of allocated space. Return either SQLITE_OK or
49457 ** an error code (usually SQLITE_CORRUPT).
49458 **
49459 ** The caller guarantees that there is sufficient space to make the
49460 ** allocation.  This routine might need to defragment in order to bring
49461 ** all the space together, however.  This routine will avoid using
49462 ** the first two bytes past the cell pointer area since presumably this
49463 ** allocation is being made in order to insert a new cell, so we will
49464 ** also end up needing a new cell pointer.
49465 */
49466 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49467   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
49468   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
49469   int nFrag;                           /* Number of fragmented bytes on pPage */
49470   int top;                             /* First byte of cell content area */
49471   int gap;        /* First byte of gap between cell pointers and cell content */
49472   int rc;         /* Integer return code */
49473   int usableSize; /* Usable size of the page */
49474   
49475   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49476   assert( pPage->pBt );
49477   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49478   assert( nByte>=0 );  /* Minimum cell size is 4 */
49479   assert( pPage->nFree>=nByte );
49480   assert( pPage->nOverflow==0 );
49481   usableSize = pPage->pBt->usableSize;
49482   assert( nByte < usableSize-8 );
49483
49484   nFrag = data[hdr+7];
49485   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49486   gap = pPage->cellOffset + 2*pPage->nCell;
49487   top = get2byteNotZero(&data[hdr+5]);
49488   if( gap>top ) return SQLITE_CORRUPT_BKPT;
49489   testcase( gap+2==top );
49490   testcase( gap+1==top );
49491   testcase( gap==top );
49492
49493   if( nFrag>=60 ){
49494     /* Always defragment highly fragmented pages */
49495     rc = defragmentPage(pPage);
49496     if( rc ) return rc;
49497     top = get2byteNotZero(&data[hdr+5]);
49498   }else if( gap+2<=top ){
49499     /* Search the freelist looking for a free slot big enough to satisfy 
49500     ** the request. The allocation is made from the first free slot in 
49501     ** the list that is large enough to accomadate it.
49502     */
49503     int pc, addr;
49504     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49505       int size;            /* Size of the free slot */
49506       if( pc>usableSize-4 || pc<addr+4 ){
49507         return SQLITE_CORRUPT_BKPT;
49508       }
49509       size = get2byte(&data[pc+2]);
49510       if( size>=nByte ){
49511         int x = size - nByte;
49512         testcase( x==4 );
49513         testcase( x==3 );
49514         if( x<4 ){
49515           /* Remove the slot from the free-list. Update the number of
49516           ** fragmented bytes within the page. */
49517           memcpy(&data[addr], &data[pc], 2);
49518           data[hdr+7] = (u8)(nFrag + x);
49519         }else if( size+pc > usableSize ){
49520           return SQLITE_CORRUPT_BKPT;
49521         }else{
49522           /* The slot remains on the free-list. Reduce its size to account
49523           ** for the portion used by the new allocation. */
49524           put2byte(&data[pc+2], x);
49525         }
49526         *pIdx = pc + x;
49527         return SQLITE_OK;
49528       }
49529     }
49530   }
49531
49532   /* Check to make sure there is enough space in the gap to satisfy
49533   ** the allocation.  If not, defragment.
49534   */
49535   testcase( gap+2+nByte==top );
49536   if( gap+2+nByte>top ){
49537     rc = defragmentPage(pPage);
49538     if( rc ) return rc;
49539     top = get2byteNotZero(&data[hdr+5]);
49540     assert( gap+nByte<=top );
49541   }
49542
49543
49544   /* Allocate memory from the gap in between the cell pointer array
49545   ** and the cell content area.  The btreeInitPage() call has already
49546   ** validated the freelist.  Given that the freelist is valid, there
49547   ** is no way that the allocation can extend off the end of the page.
49548   ** The assert() below verifies the previous sentence.
49549   */
49550   top -= nByte;
49551   put2byte(&data[hdr+5], top);
49552   assert( top+nByte <= (int)pPage->pBt->usableSize );
49553   *pIdx = top;
49554   return SQLITE_OK;
49555 }
49556
49557 /*
49558 ** Return a section of the pPage->aData to the freelist.
49559 ** The first byte of the new free block is pPage->aDisk[start]
49560 ** and the size of the block is "size" bytes.
49561 **
49562 ** Most of the effort here is involved in coalesing adjacent
49563 ** free blocks into a single big free block.
49564 */
49565 static int freeSpace(MemPage *pPage, int start, int size){
49566   int addr, pbegin, hdr;
49567   int iLast;                        /* Largest possible freeblock offset */
49568   unsigned char *data = pPage->aData;
49569
49570   assert( pPage->pBt!=0 );
49571   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49572   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49573   assert( (start + size) <= (int)pPage->pBt->usableSize );
49574   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49575   assert( size>=0 );   /* Minimum cell size is 4 */
49576
49577   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
49578     /* Overwrite deleted information with zeros when the secure_delete
49579     ** option is enabled */
49580     memset(&data[start], 0, size);
49581   }
49582
49583   /* Add the space back into the linked list of freeblocks.  Note that
49584   ** even though the freeblock list was checked by btreeInitPage(),
49585   ** btreeInitPage() did not detect overlapping cells or
49586   ** freeblocks that overlapped cells.   Nor does it detect when the
49587   ** cell content area exceeds the value in the page header.  If these
49588   ** situations arise, then subsequent insert operations might corrupt
49589   ** the freelist.  So we do need to check for corruption while scanning
49590   ** the freelist.
49591   */
49592   hdr = pPage->hdrOffset;
49593   addr = hdr + 1;
49594   iLast = pPage->pBt->usableSize - 4;
49595   assert( start<=iLast );
49596   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49597     if( pbegin<addr+4 ){
49598       return SQLITE_CORRUPT_BKPT;
49599     }
49600     addr = pbegin;
49601   }
49602   if( pbegin>iLast ){
49603     return SQLITE_CORRUPT_BKPT;
49604   }
49605   assert( pbegin>addr || pbegin==0 );
49606   put2byte(&data[addr], start);
49607   put2byte(&data[start], pbegin);
49608   put2byte(&data[start+2], size);
49609   pPage->nFree = pPage->nFree + (u16)size;
49610
49611   /* Coalesce adjacent free blocks */
49612   addr = hdr + 1;
49613   while( (pbegin = get2byte(&data[addr]))>0 ){
49614     int pnext, psize, x;
49615     assert( pbegin>addr );
49616     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49617     pnext = get2byte(&data[pbegin]);
49618     psize = get2byte(&data[pbegin+2]);
49619     if( pbegin + psize + 3 >= pnext && pnext>0 ){
49620       int frag = pnext - (pbegin+psize);
49621       if( (frag<0) || (frag>(int)data[hdr+7]) ){
49622         return SQLITE_CORRUPT_BKPT;
49623       }
49624       data[hdr+7] -= (u8)frag;
49625       x = get2byte(&data[pnext]);
49626       put2byte(&data[pbegin], x);
49627       x = pnext + get2byte(&data[pnext+2]) - pbegin;
49628       put2byte(&data[pbegin+2], x);
49629     }else{
49630       addr = pbegin;
49631     }
49632   }
49633
49634   /* If the cell content area begins with a freeblock, remove it. */
49635   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49636     int top;
49637     pbegin = get2byte(&data[hdr+1]);
49638     memcpy(&data[hdr+1], &data[pbegin], 2);
49639     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49640     put2byte(&data[hdr+5], top);
49641   }
49642   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49643   return SQLITE_OK;
49644 }
49645
49646 /*
49647 ** Decode the flags byte (the first byte of the header) for a page
49648 ** and initialize fields of the MemPage structure accordingly.
49649 **
49650 ** Only the following combinations are supported.  Anything different
49651 ** indicates a corrupt database files:
49652 **
49653 **         PTF_ZERODATA
49654 **         PTF_ZERODATA | PTF_LEAF
49655 **         PTF_LEAFDATA | PTF_INTKEY
49656 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49657 */
49658 static int decodeFlags(MemPage *pPage, int flagByte){
49659   BtShared *pBt;     /* A copy of pPage->pBt */
49660
49661   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49662   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49663   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
49664   flagByte &= ~PTF_LEAF;
49665   pPage->childPtrSize = 4-4*pPage->leaf;
49666   pBt = pPage->pBt;
49667   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49668     pPage->intKey = 1;
49669     pPage->hasData = pPage->leaf;
49670     pPage->maxLocal = pBt->maxLeaf;
49671     pPage->minLocal = pBt->minLeaf;
49672   }else if( flagByte==PTF_ZERODATA ){
49673     pPage->intKey = 0;
49674     pPage->hasData = 0;
49675     pPage->maxLocal = pBt->maxLocal;
49676     pPage->minLocal = pBt->minLocal;
49677   }else{
49678     return SQLITE_CORRUPT_BKPT;
49679   }
49680   pPage->max1bytePayload = pBt->max1bytePayload;
49681   return SQLITE_OK;
49682 }
49683
49684 /*
49685 ** Initialize the auxiliary information for a disk block.
49686 **
49687 ** Return SQLITE_OK on success.  If we see that the page does
49688 ** not contain a well-formed database page, then return 
49689 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
49690 ** guarantee that the page is well-formed.  It only shows that
49691 ** we failed to detect any corruption.
49692 */
49693 static int btreeInitPage(MemPage *pPage){
49694
49695   assert( pPage->pBt!=0 );
49696   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49697   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49698   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49699   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49700
49701   if( !pPage->isInit ){
49702     u16 pc;            /* Address of a freeblock within pPage->aData[] */
49703     u8 hdr;            /* Offset to beginning of page header */
49704     u8 *data;          /* Equal to pPage->aData */
49705     BtShared *pBt;        /* The main btree structure */
49706     int usableSize;    /* Amount of usable space on each page */
49707     u16 cellOffset;    /* Offset from start of page to first cell pointer */
49708     int nFree;         /* Number of unused bytes on the page */
49709     int top;           /* First byte of the cell content area */
49710     int iCellFirst;    /* First allowable cell or freeblock offset */
49711     int iCellLast;     /* Last possible cell or freeblock offset */
49712
49713     pBt = pPage->pBt;
49714
49715     hdr = pPage->hdrOffset;
49716     data = pPage->aData;
49717     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49718     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49719     pPage->maskPage = (u16)(pBt->pageSize - 1);
49720     pPage->nOverflow = 0;
49721     usableSize = pBt->usableSize;
49722     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49723     pPage->aDataEnd = &data[usableSize];
49724     pPage->aCellIdx = &data[cellOffset];
49725     top = get2byteNotZero(&data[hdr+5]);
49726     pPage->nCell = get2byte(&data[hdr+3]);
49727     if( pPage->nCell>MX_CELL(pBt) ){
49728       /* To many cells for a single page.  The page must be corrupt */
49729       return SQLITE_CORRUPT_BKPT;
49730     }
49731     testcase( pPage->nCell==MX_CELL(pBt) );
49732
49733     /* A malformed database page might cause us to read past the end
49734     ** of page when parsing a cell.  
49735     **
49736     ** The following block of code checks early to see if a cell extends
49737     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
49738     ** returned if it does.
49739     */
49740     iCellFirst = cellOffset + 2*pPage->nCell;
49741     iCellLast = usableSize - 4;
49742 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49743     {
49744       int i;            /* Index into the cell pointer array */
49745       int sz;           /* Size of a cell */
49746
49747       if( !pPage->leaf ) iCellLast--;
49748       for(i=0; i<pPage->nCell; i++){
49749         pc = get2byte(&data[cellOffset+i*2]);
49750         testcase( pc==iCellFirst );
49751         testcase( pc==iCellLast );
49752         if( pc<iCellFirst || pc>iCellLast ){
49753           return SQLITE_CORRUPT_BKPT;
49754         }
49755         sz = cellSizePtr(pPage, &data[pc]);
49756         testcase( pc+sz==usableSize );
49757         if( pc+sz>usableSize ){
49758           return SQLITE_CORRUPT_BKPT;
49759         }
49760       }
49761       if( !pPage->leaf ) iCellLast++;
49762     }  
49763 #endif
49764
49765     /* Compute the total free space on the page */
49766     pc = get2byte(&data[hdr+1]);
49767     nFree = data[hdr+7] + top;
49768     while( pc>0 ){
49769       u16 next, size;
49770       if( pc<iCellFirst || pc>iCellLast ){
49771         /* Start of free block is off the page */
49772         return SQLITE_CORRUPT_BKPT; 
49773       }
49774       next = get2byte(&data[pc]);
49775       size = get2byte(&data[pc+2]);
49776       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49777         /* Free blocks must be in ascending order. And the last byte of
49778         ** the free-block must lie on the database page.  */
49779         return SQLITE_CORRUPT_BKPT; 
49780       }
49781       nFree = nFree + size;
49782       pc = next;
49783     }
49784
49785     /* At this point, nFree contains the sum of the offset to the start
49786     ** of the cell-content area plus the number of free bytes within
49787     ** the cell-content area. If this is greater than the usable-size
49788     ** of the page, then the page must be corrupted. This check also
49789     ** serves to verify that the offset to the start of the cell-content
49790     ** area, according to the page header, lies within the page.
49791     */
49792     if( nFree>usableSize ){
49793       return SQLITE_CORRUPT_BKPT; 
49794     }
49795     pPage->nFree = (u16)(nFree - iCellFirst);
49796     pPage->isInit = 1;
49797   }
49798   return SQLITE_OK;
49799 }
49800
49801 /*
49802 ** Set up a raw page so that it looks like a database page holding
49803 ** no entries.
49804 */
49805 static void zeroPage(MemPage *pPage, int flags){
49806   unsigned char *data = pPage->aData;
49807   BtShared *pBt = pPage->pBt;
49808   u8 hdr = pPage->hdrOffset;
49809   u16 first;
49810
49811   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49812   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49813   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49814   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49815   assert( sqlite3_mutex_held(pBt->mutex) );
49816   if( pBt->btsFlags & BTS_SECURE_DELETE ){
49817     memset(&data[hdr], 0, pBt->usableSize - hdr);
49818   }
49819   data[hdr] = (char)flags;
49820   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49821   memset(&data[hdr+1], 0, 4);
49822   data[hdr+7] = 0;
49823   put2byte(&data[hdr+5], pBt->usableSize);
49824   pPage->nFree = (u16)(pBt->usableSize - first);
49825   decodeFlags(pPage, flags);
49826   pPage->hdrOffset = hdr;
49827   pPage->cellOffset = first;
49828   pPage->aDataEnd = &data[pBt->usableSize];
49829   pPage->aCellIdx = &data[first];
49830   pPage->nOverflow = 0;
49831   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49832   pPage->maskPage = (u16)(pBt->pageSize - 1);
49833   pPage->nCell = 0;
49834   pPage->isInit = 1;
49835 }
49836
49837
49838 /*
49839 ** Convert a DbPage obtained from the pager into a MemPage used by
49840 ** the btree layer.
49841 */
49842 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49843   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49844   pPage->aData = sqlite3PagerGetData(pDbPage);
49845   pPage->pDbPage = pDbPage;
49846   pPage->pBt = pBt;
49847   pPage->pgno = pgno;
49848   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49849   return pPage; 
49850 }
49851
49852 /*
49853 ** Get a page from the pager.  Initialize the MemPage.pBt and
49854 ** MemPage.aData elements if needed.
49855 **
49856 ** If the noContent flag is set, it means that we do not care about
49857 ** the content of the page at this time.  So do not go to the disk
49858 ** to fetch the content.  Just fill in the content with zeros for now.
49859 ** If in the future we call sqlite3PagerWrite() on this page, that
49860 ** means we have started to be concerned about content and the disk
49861 ** read should occur at that point.
49862 */
49863 static int btreeGetPage(
49864   BtShared *pBt,       /* The btree */
49865   Pgno pgno,           /* Number of the page to fetch */
49866   MemPage **ppPage,    /* Return the page in this parameter */
49867   int noContent        /* Do not load page content if true */
49868 ){
49869   int rc;
49870   DbPage *pDbPage;
49871
49872   assert( sqlite3_mutex_held(pBt->mutex) );
49873   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49874   if( rc ) return rc;
49875   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49876   return SQLITE_OK;
49877 }
49878
49879 /*
49880 ** Retrieve a page from the pager cache. If the requested page is not
49881 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49882 ** MemPage.aData elements if needed.
49883 */
49884 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49885   DbPage *pDbPage;
49886   assert( sqlite3_mutex_held(pBt->mutex) );
49887   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49888   if( pDbPage ){
49889     return btreePageFromDbPage(pDbPage, pgno, pBt);
49890   }
49891   return 0;
49892 }
49893
49894 /*
49895 ** Return the size of the database file in pages. If there is any kind of
49896 ** error, return ((unsigned int)-1).
49897 */
49898 static Pgno btreePagecount(BtShared *pBt){
49899   return pBt->nPage;
49900 }
49901 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
49902   assert( sqlite3BtreeHoldsMutex(p) );
49903   assert( ((p->pBt->nPage)&0x8000000)==0 );
49904   return (int)btreePagecount(p->pBt);
49905 }
49906
49907 /*
49908 ** Get a page from the pager and initialize it.  This routine is just a
49909 ** convenience wrapper around separate calls to btreeGetPage() and 
49910 ** btreeInitPage().
49911 **
49912 ** If an error occurs, then the value *ppPage is set to is undefined. It
49913 ** may remain unchanged, or it may be set to an invalid value.
49914 */
49915 static int getAndInitPage(
49916   BtShared *pBt,          /* The database file */
49917   Pgno pgno,           /* Number of the page to get */
49918   MemPage **ppPage     /* Write the page pointer here */
49919 ){
49920   int rc;
49921   assert( sqlite3_mutex_held(pBt->mutex) );
49922
49923   if( pgno>btreePagecount(pBt) ){
49924     rc = SQLITE_CORRUPT_BKPT;
49925   }else{
49926     rc = btreeGetPage(pBt, pgno, ppPage, 0);
49927     if( rc==SQLITE_OK ){
49928       rc = btreeInitPage(*ppPage);
49929       if( rc!=SQLITE_OK ){
49930         releasePage(*ppPage);
49931       }
49932     }
49933   }
49934
49935   testcase( pgno==0 );
49936   assert( pgno!=0 || rc==SQLITE_CORRUPT );
49937   return rc;
49938 }
49939
49940 /*
49941 ** Release a MemPage.  This should be called once for each prior
49942 ** call to btreeGetPage.
49943 */
49944 static void releasePage(MemPage *pPage){
49945   if( pPage ){
49946     assert( pPage->aData );
49947     assert( pPage->pBt );
49948     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49949     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
49950     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49951     sqlite3PagerUnref(pPage->pDbPage);
49952   }
49953 }
49954
49955 /*
49956 ** During a rollback, when the pager reloads information into the cache
49957 ** so that the cache is restored to its original state at the start of
49958 ** the transaction, for each page restored this routine is called.
49959 **
49960 ** This routine needs to reset the extra data section at the end of the
49961 ** page to agree with the restored data.
49962 */
49963 static void pageReinit(DbPage *pData){
49964   MemPage *pPage;
49965   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
49966   assert( sqlite3PagerPageRefcount(pData)>0 );
49967   if( pPage->isInit ){
49968     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49969     pPage->isInit = 0;
49970     if( sqlite3PagerPageRefcount(pData)>1 ){
49971       /* pPage might not be a btree page;  it might be an overflow page
49972       ** or ptrmap page or a free page.  In those cases, the following
49973       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
49974       ** But no harm is done by this.  And it is very important that
49975       ** btreeInitPage() be called on every btree page so we make
49976       ** the call for every page that comes in for re-initing. */
49977       btreeInitPage(pPage);
49978     }
49979   }
49980 }
49981
49982 /*
49983 ** Invoke the busy handler for a btree.
49984 */
49985 static int btreeInvokeBusyHandler(void *pArg){
49986   BtShared *pBt = (BtShared*)pArg;
49987   assert( pBt->db );
49988   assert( sqlite3_mutex_held(pBt->db->mutex) );
49989   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
49990 }
49991
49992 /*
49993 ** Open a database file.
49994 ** 
49995 ** zFilename is the name of the database file.  If zFilename is NULL
49996 ** then an ephemeral database is created.  The ephemeral database might
49997 ** be exclusively in memory, or it might use a disk-based memory cache.
49998 ** Either way, the ephemeral database will be automatically deleted 
49999 ** when sqlite3BtreeClose() is called.
50000 **
50001 ** If zFilename is ":memory:" then an in-memory database is created
50002 ** that is automatically destroyed when it is closed.
50003 **
50004 ** The "flags" parameter is a bitmask that might contain bits like
50005 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
50006 **
50007 ** If the database is already opened in the same database connection
50008 ** and we are in shared cache mode, then the open will fail with an
50009 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
50010 ** objects in the same database connection since doing so will lead
50011 ** to problems with locking.
50012 */
50013 SQLITE_PRIVATE int sqlite3BtreeOpen(
50014   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
50015   const char *zFilename,  /* Name of the file containing the BTree database */
50016   sqlite3 *db,            /* Associated database handle */
50017   Btree **ppBtree,        /* Pointer to new Btree object written here */
50018   int flags,              /* Options */
50019   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
50020 ){
50021   BtShared *pBt = 0;             /* Shared part of btree structure */
50022   Btree *p;                      /* Handle to return */
50023   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
50024   int rc = SQLITE_OK;            /* Result code from this function */
50025   u8 nReserve;                   /* Byte of unused space on each page */
50026   unsigned char zDbHeader[100];  /* Database header content */
50027
50028   /* True if opening an ephemeral, temporary database */
50029   const int isTempDb = zFilename==0 || zFilename[0]==0;
50030
50031   /* Set the variable isMemdb to true for an in-memory database, or 
50032   ** false for a file-based database.
50033   */
50034 #ifdef SQLITE_OMIT_MEMORYDB
50035   const int isMemdb = 0;
50036 #else
50037   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
50038                        || (isTempDb && sqlite3TempInMemory(db))
50039                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
50040 #endif
50041
50042   assert( db!=0 );
50043   assert( pVfs!=0 );
50044   assert( sqlite3_mutex_held(db->mutex) );
50045   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
50046
50047   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
50048   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
50049
50050   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
50051   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
50052
50053   if( isMemdb ){
50054     flags |= BTREE_MEMORY;
50055   }
50056   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
50057     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
50058   }
50059   p = sqlite3MallocZero(sizeof(Btree));
50060   if( !p ){
50061     return SQLITE_NOMEM;
50062   }
50063   p->inTrans = TRANS_NONE;
50064   p->db = db;
50065 #ifndef SQLITE_OMIT_SHARED_CACHE
50066   p->lock.pBtree = p;
50067   p->lock.iTable = 1;
50068 #endif
50069
50070 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50071   /*
50072   ** If this Btree is a candidate for shared cache, try to find an
50073   ** existing BtShared object that we can share with
50074   */
50075   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
50076     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
50077       int nFullPathname = pVfs->mxPathname+1;
50078       char *zFullPathname = sqlite3Malloc(nFullPathname);
50079       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50080       p->sharable = 1;
50081       if( !zFullPathname ){
50082         sqlite3_free(p);
50083         return SQLITE_NOMEM;
50084       }
50085       if( isMemdb ){
50086         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
50087       }else{
50088         rc = sqlite3OsFullPathname(pVfs, zFilename,
50089                                    nFullPathname, zFullPathname);
50090         if( rc ){
50091           sqlite3_free(zFullPathname);
50092           sqlite3_free(p);
50093           return rc;
50094         }
50095       }
50096 #if SQLITE_THREADSAFE
50097       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
50098       sqlite3_mutex_enter(mutexOpen);
50099       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50100       sqlite3_mutex_enter(mutexShared);
50101 #endif
50102       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
50103         assert( pBt->nRef>0 );
50104         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
50105                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
50106           int iDb;
50107           for(iDb=db->nDb-1; iDb>=0; iDb--){
50108             Btree *pExisting = db->aDb[iDb].pBt;
50109             if( pExisting && pExisting->pBt==pBt ){
50110               sqlite3_mutex_leave(mutexShared);
50111               sqlite3_mutex_leave(mutexOpen);
50112               sqlite3_free(zFullPathname);
50113               sqlite3_free(p);
50114               return SQLITE_CONSTRAINT;
50115             }
50116           }
50117           p->pBt = pBt;
50118           pBt->nRef++;
50119           break;
50120         }
50121       }
50122       sqlite3_mutex_leave(mutexShared);
50123       sqlite3_free(zFullPathname);
50124     }
50125 #ifdef SQLITE_DEBUG
50126     else{
50127       /* In debug mode, we mark all persistent databases as sharable
50128       ** even when they are not.  This exercises the locking code and
50129       ** gives more opportunity for asserts(sqlite3_mutex_held())
50130       ** statements to find locking problems.
50131       */
50132       p->sharable = 1;
50133     }
50134 #endif
50135   }
50136 #endif
50137   if( pBt==0 ){
50138     /*
50139     ** The following asserts make sure that structures used by the btree are
50140     ** the right size.  This is to guard against size changes that result
50141     ** when compiling on a different architecture.
50142     */
50143     assert( sizeof(i64)==8 || sizeof(i64)==4 );
50144     assert( sizeof(u64)==8 || sizeof(u64)==4 );
50145     assert( sizeof(u32)==4 );
50146     assert( sizeof(u16)==2 );
50147     assert( sizeof(Pgno)==4 );
50148   
50149     pBt = sqlite3MallocZero( sizeof(*pBt) );
50150     if( pBt==0 ){
50151       rc = SQLITE_NOMEM;
50152       goto btree_open_out;
50153     }
50154     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
50155                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
50156     if( rc==SQLITE_OK ){
50157       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
50158     }
50159     if( rc!=SQLITE_OK ){
50160       goto btree_open_out;
50161     }
50162     pBt->openFlags = (u8)flags;
50163     pBt->db = db;
50164     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
50165     p->pBt = pBt;
50166   
50167     pBt->pCursor = 0;
50168     pBt->pPage1 = 0;
50169     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
50170 #ifdef SQLITE_SECURE_DELETE
50171     pBt->btsFlags |= BTS_SECURE_DELETE;
50172 #endif
50173     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
50174     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
50175          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
50176       pBt->pageSize = 0;
50177 #ifndef SQLITE_OMIT_AUTOVACUUM
50178       /* If the magic name ":memory:" will create an in-memory database, then
50179       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
50180       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
50181       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
50182       ** regular file-name. In this case the auto-vacuum applies as per normal.
50183       */
50184       if( zFilename && !isMemdb ){
50185         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
50186         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
50187       }
50188 #endif
50189       nReserve = 0;
50190     }else{
50191       nReserve = zDbHeader[20];
50192       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50193 #ifndef SQLITE_OMIT_AUTOVACUUM
50194       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
50195       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
50196 #endif
50197     }
50198     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50199     if( rc ) goto btree_open_out;
50200     pBt->usableSize = pBt->pageSize - nReserve;
50201     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
50202    
50203 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50204     /* Add the new BtShared object to the linked list sharable BtShareds.
50205     */
50206     if( p->sharable ){
50207       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50208       pBt->nRef = 1;
50209       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
50210       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
50211         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
50212         if( pBt->mutex==0 ){
50213           rc = SQLITE_NOMEM;
50214           db->mallocFailed = 0;
50215           goto btree_open_out;
50216         }
50217       }
50218       sqlite3_mutex_enter(mutexShared);
50219       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
50220       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
50221       sqlite3_mutex_leave(mutexShared);
50222     }
50223 #endif
50224   }
50225
50226 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50227   /* If the new Btree uses a sharable pBtShared, then link the new
50228   ** Btree into the list of all sharable Btrees for the same connection.
50229   ** The list is kept in ascending order by pBt address.
50230   */
50231   if( p->sharable ){
50232     int i;
50233     Btree *pSib;
50234     for(i=0; i<db->nDb; i++){
50235       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
50236         while( pSib->pPrev ){ pSib = pSib->pPrev; }
50237         if( p->pBt<pSib->pBt ){
50238           p->pNext = pSib;
50239           p->pPrev = 0;
50240           pSib->pPrev = p;
50241         }else{
50242           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
50243             pSib = pSib->pNext;
50244           }
50245           p->pNext = pSib->pNext;
50246           p->pPrev = pSib;
50247           if( p->pNext ){
50248             p->pNext->pPrev = p;
50249           }
50250           pSib->pNext = p;
50251         }
50252         break;
50253       }
50254     }
50255   }
50256 #endif
50257   *ppBtree = p;
50258
50259 btree_open_out:
50260   if( rc!=SQLITE_OK ){
50261     if( pBt && pBt->pPager ){
50262       sqlite3PagerClose(pBt->pPager);
50263     }
50264     sqlite3_free(pBt);
50265     sqlite3_free(p);
50266     *ppBtree = 0;
50267   }else{
50268     /* If the B-Tree was successfully opened, set the pager-cache size to the
50269     ** default value. Except, when opening on an existing shared pager-cache,
50270     ** do not change the pager-cache size.
50271     */
50272     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
50273       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
50274     }
50275   }
50276   if( mutexOpen ){
50277     assert( sqlite3_mutex_held(mutexOpen) );
50278     sqlite3_mutex_leave(mutexOpen);
50279   }
50280   return rc;
50281 }
50282
50283 /*
50284 ** Decrement the BtShared.nRef counter.  When it reaches zero,
50285 ** remove the BtShared structure from the sharing list.  Return
50286 ** true if the BtShared.nRef counter reaches zero and return
50287 ** false if it is still positive.
50288 */
50289 static int removeFromSharingList(BtShared *pBt){
50290 #ifndef SQLITE_OMIT_SHARED_CACHE
50291   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
50292   BtShared *pList;
50293   int removed = 0;
50294
50295   assert( sqlite3_mutex_notheld(pBt->mutex) );
50296   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
50297   sqlite3_mutex_enter(pMaster);
50298   pBt->nRef--;
50299   if( pBt->nRef<=0 ){
50300     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
50301       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
50302     }else{
50303       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
50304       while( ALWAYS(pList) && pList->pNext!=pBt ){
50305         pList=pList->pNext;
50306       }
50307       if( ALWAYS(pList) ){
50308         pList->pNext = pBt->pNext;
50309       }
50310     }
50311     if( SQLITE_THREADSAFE ){
50312       sqlite3_mutex_free(pBt->mutex);
50313     }
50314     removed = 1;
50315   }
50316   sqlite3_mutex_leave(pMaster);
50317   return removed;
50318 #else
50319   return 1;
50320 #endif
50321 }
50322
50323 /*
50324 ** Make sure pBt->pTmpSpace points to an allocation of 
50325 ** MX_CELL_SIZE(pBt) bytes.
50326 */
50327 static void allocateTempSpace(BtShared *pBt){
50328   if( !pBt->pTmpSpace ){
50329     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
50330   }
50331 }
50332
50333 /*
50334 ** Free the pBt->pTmpSpace allocation
50335 */
50336 static void freeTempSpace(BtShared *pBt){
50337   sqlite3PageFree( pBt->pTmpSpace);
50338   pBt->pTmpSpace = 0;
50339 }
50340
50341 /*
50342 ** Close an open database and invalidate all cursors.
50343 */
50344 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
50345   BtShared *pBt = p->pBt;
50346   BtCursor *pCur;
50347
50348   /* Close all cursors opened via this handle.  */
50349   assert( sqlite3_mutex_held(p->db->mutex) );
50350   sqlite3BtreeEnter(p);
50351   pCur = pBt->pCursor;
50352   while( pCur ){
50353     BtCursor *pTmp = pCur;
50354     pCur = pCur->pNext;
50355     if( pTmp->pBtree==p ){
50356       sqlite3BtreeCloseCursor(pTmp);
50357     }
50358   }
50359
50360   /* Rollback any active transaction and free the handle structure.
50361   ** The call to sqlite3BtreeRollback() drops any table-locks held by
50362   ** this handle.
50363   */
50364   sqlite3BtreeRollback(p, SQLITE_OK);
50365   sqlite3BtreeLeave(p);
50366
50367   /* If there are still other outstanding references to the shared-btree
50368   ** structure, return now. The remainder of this procedure cleans 
50369   ** up the shared-btree.
50370   */
50371   assert( p->wantToLock==0 && p->locked==0 );
50372   if( !p->sharable || removeFromSharingList(pBt) ){
50373     /* The pBt is no longer on the sharing list, so we can access
50374     ** it without having to hold the mutex.
50375     **
50376     ** Clean out and delete the BtShared object.
50377     */
50378     assert( !pBt->pCursor );
50379     sqlite3PagerClose(pBt->pPager);
50380     if( pBt->xFreeSchema && pBt->pSchema ){
50381       pBt->xFreeSchema(pBt->pSchema);
50382     }
50383     sqlite3DbFree(0, pBt->pSchema);
50384     freeTempSpace(pBt);
50385     sqlite3_free(pBt);
50386   }
50387
50388 #ifndef SQLITE_OMIT_SHARED_CACHE
50389   assert( p->wantToLock==0 );
50390   assert( p->locked==0 );
50391   if( p->pPrev ) p->pPrev->pNext = p->pNext;
50392   if( p->pNext ) p->pNext->pPrev = p->pPrev;
50393 #endif
50394
50395   sqlite3_free(p);
50396   return SQLITE_OK;
50397 }
50398
50399 /*
50400 ** Change the limit on the number of pages allowed in the cache.
50401 **
50402 ** The maximum number of cache pages is set to the absolute
50403 ** value of mxPage.  If mxPage is negative, the pager will
50404 ** operate asynchronously - it will not stop to do fsync()s
50405 ** to insure data is written to the disk surface before
50406 ** continuing.  Transactions still work if synchronous is off,
50407 ** and the database cannot be corrupted if this program
50408 ** crashes.  But if the operating system crashes or there is
50409 ** an abrupt power failure when synchronous is off, the database
50410 ** could be left in an inconsistent and unrecoverable state.
50411 ** Synchronous is on by default so database corruption is not
50412 ** normally a worry.
50413 */
50414 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50415   BtShared *pBt = p->pBt;
50416   assert( sqlite3_mutex_held(p->db->mutex) );
50417   sqlite3BtreeEnter(p);
50418   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50419   sqlite3BtreeLeave(p);
50420   return SQLITE_OK;
50421 }
50422
50423 /*
50424 ** Change the way data is synced to disk in order to increase or decrease
50425 ** how well the database resists damage due to OS crashes and power
50426 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
50427 ** there is a high probability of damage)  Level 2 is the default.  There
50428 ** is a very low but non-zero probability of damage.  Level 3 reduces the
50429 ** probability of damage to near zero but with a write performance reduction.
50430 */
50431 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50432 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50433   Btree *p,              /* The btree to set the safety level on */
50434   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
50435   int fullSync,          /* PRAGMA fullfsync. */
50436   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
50437 ){
50438   BtShared *pBt = p->pBt;
50439   assert( sqlite3_mutex_held(p->db->mutex) );
50440   assert( level>=1 && level<=3 );
50441   sqlite3BtreeEnter(p);
50442   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50443   sqlite3BtreeLeave(p);
50444   return SQLITE_OK;
50445 }
50446 #endif
50447
50448 /*
50449 ** Return TRUE if the given btree is set to safety level 1.  In other
50450 ** words, return TRUE if no sync() occurs on the disk files.
50451 */
50452 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50453   BtShared *pBt = p->pBt;
50454   int rc;
50455   assert( sqlite3_mutex_held(p->db->mutex) );  
50456   sqlite3BtreeEnter(p);
50457   assert( pBt && pBt->pPager );
50458   rc = sqlite3PagerNosync(pBt->pPager);
50459   sqlite3BtreeLeave(p);
50460   return rc;
50461 }
50462
50463 /*
50464 ** Change the default pages size and the number of reserved bytes per page.
50465 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
50466 ** without changing anything.
50467 **
50468 ** The page size must be a power of 2 between 512 and 65536.  If the page
50469 ** size supplied does not meet this constraint then the page size is not
50470 ** changed.
50471 **
50472 ** Page sizes are constrained to be a power of two so that the region
50473 ** of the database file used for locking (beginning at PENDING_BYTE,
50474 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50475 ** at the beginning of a page.
50476 **
50477 ** If parameter nReserve is less than zero, then the number of reserved
50478 ** bytes per page is left unchanged.
50479 **
50480 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
50481 ** and autovacuum mode can no longer be changed.
50482 */
50483 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50484   int rc = SQLITE_OK;
50485   BtShared *pBt = p->pBt;
50486   assert( nReserve>=-1 && nReserve<=255 );
50487   sqlite3BtreeEnter(p);
50488   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
50489     sqlite3BtreeLeave(p);
50490     return SQLITE_READONLY;
50491   }
50492   if( nReserve<0 ){
50493     nReserve = pBt->pageSize - pBt->usableSize;
50494   }
50495   assert( nReserve>=0 && nReserve<=255 );
50496   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50497         ((pageSize-1)&pageSize)==0 ){
50498     assert( (pageSize & 7)==0 );
50499     assert( !pBt->pPage1 && !pBt->pCursor );
50500     pBt->pageSize = (u32)pageSize;
50501     freeTempSpace(pBt);
50502   }
50503   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50504   pBt->usableSize = pBt->pageSize - (u16)nReserve;
50505   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50506   sqlite3BtreeLeave(p);
50507   return rc;
50508 }
50509
50510 /*
50511 ** Return the currently defined page size
50512 */
50513 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50514   return p->pBt->pageSize;
50515 }
50516
50517 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
50518 /*
50519 ** This function is similar to sqlite3BtreeGetReserve(), except that it
50520 ** may only be called if it is guaranteed that the b-tree mutex is already
50521 ** held.
50522 **
50523 ** This is useful in one special case in the backup API code where it is
50524 ** known that the shared b-tree mutex is held, but the mutex on the 
50525 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
50526 ** were to be called, it might collide with some other operation on the
50527 ** database handle that owns *p, causing undefined behaviour.
50528 */
50529 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
50530   assert( sqlite3_mutex_held(p->pBt->mutex) );
50531   return p->pBt->pageSize - p->pBt->usableSize;
50532 }
50533 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
50534
50535 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50536 /*
50537 ** Return the number of bytes of space at the end of every page that
50538 ** are intentually left unused.  This is the "reserved" space that is
50539 ** sometimes used by extensions.
50540 */
50541 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50542   int n;
50543   sqlite3BtreeEnter(p);
50544   n = p->pBt->pageSize - p->pBt->usableSize;
50545   sqlite3BtreeLeave(p);
50546   return n;
50547 }
50548
50549 /*
50550 ** Set the maximum page count for a database if mxPage is positive.
50551 ** No changes are made if mxPage is 0 or negative.
50552 ** Regardless of the value of mxPage, return the maximum page count.
50553 */
50554 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50555   int n;
50556   sqlite3BtreeEnter(p);
50557   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50558   sqlite3BtreeLeave(p);
50559   return n;
50560 }
50561
50562 /*
50563 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
50564 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
50565 ** setting after the change.
50566 */
50567 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50568   int b;
50569   if( p==0 ) return 0;
50570   sqlite3BtreeEnter(p);
50571   if( newFlag>=0 ){
50572     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
50573     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
50574   } 
50575   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
50576   sqlite3BtreeLeave(p);
50577   return b;
50578 }
50579 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50580
50581 /*
50582 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50583 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50584 ** is disabled. The default value for the auto-vacuum property is 
50585 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50586 */
50587 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50588 #ifdef SQLITE_OMIT_AUTOVACUUM
50589   return SQLITE_READONLY;
50590 #else
50591   BtShared *pBt = p->pBt;
50592   int rc = SQLITE_OK;
50593   u8 av = (u8)autoVacuum;
50594
50595   sqlite3BtreeEnter(p);
50596   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
50597     rc = SQLITE_READONLY;
50598   }else{
50599     pBt->autoVacuum = av ?1:0;
50600     pBt->incrVacuum = av==2 ?1:0;
50601   }
50602   sqlite3BtreeLeave(p);
50603   return rc;
50604 #endif
50605 }
50606
50607 /*
50608 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
50609 ** enabled 1 is returned. Otherwise 0.
50610 */
50611 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50612 #ifdef SQLITE_OMIT_AUTOVACUUM
50613   return BTREE_AUTOVACUUM_NONE;
50614 #else
50615   int rc;
50616   sqlite3BtreeEnter(p);
50617   rc = (
50618     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50619     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50620     BTREE_AUTOVACUUM_INCR
50621   );
50622   sqlite3BtreeLeave(p);
50623   return rc;
50624 #endif
50625 }
50626
50627
50628 /*
50629 ** Get a reference to pPage1 of the database file.  This will
50630 ** also acquire a readlock on that file.
50631 **
50632 ** SQLITE_OK is returned on success.  If the file is not a
50633 ** well-formed database file, then SQLITE_CORRUPT is returned.
50634 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
50635 ** is returned if we run out of memory. 
50636 */
50637 static int lockBtree(BtShared *pBt){
50638   int rc;              /* Result code from subfunctions */
50639   MemPage *pPage1;     /* Page 1 of the database file */
50640   int nPage;           /* Number of pages in the database */
50641   int nPageFile = 0;   /* Number of pages in the database file */
50642   int nPageHeader;     /* Number of pages in the database according to hdr */
50643
50644   assert( sqlite3_mutex_held(pBt->mutex) );
50645   assert( pBt->pPage1==0 );
50646   rc = sqlite3PagerSharedLock(pBt->pPager);
50647   if( rc!=SQLITE_OK ) return rc;
50648   rc = btreeGetPage(pBt, 1, &pPage1, 0);
50649   if( rc!=SQLITE_OK ) return rc;
50650
50651   /* Do some checking to help insure the file we opened really is
50652   ** a valid database file. 
50653   */
50654   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50655   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50656   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50657     nPage = nPageFile;
50658   }
50659   if( nPage>0 ){
50660     u32 pageSize;
50661     u32 usableSize;
50662     u8 *page1 = pPage1->aData;
50663     rc = SQLITE_NOTADB;
50664     if( memcmp(page1, zMagicHeader, 16)!=0 ){
50665       goto page1_init_failed;
50666     }
50667
50668 #ifdef SQLITE_OMIT_WAL
50669     if( page1[18]>1 ){
50670       pBt->btsFlags |= BTS_READ_ONLY;
50671     }
50672     if( page1[19]>1 ){
50673       goto page1_init_failed;
50674     }
50675 #else
50676     if( page1[18]>2 ){
50677       pBt->btsFlags |= BTS_READ_ONLY;
50678     }
50679     if( page1[19]>2 ){
50680       goto page1_init_failed;
50681     }
50682
50683     /* If the write version is set to 2, this database should be accessed
50684     ** in WAL mode. If the log is not already open, open it now. Then 
50685     ** return SQLITE_OK and return without populating BtShared.pPage1.
50686     ** The caller detects this and calls this function again. This is
50687     ** required as the version of page 1 currently in the page1 buffer
50688     ** may not be the latest version - there may be a newer one in the log
50689     ** file.
50690     */
50691     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
50692       int isOpen = 0;
50693       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50694       if( rc!=SQLITE_OK ){
50695         goto page1_init_failed;
50696       }else if( isOpen==0 ){
50697         releasePage(pPage1);
50698         return SQLITE_OK;
50699       }
50700       rc = SQLITE_NOTADB;
50701     }
50702 #endif
50703
50704     /* The maximum embedded fraction must be exactly 25%.  And the minimum
50705     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50706     ** The original design allowed these amounts to vary, but as of
50707     ** version 3.6.0, we require them to be fixed.
50708     */
50709     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50710       goto page1_init_failed;
50711     }
50712     pageSize = (page1[16]<<8) | (page1[17]<<16);
50713     if( ((pageSize-1)&pageSize)!=0
50714      || pageSize>SQLITE_MAX_PAGE_SIZE 
50715      || pageSize<=256 
50716     ){
50717       goto page1_init_failed;
50718     }
50719     assert( (pageSize & 7)==0 );
50720     usableSize = pageSize - page1[20];
50721     if( (u32)pageSize!=pBt->pageSize ){
50722       /* After reading the first page of the database assuming a page size
50723       ** of BtShared.pageSize, we have discovered that the page-size is
50724       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50725       ** zero and return SQLITE_OK. The caller will call this function
50726       ** again with the correct page-size.
50727       */
50728       releasePage(pPage1);
50729       pBt->usableSize = usableSize;
50730       pBt->pageSize = pageSize;
50731       freeTempSpace(pBt);
50732       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50733                                    pageSize-usableSize);
50734       return rc;
50735     }
50736     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50737       rc = SQLITE_CORRUPT_BKPT;
50738       goto page1_init_failed;
50739     }
50740     if( usableSize<480 ){
50741       goto page1_init_failed;
50742     }
50743     pBt->pageSize = pageSize;
50744     pBt->usableSize = usableSize;
50745 #ifndef SQLITE_OMIT_AUTOVACUUM
50746     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50747     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50748 #endif
50749   }
50750
50751   /* maxLocal is the maximum amount of payload to store locally for
50752   ** a cell.  Make sure it is small enough so that at least minFanout
50753   ** cells can will fit on one page.  We assume a 10-byte page header.
50754   ** Besides the payload, the cell must store:
50755   **     2-byte pointer to the cell
50756   **     4-byte child pointer
50757   **     9-byte nKey value
50758   **     4-byte nData value
50759   **     4-byte overflow page pointer
50760   ** So a cell consists of a 2-byte pointer, a header which is as much as
50761   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50762   ** page pointer.
50763   */
50764   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50765   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50766   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50767   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50768   if( pBt->maxLocal>127 ){
50769     pBt->max1bytePayload = 127;
50770   }else{
50771     pBt->max1bytePayload = (u8)pBt->maxLocal;
50772   }
50773   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50774   pBt->pPage1 = pPage1;
50775   pBt->nPage = nPage;
50776   return SQLITE_OK;
50777
50778 page1_init_failed:
50779   releasePage(pPage1);
50780   pBt->pPage1 = 0;
50781   return rc;
50782 }
50783
50784 /*
50785 ** If there are no outstanding cursors and we are not in the middle
50786 ** of a transaction but there is a read lock on the database, then
50787 ** this routine unrefs the first page of the database file which 
50788 ** has the effect of releasing the read lock.
50789 **
50790 ** If there is a transaction in progress, this routine is a no-op.
50791 */
50792 static void unlockBtreeIfUnused(BtShared *pBt){
50793   assert( sqlite3_mutex_held(pBt->mutex) );
50794   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50795   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50796     assert( pBt->pPage1->aData );
50797     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50798     assert( pBt->pPage1->aData );
50799     releasePage(pBt->pPage1);
50800     pBt->pPage1 = 0;
50801   }
50802 }
50803
50804 /*
50805 ** If pBt points to an empty file then convert that empty file
50806 ** into a new empty database by initializing the first page of
50807 ** the database.
50808 */
50809 static int newDatabase(BtShared *pBt){
50810   MemPage *pP1;
50811   unsigned char *data;
50812   int rc;
50813
50814   assert( sqlite3_mutex_held(pBt->mutex) );
50815   if( pBt->nPage>0 ){
50816     return SQLITE_OK;
50817   }
50818   pP1 = pBt->pPage1;
50819   assert( pP1!=0 );
50820   data = pP1->aData;
50821   rc = sqlite3PagerWrite(pP1->pDbPage);
50822   if( rc ) return rc;
50823   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50824   assert( sizeof(zMagicHeader)==16 );
50825   data[16] = (u8)((pBt->pageSize>>8)&0xff);
50826   data[17] = (u8)((pBt->pageSize>>16)&0xff);
50827   data[18] = 1;
50828   data[19] = 1;
50829   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50830   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50831   data[21] = 64;
50832   data[22] = 32;
50833   data[23] = 32;
50834   memset(&data[24], 0, 100-24);
50835   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50836   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50837 #ifndef SQLITE_OMIT_AUTOVACUUM
50838   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50839   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50840   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50841   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50842 #endif
50843   pBt->nPage = 1;
50844   data[31] = 1;
50845   return SQLITE_OK;
50846 }
50847
50848 /*
50849 ** Initialize the first page of the database file (creating a database
50850 ** consisting of a single page and no schema objects). Return SQLITE_OK
50851 ** if successful, or an SQLite error code otherwise.
50852 */
50853 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
50854   int rc;
50855   sqlite3BtreeEnter(p);
50856   p->pBt->nPage = 0;
50857   rc = newDatabase(p->pBt);
50858   sqlite3BtreeLeave(p);
50859   return rc;
50860 }
50861
50862 /*
50863 ** Attempt to start a new transaction. A write-transaction
50864 ** is started if the second argument is nonzero, otherwise a read-
50865 ** transaction.  If the second argument is 2 or more and exclusive
50866 ** transaction is started, meaning that no other process is allowed
50867 ** to access the database.  A preexisting transaction may not be
50868 ** upgraded to exclusive by calling this routine a second time - the
50869 ** exclusivity flag only works for a new transaction.
50870 **
50871 ** A write-transaction must be started before attempting any 
50872 ** changes to the database.  None of the following routines 
50873 ** will work unless a transaction is started first:
50874 **
50875 **      sqlite3BtreeCreateTable()
50876 **      sqlite3BtreeCreateIndex()
50877 **      sqlite3BtreeClearTable()
50878 **      sqlite3BtreeDropTable()
50879 **      sqlite3BtreeInsert()
50880 **      sqlite3BtreeDelete()
50881 **      sqlite3BtreeUpdateMeta()
50882 **
50883 ** If an initial attempt to acquire the lock fails because of lock contention
50884 ** and the database was previously unlocked, then invoke the busy handler
50885 ** if there is one.  But if there was previously a read-lock, do not
50886 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
50887 ** returned when there is already a read-lock in order to avoid a deadlock.
50888 **
50889 ** Suppose there are two processes A and B.  A has a read lock and B has
50890 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50891 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50892 ** One or the other of the two processes must give way or there can be
50893 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50894 ** when A already has a read lock, we encourage A to give up and let B
50895 ** proceed.
50896 */
50897 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50898   sqlite3 *pBlock = 0;
50899   BtShared *pBt = p->pBt;
50900   int rc = SQLITE_OK;
50901
50902   sqlite3BtreeEnter(p);
50903   btreeIntegrity(p);
50904
50905   /* If the btree is already in a write-transaction, or it
50906   ** is already in a read-transaction and a read-transaction
50907   ** is requested, this is a no-op.
50908   */
50909   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
50910     goto trans_begun;
50911   }
50912
50913   /* Write transactions are not possible on a read-only database */
50914   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
50915     rc = SQLITE_READONLY;
50916     goto trans_begun;
50917   }
50918
50919 #ifndef SQLITE_OMIT_SHARED_CACHE
50920   /* If another database handle has already opened a write transaction 
50921   ** on this shared-btree structure and a second write transaction is
50922   ** requested, return SQLITE_LOCKED.
50923   */
50924   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
50925    || (pBt->btsFlags & BTS_PENDING)!=0
50926   ){
50927     pBlock = pBt->pWriter->db;
50928   }else if( wrflag>1 ){
50929     BtLock *pIter;
50930     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50931       if( pIter->pBtree!=p ){
50932         pBlock = pIter->pBtree->db;
50933         break;
50934       }
50935     }
50936   }
50937   if( pBlock ){
50938     sqlite3ConnectionBlocked(p->db, pBlock);
50939     rc = SQLITE_LOCKED_SHAREDCACHE;
50940     goto trans_begun;
50941   }
50942 #endif
50943
50944   /* Any read-only or read-write transaction implies a read-lock on 
50945   ** page 1. So if some other shared-cache client already has a write-lock 
50946   ** on page 1, the transaction cannot be opened. */
50947   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
50948   if( SQLITE_OK!=rc ) goto trans_begun;
50949
50950   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
50951   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
50952   do {
50953     /* Call lockBtree() until either pBt->pPage1 is populated or
50954     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
50955     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
50956     ** reading page 1 it discovers that the page-size of the database 
50957     ** file is not pBt->pageSize. In this case lockBtree() will update
50958     ** pBt->pageSize to the page-size of the file on disk.
50959     */
50960     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
50961
50962     if( rc==SQLITE_OK && wrflag ){
50963       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
50964         rc = SQLITE_READONLY;
50965       }else{
50966         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
50967         if( rc==SQLITE_OK ){
50968           rc = newDatabase(pBt);
50969         }
50970       }
50971     }
50972   
50973     if( rc!=SQLITE_OK ){
50974       unlockBtreeIfUnused(pBt);
50975     }
50976   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
50977           btreeInvokeBusyHandler(pBt) );
50978
50979   if( rc==SQLITE_OK ){
50980     if( p->inTrans==TRANS_NONE ){
50981       pBt->nTransaction++;
50982 #ifndef SQLITE_OMIT_SHARED_CACHE
50983       if( p->sharable ){
50984         assert( p->lock.pBtree==p && p->lock.iTable==1 );
50985         p->lock.eLock = READ_LOCK;
50986         p->lock.pNext = pBt->pLock;
50987         pBt->pLock = &p->lock;
50988       }
50989 #endif
50990     }
50991     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
50992     if( p->inTrans>pBt->inTransaction ){
50993       pBt->inTransaction = p->inTrans;
50994     }
50995     if( wrflag ){
50996       MemPage *pPage1 = pBt->pPage1;
50997 #ifndef SQLITE_OMIT_SHARED_CACHE
50998       assert( !pBt->pWriter );
50999       pBt->pWriter = p;
51000       pBt->btsFlags &= ~BTS_EXCLUSIVE;
51001       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
51002 #endif
51003
51004       /* If the db-size header field is incorrect (as it may be if an old
51005       ** client has been writing the database file), update it now. Doing
51006       ** this sooner rather than later means the database size can safely 
51007       ** re-read the database size from page 1 if a savepoint or transaction
51008       ** rollback occurs within the transaction.
51009       */
51010       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
51011         rc = sqlite3PagerWrite(pPage1->pDbPage);
51012         if( rc==SQLITE_OK ){
51013           put4byte(&pPage1->aData[28], pBt->nPage);
51014         }
51015       }
51016     }
51017   }
51018
51019
51020 trans_begun:
51021   if( rc==SQLITE_OK && wrflag ){
51022     /* This call makes sure that the pager has the correct number of
51023     ** open savepoints. If the second parameter is greater than 0 and
51024     ** the sub-journal is not already open, then it will be opened here.
51025     */
51026     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
51027   }
51028
51029   btreeIntegrity(p);
51030   sqlite3BtreeLeave(p);
51031   return rc;
51032 }
51033
51034 #ifndef SQLITE_OMIT_AUTOVACUUM
51035
51036 /*
51037 ** Set the pointer-map entries for all children of page pPage. Also, if
51038 ** pPage contains cells that point to overflow pages, set the pointer
51039 ** map entries for the overflow pages as well.
51040 */
51041 static int setChildPtrmaps(MemPage *pPage){
51042   int i;                             /* Counter variable */
51043   int nCell;                         /* Number of cells in page pPage */
51044   int rc;                            /* Return code */
51045   BtShared *pBt = pPage->pBt;
51046   u8 isInitOrig = pPage->isInit;
51047   Pgno pgno = pPage->pgno;
51048
51049   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51050   rc = btreeInitPage(pPage);
51051   if( rc!=SQLITE_OK ){
51052     goto set_child_ptrmaps_out;
51053   }
51054   nCell = pPage->nCell;
51055
51056   for(i=0; i<nCell; i++){
51057     u8 *pCell = findCell(pPage, i);
51058
51059     ptrmapPutOvflPtr(pPage, pCell, &rc);
51060
51061     if( !pPage->leaf ){
51062       Pgno childPgno = get4byte(pCell);
51063       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51064     }
51065   }
51066
51067   if( !pPage->leaf ){
51068     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51069     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51070   }
51071
51072 set_child_ptrmaps_out:
51073   pPage->isInit = isInitOrig;
51074   return rc;
51075 }
51076
51077 /*
51078 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
51079 ** that it points to iTo. Parameter eType describes the type of pointer to
51080 ** be modified, as  follows:
51081 **
51082 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
51083 **                   page of pPage.
51084 **
51085 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
51086 **                   page pointed to by one of the cells on pPage.
51087 **
51088 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
51089 **                   overflow page in the list.
51090 */
51091 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
51092   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51093   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51094   if( eType==PTRMAP_OVERFLOW2 ){
51095     /* The pointer is always the first 4 bytes of the page in this case.  */
51096     if( get4byte(pPage->aData)!=iFrom ){
51097       return SQLITE_CORRUPT_BKPT;
51098     }
51099     put4byte(pPage->aData, iTo);
51100   }else{
51101     u8 isInitOrig = pPage->isInit;
51102     int i;
51103     int nCell;
51104
51105     btreeInitPage(pPage);
51106     nCell = pPage->nCell;
51107
51108     for(i=0; i<nCell; i++){
51109       u8 *pCell = findCell(pPage, i);
51110       if( eType==PTRMAP_OVERFLOW1 ){
51111         CellInfo info;
51112         btreeParseCellPtr(pPage, pCell, &info);
51113         if( info.iOverflow
51114          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
51115          && iFrom==get4byte(&pCell[info.iOverflow])
51116         ){
51117           put4byte(&pCell[info.iOverflow], iTo);
51118           break;
51119         }
51120       }else{
51121         if( get4byte(pCell)==iFrom ){
51122           put4byte(pCell, iTo);
51123           break;
51124         }
51125       }
51126     }
51127   
51128     if( i==nCell ){
51129       if( eType!=PTRMAP_BTREE || 
51130           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
51131         return SQLITE_CORRUPT_BKPT;
51132       }
51133       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
51134     }
51135
51136     pPage->isInit = isInitOrig;
51137   }
51138   return SQLITE_OK;
51139 }
51140
51141
51142 /*
51143 ** Move the open database page pDbPage to location iFreePage in the 
51144 ** database. The pDbPage reference remains valid.
51145 **
51146 ** The isCommit flag indicates that there is no need to remember that
51147 ** the journal needs to be sync()ed before database page pDbPage->pgno 
51148 ** can be written to. The caller has already promised not to write to that
51149 ** page.
51150 */
51151 static int relocatePage(
51152   BtShared *pBt,           /* Btree */
51153   MemPage *pDbPage,        /* Open page to move */
51154   u8 eType,                /* Pointer map 'type' entry for pDbPage */
51155   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
51156   Pgno iFreePage,          /* The location to move pDbPage to */
51157   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
51158 ){
51159   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
51160   Pgno iDbPage = pDbPage->pgno;
51161   Pager *pPager = pBt->pPager;
51162   int rc;
51163
51164   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
51165       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
51166   assert( sqlite3_mutex_held(pBt->mutex) );
51167   assert( pDbPage->pBt==pBt );
51168
51169   /* Move page iDbPage from its current location to page number iFreePage */
51170   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
51171       iDbPage, iFreePage, iPtrPage, eType));
51172   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
51173   if( rc!=SQLITE_OK ){
51174     return rc;
51175   }
51176   pDbPage->pgno = iFreePage;
51177
51178   /* If pDbPage was a btree-page, then it may have child pages and/or cells
51179   ** that point to overflow pages. The pointer map entries for all these
51180   ** pages need to be changed.
51181   **
51182   ** If pDbPage is an overflow page, then the first 4 bytes may store a
51183   ** pointer to a subsequent overflow page. If this is the case, then
51184   ** the pointer map needs to be updated for the subsequent overflow page.
51185   */
51186   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
51187     rc = setChildPtrmaps(pDbPage);
51188     if( rc!=SQLITE_OK ){
51189       return rc;
51190     }
51191   }else{
51192     Pgno nextOvfl = get4byte(pDbPage->aData);
51193     if( nextOvfl!=0 ){
51194       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
51195       if( rc!=SQLITE_OK ){
51196         return rc;
51197       }
51198     }
51199   }
51200
51201   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
51202   ** that it points at iFreePage. Also fix the pointer map entry for
51203   ** iPtrPage.
51204   */
51205   if( eType!=PTRMAP_ROOTPAGE ){
51206     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
51207     if( rc!=SQLITE_OK ){
51208       return rc;
51209     }
51210     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
51211     if( rc!=SQLITE_OK ){
51212       releasePage(pPtrPage);
51213       return rc;
51214     }
51215     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
51216     releasePage(pPtrPage);
51217     if( rc==SQLITE_OK ){
51218       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
51219     }
51220   }
51221   return rc;
51222 }
51223
51224 /* Forward declaration required by incrVacuumStep(). */
51225 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
51226
51227 /*
51228 ** Perform a single step of an incremental-vacuum. If successful,
51229 ** return SQLITE_OK. If there is no work to do (and therefore no
51230 ** point in calling this function again), return SQLITE_DONE.
51231 **
51232 ** More specificly, this function attempts to re-organize the 
51233 ** database so that the last page of the file currently in use
51234 ** is no longer in use.
51235 **
51236 ** If the nFin parameter is non-zero, this function assumes
51237 ** that the caller will keep calling incrVacuumStep() until
51238 ** it returns SQLITE_DONE or an error, and that nFin is the
51239 ** number of pages the database file will contain after this 
51240 ** process is complete.  If nFin is zero, it is assumed that
51241 ** incrVacuumStep() will be called a finite amount of times
51242 ** which may or may not empty the freelist.  A full autovacuum
51243 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
51244 */
51245 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
51246   Pgno nFreeList;           /* Number of pages still on the free-list */
51247   int rc;
51248
51249   assert( sqlite3_mutex_held(pBt->mutex) );
51250   assert( iLastPg>nFin );
51251
51252   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
51253     u8 eType;
51254     Pgno iPtrPage;
51255
51256     nFreeList = get4byte(&pBt->pPage1->aData[36]);
51257     if( nFreeList==0 ){
51258       return SQLITE_DONE;
51259     }
51260
51261     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
51262     if( rc!=SQLITE_OK ){
51263       return rc;
51264     }
51265     if( eType==PTRMAP_ROOTPAGE ){
51266       return SQLITE_CORRUPT_BKPT;
51267     }
51268
51269     if( eType==PTRMAP_FREEPAGE ){
51270       if( nFin==0 ){
51271         /* Remove the page from the files free-list. This is not required
51272         ** if nFin is non-zero. In that case, the free-list will be
51273         ** truncated to zero after this function returns, so it doesn't 
51274         ** matter if it still contains some garbage entries.
51275         */
51276         Pgno iFreePg;
51277         MemPage *pFreePg;
51278         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
51279         if( rc!=SQLITE_OK ){
51280           return rc;
51281         }
51282         assert( iFreePg==iLastPg );
51283         releasePage(pFreePg);
51284       }
51285     } else {
51286       Pgno iFreePg;             /* Index of free page to move pLastPg to */
51287       MemPage *pLastPg;
51288
51289       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
51290       if( rc!=SQLITE_OK ){
51291         return rc;
51292       }
51293
51294       /* If nFin is zero, this loop runs exactly once and page pLastPg
51295       ** is swapped with the first free page pulled off the free list.
51296       **
51297       ** On the other hand, if nFin is greater than zero, then keep
51298       ** looping until a free-page located within the first nFin pages
51299       ** of the file is found.
51300       */
51301       do {
51302         MemPage *pFreePg;
51303         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
51304         if( rc!=SQLITE_OK ){
51305           releasePage(pLastPg);
51306           return rc;
51307         }
51308         releasePage(pFreePg);
51309       }while( nFin!=0 && iFreePg>nFin );
51310       assert( iFreePg<iLastPg );
51311       
51312       rc = sqlite3PagerWrite(pLastPg->pDbPage);
51313       if( rc==SQLITE_OK ){
51314         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
51315       }
51316       releasePage(pLastPg);
51317       if( rc!=SQLITE_OK ){
51318         return rc;
51319       }
51320     }
51321   }
51322
51323   if( nFin==0 ){
51324     iLastPg--;
51325     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
51326       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
51327         MemPage *pPg;
51328         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
51329         if( rc!=SQLITE_OK ){
51330           return rc;
51331         }
51332         rc = sqlite3PagerWrite(pPg->pDbPage);
51333         releasePage(pPg);
51334         if( rc!=SQLITE_OK ){
51335           return rc;
51336         }
51337       }
51338       iLastPg--;
51339     }
51340     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
51341     pBt->nPage = iLastPg;
51342   }
51343   return SQLITE_OK;
51344 }
51345
51346 /*
51347 ** A write-transaction must be opened before calling this function.
51348 ** It performs a single unit of work towards an incremental vacuum.
51349 **
51350 ** If the incremental vacuum is finished after this function has run,
51351 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
51352 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
51353 */
51354 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
51355   int rc;
51356   BtShared *pBt = p->pBt;
51357
51358   sqlite3BtreeEnter(p);
51359   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
51360   if( !pBt->autoVacuum ){
51361     rc = SQLITE_DONE;
51362   }else{
51363     invalidateAllOverflowCache(pBt);
51364     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
51365     if( rc==SQLITE_OK ){
51366       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51367       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
51368     }
51369   }
51370   sqlite3BtreeLeave(p);
51371   return rc;
51372 }
51373
51374 /*
51375 ** This routine is called prior to sqlite3PagerCommit when a transaction
51376 ** is commited for an auto-vacuum database.
51377 **
51378 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
51379 ** the database file should be truncated to during the commit process. 
51380 ** i.e. the database has been reorganized so that only the first *pnTrunc
51381 ** pages are in use.
51382 */
51383 static int autoVacuumCommit(BtShared *pBt){
51384   int rc = SQLITE_OK;
51385   Pager *pPager = pBt->pPager;
51386   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
51387
51388   assert( sqlite3_mutex_held(pBt->mutex) );
51389   invalidateAllOverflowCache(pBt);
51390   assert(pBt->autoVacuum);
51391   if( !pBt->incrVacuum ){
51392     Pgno nFin;         /* Number of pages in database after autovacuuming */
51393     Pgno nFree;        /* Number of pages on the freelist initially */
51394     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
51395     Pgno iFree;        /* The next page to be freed */
51396     int nEntry;        /* Number of entries on one ptrmap page */
51397     Pgno nOrig;        /* Database size before freeing */
51398
51399     nOrig = btreePagecount(pBt);
51400     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
51401       /* It is not possible to create a database for which the final page
51402       ** is either a pointer-map page or the pending-byte page. If one
51403       ** is encountered, this indicates corruption.
51404       */
51405       return SQLITE_CORRUPT_BKPT;
51406     }
51407
51408     nFree = get4byte(&pBt->pPage1->aData[36]);
51409     nEntry = pBt->usableSize/5;
51410     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
51411     nFin = nOrig - nFree - nPtrmap;
51412     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
51413       nFin--;
51414     }
51415     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
51416       nFin--;
51417     }
51418     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51419
51420     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51421       rc = incrVacuumStep(pBt, nFin, iFree);
51422     }
51423     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51424       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51425       put4byte(&pBt->pPage1->aData[32], 0);
51426       put4byte(&pBt->pPage1->aData[36], 0);
51427       put4byte(&pBt->pPage1->aData[28], nFin);
51428       sqlite3PagerTruncateImage(pBt->pPager, nFin);
51429       pBt->nPage = nFin;
51430     }
51431     if( rc!=SQLITE_OK ){
51432       sqlite3PagerRollback(pPager);
51433     }
51434   }
51435
51436   assert( nRef==sqlite3PagerRefcount(pPager) );
51437   return rc;
51438 }
51439
51440 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51441 # define setChildPtrmaps(x) SQLITE_OK
51442 #endif
51443
51444 /*
51445 ** This routine does the first phase of a two-phase commit.  This routine
51446 ** causes a rollback journal to be created (if it does not already exist)
51447 ** and populated with enough information so that if a power loss occurs
51448 ** the database can be restored to its original state by playing back
51449 ** the journal.  Then the contents of the journal are flushed out to
51450 ** the disk.  After the journal is safely on oxide, the changes to the
51451 ** database are written into the database file and flushed to oxide.
51452 ** At the end of this call, the rollback journal still exists on the
51453 ** disk and we are still holding all locks, so the transaction has not
51454 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51455 ** commit process.
51456 **
51457 ** This call is a no-op if no write-transaction is currently active on pBt.
51458 **
51459 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51460 ** the name of a master journal file that should be written into the
51461 ** individual journal file, or is NULL, indicating no master journal file 
51462 ** (single database transaction).
51463 **
51464 ** When this is called, the master journal should already have been
51465 ** created, populated with this journal pointer and synced to disk.
51466 **
51467 ** Once this is routine has returned, the only thing required to commit
51468 ** the write-transaction for this database file is to delete the journal.
51469 */
51470 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51471   int rc = SQLITE_OK;
51472   if( p->inTrans==TRANS_WRITE ){
51473     BtShared *pBt = p->pBt;
51474     sqlite3BtreeEnter(p);
51475 #ifndef SQLITE_OMIT_AUTOVACUUM
51476     if( pBt->autoVacuum ){
51477       rc = autoVacuumCommit(pBt);
51478       if( rc!=SQLITE_OK ){
51479         sqlite3BtreeLeave(p);
51480         return rc;
51481       }
51482     }
51483 #endif
51484     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51485     sqlite3BtreeLeave(p);
51486   }
51487   return rc;
51488 }
51489
51490 /*
51491 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51492 ** at the conclusion of a transaction.
51493 */
51494 static void btreeEndTransaction(Btree *p){
51495   BtShared *pBt = p->pBt;
51496   assert( sqlite3BtreeHoldsMutex(p) );
51497
51498   btreeClearHasContent(pBt);
51499   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51500     /* If there are other active statements that belong to this database
51501     ** handle, downgrade to a read-only transaction. The other statements
51502     ** may still be reading from the database.  */
51503     downgradeAllSharedCacheTableLocks(p);
51504     p->inTrans = TRANS_READ;
51505   }else{
51506     /* If the handle had any kind of transaction open, decrement the 
51507     ** transaction count of the shared btree. If the transaction count 
51508     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51509     ** call below will unlock the pager.  */
51510     if( p->inTrans!=TRANS_NONE ){
51511       clearAllSharedCacheTableLocks(p);
51512       pBt->nTransaction--;
51513       if( 0==pBt->nTransaction ){
51514         pBt->inTransaction = TRANS_NONE;
51515       }
51516     }
51517
51518     /* Set the current transaction state to TRANS_NONE and unlock the 
51519     ** pager if this call closed the only read or write transaction.  */
51520     p->inTrans = TRANS_NONE;
51521     unlockBtreeIfUnused(pBt);
51522   }
51523
51524   btreeIntegrity(p);
51525 }
51526
51527 /*
51528 ** Commit the transaction currently in progress.
51529 **
51530 ** This routine implements the second phase of a 2-phase commit.  The
51531 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51532 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
51533 ** routine did all the work of writing information out to disk and flushing the
51534 ** contents so that they are written onto the disk platter.  All this
51535 ** routine has to do is delete or truncate or zero the header in the
51536 ** the rollback journal (which causes the transaction to commit) and
51537 ** drop locks.
51538 **
51539 ** Normally, if an error occurs while the pager layer is attempting to 
51540 ** finalize the underlying journal file, this function returns an error and
51541 ** the upper layer will attempt a rollback. However, if the second argument
51542 ** is non-zero then this b-tree transaction is part of a multi-file 
51543 ** transaction. In this case, the transaction has already been committed 
51544 ** (by deleting a master journal file) and the caller will ignore this 
51545 ** functions return code. So, even if an error occurs in the pager layer,
51546 ** reset the b-tree objects internal state to indicate that the write
51547 ** transaction has been closed. This is quite safe, as the pager will have
51548 ** transitioned to the error state.
51549 **
51550 ** This will release the write lock on the database file.  If there
51551 ** are no active cursors, it also releases the read lock.
51552 */
51553 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51554
51555   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51556   sqlite3BtreeEnter(p);
51557   btreeIntegrity(p);
51558
51559   /* If the handle has a write-transaction open, commit the shared-btrees 
51560   ** transaction and set the shared state to TRANS_READ.
51561   */
51562   if( p->inTrans==TRANS_WRITE ){
51563     int rc;
51564     BtShared *pBt = p->pBt;
51565     assert( pBt->inTransaction==TRANS_WRITE );
51566     assert( pBt->nTransaction>0 );
51567     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51568     if( rc!=SQLITE_OK && bCleanup==0 ){
51569       sqlite3BtreeLeave(p);
51570       return rc;
51571     }
51572     pBt->inTransaction = TRANS_READ;
51573   }
51574
51575   btreeEndTransaction(p);
51576   sqlite3BtreeLeave(p);
51577   return SQLITE_OK;
51578 }
51579
51580 /*
51581 ** Do both phases of a commit.
51582 */
51583 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51584   int rc;
51585   sqlite3BtreeEnter(p);
51586   rc = sqlite3BtreeCommitPhaseOne(p, 0);
51587   if( rc==SQLITE_OK ){
51588     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51589   }
51590   sqlite3BtreeLeave(p);
51591   return rc;
51592 }
51593
51594 #ifndef NDEBUG
51595 /*
51596 ** Return the number of write-cursors open on this handle. This is for use
51597 ** in assert() expressions, so it is only compiled if NDEBUG is not
51598 ** defined.
51599 **
51600 ** For the purposes of this routine, a write-cursor is any cursor that
51601 ** is capable of writing to the databse.  That means the cursor was
51602 ** originally opened for writing and the cursor has not be disabled
51603 ** by having its state changed to CURSOR_FAULT.
51604 */
51605 static int countWriteCursors(BtShared *pBt){
51606   BtCursor *pCur;
51607   int r = 0;
51608   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51609     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
51610   }
51611   return r;
51612 }
51613 #endif
51614
51615 /*
51616 ** This routine sets the state to CURSOR_FAULT and the error
51617 ** code to errCode for every cursor on BtShared that pBtree
51618 ** references.
51619 **
51620 ** Every cursor is tripped, including cursors that belong
51621 ** to other database connections that happen to be sharing
51622 ** the cache with pBtree.
51623 **
51624 ** This routine gets called when a rollback occurs.
51625 ** All cursors using the same cache must be tripped
51626 ** to prevent them from trying to use the btree after
51627 ** the rollback.  The rollback may have deleted tables
51628 ** or moved root pages, so it is not sufficient to
51629 ** save the state of the cursor.  The cursor must be
51630 ** invalidated.
51631 */
51632 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51633   BtCursor *p;
51634   if( pBtree==0 ) return;
51635   sqlite3BtreeEnter(pBtree);
51636   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51637     int i;
51638     sqlite3BtreeClearCursor(p);
51639     p->eState = CURSOR_FAULT;
51640     p->skipNext = errCode;
51641     for(i=0; i<=p->iPage; i++){
51642       releasePage(p->apPage[i]);
51643       p->apPage[i] = 0;
51644     }
51645   }
51646   sqlite3BtreeLeave(pBtree);
51647 }
51648
51649 /*
51650 ** Rollback the transaction in progress.  All cursors will be
51651 ** invalided by this operation.  Any attempt to use a cursor
51652 ** that was open at the beginning of this operation will result
51653 ** in an error.
51654 **
51655 ** This will release the write lock on the database file.  If there
51656 ** are no active cursors, it also releases the read lock.
51657 */
51658 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
51659   int rc;
51660   BtShared *pBt = p->pBt;
51661   MemPage *pPage1;
51662
51663   sqlite3BtreeEnter(p);
51664   if( tripCode==SQLITE_OK ){
51665     rc = tripCode = saveAllCursors(pBt, 0, 0);
51666   }else{
51667     rc = SQLITE_OK;
51668   }
51669   if( tripCode ){
51670     sqlite3BtreeTripAllCursors(p, tripCode);
51671   }
51672   btreeIntegrity(p);
51673
51674   if( p->inTrans==TRANS_WRITE ){
51675     int rc2;
51676
51677     assert( TRANS_WRITE==pBt->inTransaction );
51678     rc2 = sqlite3PagerRollback(pBt->pPager);
51679     if( rc2!=SQLITE_OK ){
51680       rc = rc2;
51681     }
51682
51683     /* The rollback may have destroyed the pPage1->aData value.  So
51684     ** call btreeGetPage() on page 1 again to make
51685     ** sure pPage1->aData is set correctly. */
51686     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51687       int nPage = get4byte(28+(u8*)pPage1->aData);
51688       testcase( nPage==0 );
51689       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51690       testcase( pBt->nPage!=nPage );
51691       pBt->nPage = nPage;
51692       releasePage(pPage1);
51693     }
51694     assert( countWriteCursors(pBt)==0 );
51695     pBt->inTransaction = TRANS_READ;
51696   }
51697
51698   btreeEndTransaction(p);
51699   sqlite3BtreeLeave(p);
51700   return rc;
51701 }
51702
51703 /*
51704 ** Start a statement subtransaction. The subtransaction can can be rolled
51705 ** back independently of the main transaction. You must start a transaction 
51706 ** before starting a subtransaction. The subtransaction is ended automatically 
51707 ** if the main transaction commits or rolls back.
51708 **
51709 ** Statement subtransactions are used around individual SQL statements
51710 ** that are contained within a BEGIN...COMMIT block.  If a constraint
51711 ** error occurs within the statement, the effect of that one statement
51712 ** can be rolled back without having to rollback the entire transaction.
51713 **
51714 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51715 ** value passed as the second parameter is the total number of savepoints,
51716 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51717 ** are no active savepoints and no other statement-transactions open,
51718 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51719 ** using the sqlite3BtreeSavepoint() function.
51720 */
51721 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51722   int rc;
51723   BtShared *pBt = p->pBt;
51724   sqlite3BtreeEnter(p);
51725   assert( p->inTrans==TRANS_WRITE );
51726   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
51727   assert( iStatement>0 );
51728   assert( iStatement>p->db->nSavepoint );
51729   assert( pBt->inTransaction==TRANS_WRITE );
51730   /* At the pager level, a statement transaction is a savepoint with
51731   ** an index greater than all savepoints created explicitly using
51732   ** SQL statements. It is illegal to open, release or rollback any
51733   ** such savepoints while the statement transaction savepoint is active.
51734   */
51735   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51736   sqlite3BtreeLeave(p);
51737   return rc;
51738 }
51739
51740 /*
51741 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51742 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51743 ** savepoint identified by parameter iSavepoint, depending on the value 
51744 ** of op.
51745 **
51746 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51747 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
51748 ** contents of the entire transaction are rolled back. This is different
51749 ** from a normal transaction rollback, as no locks are released and the
51750 ** transaction remains open.
51751 */
51752 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51753   int rc = SQLITE_OK;
51754   if( p && p->inTrans==TRANS_WRITE ){
51755     BtShared *pBt = p->pBt;
51756     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51757     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51758     sqlite3BtreeEnter(p);
51759     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51760     if( rc==SQLITE_OK ){
51761       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
51762         pBt->nPage = 0;
51763       }
51764       rc = newDatabase(pBt);
51765       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51766
51767       /* The database size was written into the offset 28 of the header
51768       ** when the transaction started, so we know that the value at offset
51769       ** 28 is nonzero. */
51770       assert( pBt->nPage>0 );
51771     }
51772     sqlite3BtreeLeave(p);
51773   }
51774   return rc;
51775 }
51776
51777 /*
51778 ** Create a new cursor for the BTree whose root is on the page
51779 ** iTable. If a read-only cursor is requested, it is assumed that
51780 ** the caller already has at least a read-only transaction open
51781 ** on the database already. If a write-cursor is requested, then
51782 ** the caller is assumed to have an open write transaction.
51783 **
51784 ** If wrFlag==0, then the cursor can only be used for reading.
51785 ** If wrFlag==1, then the cursor can be used for reading or for
51786 ** writing if other conditions for writing are also met.  These
51787 ** are the conditions that must be met in order for writing to
51788 ** be allowed:
51789 **
51790 ** 1:  The cursor must have been opened with wrFlag==1
51791 **
51792 ** 2:  Other database connections that share the same pager cache
51793 **     but which are not in the READ_UNCOMMITTED state may not have
51794 **     cursors open with wrFlag==0 on the same table.  Otherwise
51795 **     the changes made by this write cursor would be visible to
51796 **     the read cursors in the other database connection.
51797 **
51798 ** 3:  The database must be writable (not on read-only media)
51799 **
51800 ** 4:  There must be an active transaction.
51801 **
51802 ** No checking is done to make sure that page iTable really is the
51803 ** root page of a b-tree.  If it is not, then the cursor acquired
51804 ** will not work correctly.
51805 **
51806 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51807 ** on pCur to initialize the memory space prior to invoking this routine.
51808 */
51809 static int btreeCursor(
51810   Btree *p,                              /* The btree */
51811   int iTable,                            /* Root page of table to open */
51812   int wrFlag,                            /* 1 to write. 0 read-only */
51813   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
51814   BtCursor *pCur                         /* Space for new cursor */
51815 ){
51816   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
51817
51818   assert( sqlite3BtreeHoldsMutex(p) );
51819   assert( wrFlag==0 || wrFlag==1 );
51820
51821   /* The following assert statements verify that if this is a sharable 
51822   ** b-tree database, the connection is holding the required table locks, 
51823   ** and that no other connection has any open cursor that conflicts with 
51824   ** this lock.  */
51825   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51826   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51827
51828   /* Assert that the caller has opened the required transaction. */
51829   assert( p->inTrans>TRANS_NONE );
51830   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51831   assert( pBt->pPage1 && pBt->pPage1->aData );
51832
51833   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
51834     return SQLITE_READONLY;
51835   }
51836   if( iTable==1 && btreePagecount(pBt)==0 ){
51837     assert( wrFlag==0 );
51838     iTable = 0;
51839   }
51840
51841   /* Now that no other errors can occur, finish filling in the BtCursor
51842   ** variables and link the cursor into the BtShared list.  */
51843   pCur->pgnoRoot = (Pgno)iTable;
51844   pCur->iPage = -1;
51845   pCur->pKeyInfo = pKeyInfo;
51846   pCur->pBtree = p;
51847   pCur->pBt = pBt;
51848   pCur->wrFlag = (u8)wrFlag;
51849   pCur->pNext = pBt->pCursor;
51850   if( pCur->pNext ){
51851     pCur->pNext->pPrev = pCur;
51852   }
51853   pBt->pCursor = pCur;
51854   pCur->eState = CURSOR_INVALID;
51855   pCur->cachedRowid = 0;
51856   return SQLITE_OK;
51857 }
51858 SQLITE_PRIVATE int sqlite3BtreeCursor(
51859   Btree *p,                                   /* The btree */
51860   int iTable,                                 /* Root page of table to open */
51861   int wrFlag,                                 /* 1 to write. 0 read-only */
51862   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51863   BtCursor *pCur                              /* Write new cursor here */
51864 ){
51865   int rc;
51866   sqlite3BtreeEnter(p);
51867   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51868   sqlite3BtreeLeave(p);
51869   return rc;
51870 }
51871
51872 /*
51873 ** Return the size of a BtCursor object in bytes.
51874 **
51875 ** This interfaces is needed so that users of cursors can preallocate
51876 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51877 ** to users so they cannot do the sizeof() themselves - they must call
51878 ** this routine.
51879 */
51880 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51881   return ROUND8(sizeof(BtCursor));
51882 }
51883
51884 /*
51885 ** Initialize memory that will be converted into a BtCursor object.
51886 **
51887 ** The simple approach here would be to memset() the entire object
51888 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
51889 ** do not need to be zeroed and they are large, so we can save a lot
51890 ** of run-time by skipping the initialization of those elements.
51891 */
51892 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
51893   memset(p, 0, offsetof(BtCursor, iPage));
51894 }
51895
51896 /*
51897 ** Set the cached rowid value of every cursor in the same database file
51898 ** as pCur and having the same root page number as pCur.  The value is
51899 ** set to iRowid.
51900 **
51901 ** Only positive rowid values are considered valid for this cache.
51902 ** The cache is initialized to zero, indicating an invalid cache.
51903 ** A btree will work fine with zero or negative rowids.  We just cannot
51904 ** cache zero or negative rowids, which means tables that use zero or
51905 ** negative rowids might run a little slower.  But in practice, zero
51906 ** or negative rowids are very uncommon so this should not be a problem.
51907 */
51908 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
51909   BtCursor *p;
51910   for(p=pCur->pBt->pCursor; p; p=p->pNext){
51911     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
51912   }
51913   assert( pCur->cachedRowid==iRowid );
51914 }
51915
51916 /*
51917 ** Return the cached rowid for the given cursor.  A negative or zero
51918 ** return value indicates that the rowid cache is invalid and should be
51919 ** ignored.  If the rowid cache has never before been set, then a
51920 ** zero is returned.
51921 */
51922 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
51923   return pCur->cachedRowid;
51924 }
51925
51926 /*
51927 ** Close a cursor.  The read lock on the database file is released
51928 ** when the last cursor is closed.
51929 */
51930 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
51931   Btree *pBtree = pCur->pBtree;
51932   if( pBtree ){
51933     int i;
51934     BtShared *pBt = pCur->pBt;
51935     sqlite3BtreeEnter(pBtree);
51936     sqlite3BtreeClearCursor(pCur);
51937     if( pCur->pPrev ){
51938       pCur->pPrev->pNext = pCur->pNext;
51939     }else{
51940       pBt->pCursor = pCur->pNext;
51941     }
51942     if( pCur->pNext ){
51943       pCur->pNext->pPrev = pCur->pPrev;
51944     }
51945     for(i=0; i<=pCur->iPage; i++){
51946       releasePage(pCur->apPage[i]);
51947     }
51948     unlockBtreeIfUnused(pBt);
51949     invalidateOverflowCache(pCur);
51950     /* sqlite3_free(pCur); */
51951     sqlite3BtreeLeave(pBtree);
51952   }
51953   return SQLITE_OK;
51954 }
51955
51956 /*
51957 ** Make sure the BtCursor* given in the argument has a valid
51958 ** BtCursor.info structure.  If it is not already valid, call
51959 ** btreeParseCell() to fill it in.
51960 **
51961 ** BtCursor.info is a cache of the information in the current cell.
51962 ** Using this cache reduces the number of calls to btreeParseCell().
51963 **
51964 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
51965 ** compiler to crash when getCellInfo() is implemented as a macro.
51966 ** But there is a measureable speed advantage to using the macro on gcc
51967 ** (when less compiler optimizations like -Os or -O0 are used and the
51968 ** compiler is not doing agressive inlining.)  So we use a real function
51969 ** for MSVC and a macro for everything else.  Ticket #2457.
51970 */
51971 #ifndef NDEBUG
51972   static void assertCellInfo(BtCursor *pCur){
51973     CellInfo info;
51974     int iPage = pCur->iPage;
51975     memset(&info, 0, sizeof(info));
51976     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
51977     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
51978   }
51979 #else
51980   #define assertCellInfo(x)
51981 #endif
51982 #ifdef _MSC_VER
51983   /* Use a real function in MSVC to work around bugs in that compiler. */
51984   static void getCellInfo(BtCursor *pCur){
51985     if( pCur->info.nSize==0 ){
51986       int iPage = pCur->iPage;
51987       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
51988       pCur->validNKey = 1;
51989     }else{
51990       assertCellInfo(pCur);
51991     }
51992   }
51993 #else /* if not _MSC_VER */
51994   /* Use a macro in all other compilers so that the function is inlined */
51995 #define getCellInfo(pCur)                                                      \
51996   if( pCur->info.nSize==0 ){                                                   \
51997     int iPage = pCur->iPage;                                                   \
51998     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
51999     pCur->validNKey = 1;                                                       \
52000   }else{                                                                       \
52001     assertCellInfo(pCur);                                                      \
52002   }
52003 #endif /* _MSC_VER */
52004
52005 #ifndef NDEBUG  /* The next routine used only within assert() statements */
52006 /*
52007 ** Return true if the given BtCursor is valid.  A valid cursor is one
52008 ** that is currently pointing to a row in a (non-empty) table.
52009 ** This is a verification routine is used only within assert() statements.
52010 */
52011 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
52012   return pCur && pCur->eState==CURSOR_VALID;
52013 }
52014 #endif /* NDEBUG */
52015
52016 /*
52017 ** Set *pSize to the size of the buffer needed to hold the value of
52018 ** the key for the current entry.  If the cursor is not pointing
52019 ** to a valid entry, *pSize is set to 0. 
52020 **
52021 ** For a table with the INTKEY flag set, this routine returns the key
52022 ** itself, not the number of bytes in the key.
52023 **
52024 ** The caller must position the cursor prior to invoking this routine.
52025 ** 
52026 ** This routine cannot fail.  It always returns SQLITE_OK.  
52027 */
52028 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
52029   assert( cursorHoldsMutex(pCur) );
52030   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
52031   if( pCur->eState!=CURSOR_VALID ){
52032     *pSize = 0;
52033   }else{
52034     getCellInfo(pCur);
52035     *pSize = pCur->info.nKey;
52036   }
52037   return SQLITE_OK;
52038 }
52039
52040 /*
52041 ** Set *pSize to the number of bytes of data in the entry the
52042 ** cursor currently points to.
52043 **
52044 ** The caller must guarantee that the cursor is pointing to a non-NULL
52045 ** valid entry.  In other words, the calling procedure must guarantee
52046 ** that the cursor has Cursor.eState==CURSOR_VALID.
52047 **
52048 ** Failure is not possible.  This function always returns SQLITE_OK.
52049 ** It might just as well be a procedure (returning void) but we continue
52050 ** to return an integer result code for historical reasons.
52051 */
52052 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
52053   assert( cursorHoldsMutex(pCur) );
52054   assert( pCur->eState==CURSOR_VALID );
52055   getCellInfo(pCur);
52056   *pSize = pCur->info.nData;
52057   return SQLITE_OK;
52058 }
52059
52060 /*
52061 ** Given the page number of an overflow page in the database (parameter
52062 ** ovfl), this function finds the page number of the next page in the 
52063 ** linked list of overflow pages. If possible, it uses the auto-vacuum
52064 ** pointer-map data instead of reading the content of page ovfl to do so. 
52065 **
52066 ** If an error occurs an SQLite error code is returned. Otherwise:
52067 **
52068 ** The page number of the next overflow page in the linked list is 
52069 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
52070 ** list, *pPgnoNext is set to zero. 
52071 **
52072 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
52073 ** to page number pOvfl was obtained, then *ppPage is set to point to that
52074 ** reference. It is the responsibility of the caller to call releasePage()
52075 ** on *ppPage to free the reference. In no reference was obtained (because
52076 ** the pointer-map was used to obtain the value for *pPgnoNext), then
52077 ** *ppPage is set to zero.
52078 */
52079 static int getOverflowPage(
52080   BtShared *pBt,               /* The database file */
52081   Pgno ovfl,                   /* Current overflow page number */
52082   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
52083   Pgno *pPgnoNext              /* OUT: Next overflow page number */
52084 ){
52085   Pgno next = 0;
52086   MemPage *pPage = 0;
52087   int rc = SQLITE_OK;
52088
52089   assert( sqlite3_mutex_held(pBt->mutex) );
52090   assert(pPgnoNext);
52091
52092 #ifndef SQLITE_OMIT_AUTOVACUUM
52093   /* Try to find the next page in the overflow list using the
52094   ** autovacuum pointer-map pages. Guess that the next page in 
52095   ** the overflow list is page number (ovfl+1). If that guess turns 
52096   ** out to be wrong, fall back to loading the data of page 
52097   ** number ovfl to determine the next page number.
52098   */
52099   if( pBt->autoVacuum ){
52100     Pgno pgno;
52101     Pgno iGuess = ovfl+1;
52102     u8 eType;
52103
52104     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
52105       iGuess++;
52106     }
52107
52108     if( iGuess<=btreePagecount(pBt) ){
52109       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
52110       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
52111         next = iGuess;
52112         rc = SQLITE_DONE;
52113       }
52114     }
52115   }
52116 #endif
52117
52118   assert( next==0 || rc==SQLITE_DONE );
52119   if( rc==SQLITE_OK ){
52120     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
52121     assert( rc==SQLITE_OK || pPage==0 );
52122     if( rc==SQLITE_OK ){
52123       next = get4byte(pPage->aData);
52124     }
52125   }
52126
52127   *pPgnoNext = next;
52128   if( ppPage ){
52129     *ppPage = pPage;
52130   }else{
52131     releasePage(pPage);
52132   }
52133   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
52134 }
52135
52136 /*
52137 ** Copy data from a buffer to a page, or from a page to a buffer.
52138 **
52139 ** pPayload is a pointer to data stored on database page pDbPage.
52140 ** If argument eOp is false, then nByte bytes of data are copied
52141 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
52142 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
52143 ** of data are copied from the buffer pBuf to pPayload.
52144 **
52145 ** SQLITE_OK is returned on success, otherwise an error code.
52146 */
52147 static int copyPayload(
52148   void *pPayload,           /* Pointer to page data */
52149   void *pBuf,               /* Pointer to buffer */
52150   int nByte,                /* Number of bytes to copy */
52151   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
52152   DbPage *pDbPage           /* Page containing pPayload */
52153 ){
52154   if( eOp ){
52155     /* Copy data from buffer to page (a write operation) */
52156     int rc = sqlite3PagerWrite(pDbPage);
52157     if( rc!=SQLITE_OK ){
52158       return rc;
52159     }
52160     memcpy(pPayload, pBuf, nByte);
52161   }else{
52162     /* Copy data from page to buffer (a read operation) */
52163     memcpy(pBuf, pPayload, nByte);
52164   }
52165   return SQLITE_OK;
52166 }
52167
52168 /*
52169 ** This function is used to read or overwrite payload information
52170 ** for the entry that the pCur cursor is pointing to. If the eOp
52171 ** parameter is 0, this is a read operation (data copied into
52172 ** buffer pBuf). If it is non-zero, a write (data copied from
52173 ** buffer pBuf).
52174 **
52175 ** A total of "amt" bytes are read or written beginning at "offset".
52176 ** Data is read to or from the buffer pBuf.
52177 **
52178 ** The content being read or written might appear on the main page
52179 ** or be scattered out on multiple overflow pages.
52180 **
52181 ** If the BtCursor.isIncrblobHandle flag is set, and the current
52182 ** cursor entry uses one or more overflow pages, this function
52183 ** allocates space for and lazily popluates the overflow page-list 
52184 ** cache array (BtCursor.aOverflow). Subsequent calls use this
52185 ** cache to make seeking to the supplied offset more efficient.
52186 **
52187 ** Once an overflow page-list cache has been allocated, it may be
52188 ** invalidated if some other cursor writes to the same table, or if
52189 ** the cursor is moved to a different row. Additionally, in auto-vacuum
52190 ** mode, the following events may invalidate an overflow page-list cache.
52191 **
52192 **   * An incremental vacuum,
52193 **   * A commit in auto_vacuum="full" mode,
52194 **   * Creating a table (may require moving an overflow page).
52195 */
52196 static int accessPayload(
52197   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52198   u32 offset,          /* Begin reading this far into payload */
52199   u32 amt,             /* Read this many bytes */
52200   unsigned char *pBuf, /* Write the bytes into this buffer */ 
52201   int eOp              /* zero to read. non-zero to write. */
52202 ){
52203   unsigned char *aPayload;
52204   int rc = SQLITE_OK;
52205   u32 nKey;
52206   int iIdx = 0;
52207   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
52208   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
52209
52210   assert( pPage );
52211   assert( pCur->eState==CURSOR_VALID );
52212   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52213   assert( cursorHoldsMutex(pCur) );
52214
52215   getCellInfo(pCur);
52216   aPayload = pCur->info.pCell + pCur->info.nHeader;
52217   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
52218
52219   if( NEVER(offset+amt > nKey+pCur->info.nData) 
52220    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
52221   ){
52222     /* Trying to read or write past the end of the data is an error */
52223     return SQLITE_CORRUPT_BKPT;
52224   }
52225
52226   /* Check if data must be read/written to/from the btree page itself. */
52227   if( offset<pCur->info.nLocal ){
52228     int a = amt;
52229     if( a+offset>pCur->info.nLocal ){
52230       a = pCur->info.nLocal - offset;
52231     }
52232     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
52233     offset = 0;
52234     pBuf += a;
52235     amt -= a;
52236   }else{
52237     offset -= pCur->info.nLocal;
52238   }
52239
52240   if( rc==SQLITE_OK && amt>0 ){
52241     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
52242     Pgno nextPage;
52243
52244     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
52245
52246 #ifndef SQLITE_OMIT_INCRBLOB
52247     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
52248     ** has not been allocated, allocate it now. The array is sized at
52249     ** one entry for each overflow page in the overflow chain. The
52250     ** page number of the first overflow page is stored in aOverflow[0],
52251     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
52252     ** (the cache is lazily populated).
52253     */
52254     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
52255       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
52256       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
52257       /* nOvfl is always positive.  If it were zero, fetchPayload would have
52258       ** been used instead of this routine. */
52259       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
52260         rc = SQLITE_NOMEM;
52261       }
52262     }
52263
52264     /* If the overflow page-list cache has been allocated and the
52265     ** entry for the first required overflow page is valid, skip
52266     ** directly to it.
52267     */
52268     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
52269       iIdx = (offset/ovflSize);
52270       nextPage = pCur->aOverflow[iIdx];
52271       offset = (offset%ovflSize);
52272     }
52273 #endif
52274
52275     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
52276
52277 #ifndef SQLITE_OMIT_INCRBLOB
52278       /* If required, populate the overflow page-list cache. */
52279       if( pCur->aOverflow ){
52280         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
52281         pCur->aOverflow[iIdx] = nextPage;
52282       }
52283 #endif
52284
52285       if( offset>=ovflSize ){
52286         /* The only reason to read this page is to obtain the page
52287         ** number for the next page in the overflow chain. The page
52288         ** data is not required. So first try to lookup the overflow
52289         ** page-list cache, if any, then fall back to the getOverflowPage()
52290         ** function.
52291         */
52292 #ifndef SQLITE_OMIT_INCRBLOB
52293         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
52294           nextPage = pCur->aOverflow[iIdx+1];
52295         } else 
52296 #endif
52297           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
52298         offset -= ovflSize;
52299       }else{
52300         /* Need to read this page properly. It contains some of the
52301         ** range of data that is being read (eOp==0) or written (eOp!=0).
52302         */
52303 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52304         sqlite3_file *fd;
52305 #endif
52306         int a = amt;
52307         if( a + offset > ovflSize ){
52308           a = ovflSize - offset;
52309         }
52310
52311 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52312         /* If all the following are true:
52313         **
52314         **   1) this is a read operation, and 
52315         **   2) data is required from the start of this overflow page, and
52316         **   3) the database is file-backed, and
52317         **   4) there is no open write-transaction, and
52318         **   5) the database is not a WAL database,
52319         **
52320         ** then data can be read directly from the database file into the
52321         ** output buffer, bypassing the page-cache altogether. This speeds
52322         ** up loading large records that span many overflow pages.
52323         */
52324         if( eOp==0                                             /* (1) */
52325          && offset==0                                          /* (2) */
52326          && pBt->inTransaction==TRANS_READ                     /* (4) */
52327          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
52328          && pBt->pPage1->aData[19]==0x01                       /* (5) */
52329         ){
52330           u8 aSave[4];
52331           u8 *aWrite = &pBuf[-4];
52332           memcpy(aSave, aWrite, 4);
52333           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
52334           nextPage = get4byte(aWrite);
52335           memcpy(aWrite, aSave, 4);
52336         }else
52337 #endif
52338
52339         {
52340           DbPage *pDbPage;
52341           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
52342           if( rc==SQLITE_OK ){
52343             aPayload = sqlite3PagerGetData(pDbPage);
52344             nextPage = get4byte(aPayload);
52345             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
52346             sqlite3PagerUnref(pDbPage);
52347             offset = 0;
52348           }
52349         }
52350         amt -= a;
52351         pBuf += a;
52352       }
52353     }
52354   }
52355
52356   if( rc==SQLITE_OK && amt>0 ){
52357     return SQLITE_CORRUPT_BKPT;
52358   }
52359   return rc;
52360 }
52361
52362 /*
52363 ** Read part of the key associated with cursor pCur.  Exactly
52364 ** "amt" bytes will be transfered into pBuf[].  The transfer
52365 ** begins at "offset".
52366 **
52367 ** The caller must ensure that pCur is pointing to a valid row
52368 ** in the table.
52369 **
52370 ** Return SQLITE_OK on success or an error code if anything goes
52371 ** wrong.  An error is returned if "offset+amt" is larger than
52372 ** the available payload.
52373 */
52374 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52375   assert( cursorHoldsMutex(pCur) );
52376   assert( pCur->eState==CURSOR_VALID );
52377   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52378   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52379   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
52380 }
52381
52382 /*
52383 ** Read part of the data associated with cursor pCur.  Exactly
52384 ** "amt" bytes will be transfered into pBuf[].  The transfer
52385 ** begins at "offset".
52386 **
52387 ** Return SQLITE_OK on success or an error code if anything goes
52388 ** wrong.  An error is returned if "offset+amt" is larger than
52389 ** the available payload.
52390 */
52391 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52392   int rc;
52393
52394 #ifndef SQLITE_OMIT_INCRBLOB
52395   if ( pCur->eState==CURSOR_INVALID ){
52396     return SQLITE_ABORT;
52397   }
52398 #endif
52399
52400   assert( cursorHoldsMutex(pCur) );
52401   rc = restoreCursorPosition(pCur);
52402   if( rc==SQLITE_OK ){
52403     assert( pCur->eState==CURSOR_VALID );
52404     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52405     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52406     rc = accessPayload(pCur, offset, amt, pBuf, 0);
52407   }
52408   return rc;
52409 }
52410
52411 /*
52412 ** Return a pointer to payload information from the entry that the 
52413 ** pCur cursor is pointing to.  The pointer is to the beginning of
52414 ** the key if skipKey==0 and it points to the beginning of data if
52415 ** skipKey==1.  The number of bytes of available key/data is written
52416 ** into *pAmt.  If *pAmt==0, then the value returned will not be
52417 ** a valid pointer.
52418 **
52419 ** This routine is an optimization.  It is common for the entire key
52420 ** and data to fit on the local page and for there to be no overflow
52421 ** pages.  When that is so, this routine can be used to access the
52422 ** key and data without making a copy.  If the key and/or data spills
52423 ** onto overflow pages, then accessPayload() must be used to reassemble
52424 ** the key/data and copy it into a preallocated buffer.
52425 **
52426 ** The pointer returned by this routine looks directly into the cached
52427 ** page of the database.  The data might change or move the next time
52428 ** any btree routine is called.
52429 */
52430 static const unsigned char *fetchPayload(
52431   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52432   int *pAmt,           /* Write the number of available bytes here */
52433   int skipKey          /* read beginning at data if this is true */
52434 ){
52435   unsigned char *aPayload;
52436   MemPage *pPage;
52437   u32 nKey;
52438   u32 nLocal;
52439
52440   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52441   assert( pCur->eState==CURSOR_VALID );
52442   assert( cursorHoldsMutex(pCur) );
52443   pPage = pCur->apPage[pCur->iPage];
52444   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52445   if( NEVER(pCur->info.nSize==0) ){
52446     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52447                    &pCur->info);
52448   }
52449   aPayload = pCur->info.pCell;
52450   aPayload += pCur->info.nHeader;
52451   if( pPage->intKey ){
52452     nKey = 0;
52453   }else{
52454     nKey = (int)pCur->info.nKey;
52455   }
52456   if( skipKey ){
52457     aPayload += nKey;
52458     nLocal = pCur->info.nLocal - nKey;
52459   }else{
52460     nLocal = pCur->info.nLocal;
52461     assert( nLocal<=nKey );
52462   }
52463   *pAmt = nLocal;
52464   return aPayload;
52465 }
52466
52467
52468 /*
52469 ** For the entry that cursor pCur is point to, return as
52470 ** many bytes of the key or data as are available on the local
52471 ** b-tree page.  Write the number of available bytes into *pAmt.
52472 **
52473 ** The pointer returned is ephemeral.  The key/data may move
52474 ** or be destroyed on the next call to any Btree routine,
52475 ** including calls from other threads against the same cache.
52476 ** Hence, a mutex on the BtShared should be held prior to calling
52477 ** this routine.
52478 **
52479 ** These routines is used to get quick access to key and data
52480 ** in the common case where no overflow pages are used.
52481 */
52482 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52483   const void *p = 0;
52484   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52485   assert( cursorHoldsMutex(pCur) );
52486   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52487     p = (const void*)fetchPayload(pCur, pAmt, 0);
52488   }
52489   return p;
52490 }
52491 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52492   const void *p = 0;
52493   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52494   assert( cursorHoldsMutex(pCur) );
52495   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52496     p = (const void*)fetchPayload(pCur, pAmt, 1);
52497   }
52498   return p;
52499 }
52500
52501
52502 /*
52503 ** Move the cursor down to a new child page.  The newPgno argument is the
52504 ** page number of the child page to move to.
52505 **
52506 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52507 ** the new child page does not match the flags field of the parent (i.e.
52508 ** if an intkey page appears to be the parent of a non-intkey page, or
52509 ** vice-versa).
52510 */
52511 static int moveToChild(BtCursor *pCur, u32 newPgno){
52512   int rc;
52513   int i = pCur->iPage;
52514   MemPage *pNewPage;
52515   BtShared *pBt = pCur->pBt;
52516
52517   assert( cursorHoldsMutex(pCur) );
52518   assert( pCur->eState==CURSOR_VALID );
52519   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52520   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52521     return SQLITE_CORRUPT_BKPT;
52522   }
52523   rc = getAndInitPage(pBt, newPgno, &pNewPage);
52524   if( rc ) return rc;
52525   pCur->apPage[i+1] = pNewPage;
52526   pCur->aiIdx[i+1] = 0;
52527   pCur->iPage++;
52528
52529   pCur->info.nSize = 0;
52530   pCur->validNKey = 0;
52531   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52532     return SQLITE_CORRUPT_BKPT;
52533   }
52534   return SQLITE_OK;
52535 }
52536
52537 #if 0
52538 /*
52539 ** Page pParent is an internal (non-leaf) tree page. This function 
52540 ** asserts that page number iChild is the left-child if the iIdx'th
52541 ** cell in page pParent. Or, if iIdx is equal to the total number of
52542 ** cells in pParent, that page number iChild is the right-child of
52543 ** the page.
52544 */
52545 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52546   assert( iIdx<=pParent->nCell );
52547   if( iIdx==pParent->nCell ){
52548     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52549   }else{
52550     assert( get4byte(findCell(pParent, iIdx))==iChild );
52551   }
52552 }
52553 #else
52554 #  define assertParentIndex(x,y,z) 
52555 #endif
52556
52557 /*
52558 ** Move the cursor up to the parent page.
52559 **
52560 ** pCur->idx is set to the cell index that contains the pointer
52561 ** to the page we are coming from.  If we are coming from the
52562 ** right-most child page then pCur->idx is set to one more than
52563 ** the largest cell index.
52564 */
52565 static void moveToParent(BtCursor *pCur){
52566   assert( cursorHoldsMutex(pCur) );
52567   assert( pCur->eState==CURSOR_VALID );
52568   assert( pCur->iPage>0 );
52569   assert( pCur->apPage[pCur->iPage] );
52570
52571   /* UPDATE: It is actually possible for the condition tested by the assert
52572   ** below to be untrue if the database file is corrupt. This can occur if
52573   ** one cursor has modified page pParent while a reference to it is held 
52574   ** by a second cursor. Which can only happen if a single page is linked
52575   ** into more than one b-tree structure in a corrupt database.  */
52576 #if 0
52577   assertParentIndex(
52578     pCur->apPage[pCur->iPage-1], 
52579     pCur->aiIdx[pCur->iPage-1], 
52580     pCur->apPage[pCur->iPage]->pgno
52581   );
52582 #endif
52583   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
52584
52585   releasePage(pCur->apPage[pCur->iPage]);
52586   pCur->iPage--;
52587   pCur->info.nSize = 0;
52588   pCur->validNKey = 0;
52589 }
52590
52591 /*
52592 ** Move the cursor to point to the root page of its b-tree structure.
52593 **
52594 ** If the table has a virtual root page, then the cursor is moved to point
52595 ** to the virtual root page instead of the actual root page. A table has a
52596 ** virtual root page when the actual root page contains no cells and a 
52597 ** single child page. This can only happen with the table rooted at page 1.
52598 **
52599 ** If the b-tree structure is empty, the cursor state is set to 
52600 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52601 ** cell located on the root (or virtual root) page and the cursor state
52602 ** is set to CURSOR_VALID.
52603 **
52604 ** If this function returns successfully, it may be assumed that the
52605 ** page-header flags indicate that the [virtual] root-page is the expected 
52606 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52607 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52608 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
52609 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52610 ** b-tree).
52611 */
52612 static int moveToRoot(BtCursor *pCur){
52613   MemPage *pRoot;
52614   int rc = SQLITE_OK;
52615   Btree *p = pCur->pBtree;
52616   BtShared *pBt = p->pBt;
52617
52618   assert( cursorHoldsMutex(pCur) );
52619   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52620   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
52621   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
52622   if( pCur->eState>=CURSOR_REQUIRESEEK ){
52623     if( pCur->eState==CURSOR_FAULT ){
52624       assert( pCur->skipNext!=SQLITE_OK );
52625       return pCur->skipNext;
52626     }
52627     sqlite3BtreeClearCursor(pCur);
52628   }
52629
52630   if( pCur->iPage>=0 ){
52631     int i;
52632     for(i=1; i<=pCur->iPage; i++){
52633       releasePage(pCur->apPage[i]);
52634     }
52635     pCur->iPage = 0;
52636   }else if( pCur->pgnoRoot==0 ){
52637     pCur->eState = CURSOR_INVALID;
52638     return SQLITE_OK;
52639   }else{
52640     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52641     if( rc!=SQLITE_OK ){
52642       pCur->eState = CURSOR_INVALID;
52643       return rc;
52644     }
52645     pCur->iPage = 0;
52646
52647     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52648     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52649     ** NULL, the caller expects a table b-tree. If this is not the case,
52650     ** return an SQLITE_CORRUPT error.  */
52651     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52652     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52653       return SQLITE_CORRUPT_BKPT;
52654     }
52655   }
52656
52657   /* Assert that the root page is of the correct type. This must be the
52658   ** case as the call to this function that loaded the root-page (either
52659   ** this call or a previous invocation) would have detected corruption 
52660   ** if the assumption were not true, and it is not possible for the flags 
52661   ** byte to have been modified while this cursor is holding a reference
52662   ** to the page.  */
52663   pRoot = pCur->apPage[0];
52664   assert( pRoot->pgno==pCur->pgnoRoot );
52665   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52666
52667   pCur->aiIdx[0] = 0;
52668   pCur->info.nSize = 0;
52669   pCur->atLast = 0;
52670   pCur->validNKey = 0;
52671
52672   if( pRoot->nCell==0 && !pRoot->leaf ){
52673     Pgno subpage;
52674     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52675     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52676     pCur->eState = CURSOR_VALID;
52677     rc = moveToChild(pCur, subpage);
52678   }else{
52679     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52680   }
52681   return rc;
52682 }
52683
52684 /*
52685 ** Move the cursor down to the left-most leaf entry beneath the
52686 ** entry to which it is currently pointing.
52687 **
52688 ** The left-most leaf is the one with the smallest key - the first
52689 ** in ascending order.
52690 */
52691 static int moveToLeftmost(BtCursor *pCur){
52692   Pgno pgno;
52693   int rc = SQLITE_OK;
52694   MemPage *pPage;
52695
52696   assert( cursorHoldsMutex(pCur) );
52697   assert( pCur->eState==CURSOR_VALID );
52698   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52699     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52700     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52701     rc = moveToChild(pCur, pgno);
52702   }
52703   return rc;
52704 }
52705
52706 /*
52707 ** Move the cursor down to the right-most leaf entry beneath the
52708 ** page to which it is currently pointing.  Notice the difference
52709 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
52710 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52711 ** finds the right-most entry beneath the *page*.
52712 **
52713 ** The right-most entry is the one with the largest key - the last
52714 ** key in ascending order.
52715 */
52716 static int moveToRightmost(BtCursor *pCur){
52717   Pgno pgno;
52718   int rc = SQLITE_OK;
52719   MemPage *pPage = 0;
52720
52721   assert( cursorHoldsMutex(pCur) );
52722   assert( pCur->eState==CURSOR_VALID );
52723   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52724     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52725     pCur->aiIdx[pCur->iPage] = pPage->nCell;
52726     rc = moveToChild(pCur, pgno);
52727   }
52728   if( rc==SQLITE_OK ){
52729     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52730     pCur->info.nSize = 0;
52731     pCur->validNKey = 0;
52732   }
52733   return rc;
52734 }
52735
52736 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
52737 ** on success.  Set *pRes to 0 if the cursor actually points to something
52738 ** or set *pRes to 1 if the table is empty.
52739 */
52740 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52741   int rc;
52742
52743   assert( cursorHoldsMutex(pCur) );
52744   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52745   rc = moveToRoot(pCur);
52746   if( rc==SQLITE_OK ){
52747     if( pCur->eState==CURSOR_INVALID ){
52748       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52749       *pRes = 1;
52750     }else{
52751       assert( pCur->apPage[pCur->iPage]->nCell>0 );
52752       *pRes = 0;
52753       rc = moveToLeftmost(pCur);
52754     }
52755   }
52756   return rc;
52757 }
52758
52759 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
52760 ** on success.  Set *pRes to 0 if the cursor actually points to something
52761 ** or set *pRes to 1 if the table is empty.
52762 */
52763 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52764   int rc;
52765  
52766   assert( cursorHoldsMutex(pCur) );
52767   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52768
52769   /* If the cursor already points to the last entry, this is a no-op. */
52770   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52771 #ifdef SQLITE_DEBUG
52772     /* This block serves to assert() that the cursor really does point 
52773     ** to the last entry in the b-tree. */
52774     int ii;
52775     for(ii=0; ii<pCur->iPage; ii++){
52776       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52777     }
52778     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52779     assert( pCur->apPage[pCur->iPage]->leaf );
52780 #endif
52781     return SQLITE_OK;
52782   }
52783
52784   rc = moveToRoot(pCur);
52785   if( rc==SQLITE_OK ){
52786     if( CURSOR_INVALID==pCur->eState ){
52787       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52788       *pRes = 1;
52789     }else{
52790       assert( pCur->eState==CURSOR_VALID );
52791       *pRes = 0;
52792       rc = moveToRightmost(pCur);
52793       pCur->atLast = rc==SQLITE_OK ?1:0;
52794     }
52795   }
52796   return rc;
52797 }
52798
52799 /* Move the cursor so that it points to an entry near the key 
52800 ** specified by pIdxKey or intKey.   Return a success code.
52801 **
52802 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
52803 ** must be NULL.  For index tables, pIdxKey is used and intKey
52804 ** is ignored.
52805 **
52806 ** If an exact match is not found, then the cursor is always
52807 ** left pointing at a leaf page which would hold the entry if it
52808 ** were present.  The cursor might point to an entry that comes
52809 ** before or after the key.
52810 **
52811 ** An integer is written into *pRes which is the result of
52812 ** comparing the key with the entry to which the cursor is 
52813 ** pointing.  The meaning of the integer written into
52814 ** *pRes is as follows:
52815 **
52816 **     *pRes<0      The cursor is left pointing at an entry that
52817 **                  is smaller than intKey/pIdxKey or if the table is empty
52818 **                  and the cursor is therefore left point to nothing.
52819 **
52820 **     *pRes==0     The cursor is left pointing at an entry that
52821 **                  exactly matches intKey/pIdxKey.
52822 **
52823 **     *pRes>0      The cursor is left pointing at an entry that
52824 **                  is larger than intKey/pIdxKey.
52825 **
52826 */
52827 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52828   BtCursor *pCur,          /* The cursor to be moved */
52829   UnpackedRecord *pIdxKey, /* Unpacked index key */
52830   i64 intKey,              /* The table key */
52831   int biasRight,           /* If true, bias the search to the high end */
52832   int *pRes                /* Write search results here */
52833 ){
52834   int rc;
52835
52836   assert( cursorHoldsMutex(pCur) );
52837   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52838   assert( pRes );
52839   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52840
52841   /* If the cursor is already positioned at the point we are trying
52842   ** to move to, then just return without doing any work */
52843   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
52844    && pCur->apPage[0]->intKey 
52845   ){
52846     if( pCur->info.nKey==intKey ){
52847       *pRes = 0;
52848       return SQLITE_OK;
52849     }
52850     if( pCur->atLast && pCur->info.nKey<intKey ){
52851       *pRes = -1;
52852       return SQLITE_OK;
52853     }
52854   }
52855
52856   rc = moveToRoot(pCur);
52857   if( rc ){
52858     return rc;
52859   }
52860   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52861   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52862   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52863   if( pCur->eState==CURSOR_INVALID ){
52864     *pRes = -1;
52865     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52866     return SQLITE_OK;
52867   }
52868   assert( pCur->apPage[0]->intKey || pIdxKey );
52869   for(;;){
52870     int lwr, upr, idx;
52871     Pgno chldPg;
52872     MemPage *pPage = pCur->apPage[pCur->iPage];
52873     int c;
52874
52875     /* pPage->nCell must be greater than zero. If this is the root-page
52876     ** the cursor would have been INVALID above and this for(;;) loop
52877     ** not run. If this is not the root-page, then the moveToChild() routine
52878     ** would have already detected db corruption. Similarly, pPage must
52879     ** be the right kind (index or table) of b-tree page. Otherwise
52880     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
52881     assert( pPage->nCell>0 );
52882     assert( pPage->intKey==(pIdxKey==0) );
52883     lwr = 0;
52884     upr = pPage->nCell-1;
52885     if( biasRight ){
52886       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
52887     }else{
52888       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
52889     }
52890     for(;;){
52891       u8 *pCell;                          /* Pointer to current cell in pPage */
52892
52893       assert( idx==pCur->aiIdx[pCur->iPage] );
52894       pCur->info.nSize = 0;
52895       pCell = findCell(pPage, idx) + pPage->childPtrSize;
52896       if( pPage->intKey ){
52897         i64 nCellKey;
52898         if( pPage->hasData ){
52899           u32 dummy;
52900           pCell += getVarint32(pCell, dummy);
52901         }
52902         getVarint(pCell, (u64*)&nCellKey);
52903         if( nCellKey==intKey ){
52904           c = 0;
52905         }else if( nCellKey<intKey ){
52906           c = -1;
52907         }else{
52908           assert( nCellKey>intKey );
52909           c = +1;
52910         }
52911         pCur->validNKey = 1;
52912         pCur->info.nKey = nCellKey;
52913       }else{
52914         /* The maximum supported page-size is 65536 bytes. This means that
52915         ** the maximum number of record bytes stored on an index B-Tree
52916         ** page is less than 16384 bytes and may be stored as a 2-byte
52917         ** varint. This information is used to attempt to avoid parsing 
52918         ** the entire cell by checking for the cases where the record is 
52919         ** stored entirely within the b-tree page by inspecting the first 
52920         ** 2 bytes of the cell.
52921         */
52922         int nCell = pCell[0];
52923         if( nCell<=pPage->max1bytePayload
52924          /* && (pCell+nCell)<pPage->aDataEnd */
52925         ){
52926           /* This branch runs if the record-size field of the cell is a
52927           ** single byte varint and the record fits entirely on the main
52928           ** b-tree page.  */
52929           testcase( pCell+nCell+1==pPage->aDataEnd );
52930           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
52931         }else if( !(pCell[1] & 0x80) 
52932           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
52933           /* && (pCell+nCell+2)<=pPage->aDataEnd */
52934         ){
52935           /* The record-size field is a 2 byte varint and the record 
52936           ** fits entirely on the main b-tree page.  */
52937           testcase( pCell+nCell+2==pPage->aDataEnd );
52938           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
52939         }else{
52940           /* The record flows over onto one or more overflow pages. In
52941           ** this case the whole cell needs to be parsed, a buffer allocated
52942           ** and accessPayload() used to retrieve the record into the
52943           ** buffer before VdbeRecordCompare() can be called. */
52944           void *pCellKey;
52945           u8 * const pCellBody = pCell - pPage->childPtrSize;
52946           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
52947           nCell = (int)pCur->info.nKey;
52948           pCellKey = sqlite3Malloc( nCell );
52949           if( pCellKey==0 ){
52950             rc = SQLITE_NOMEM;
52951             goto moveto_finish;
52952           }
52953           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
52954           if( rc ){
52955             sqlite3_free(pCellKey);
52956             goto moveto_finish;
52957           }
52958           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
52959           sqlite3_free(pCellKey);
52960         }
52961       }
52962       if( c==0 ){
52963         if( pPage->intKey && !pPage->leaf ){
52964           lwr = idx;
52965           break;
52966         }else{
52967           *pRes = 0;
52968           rc = SQLITE_OK;
52969           goto moveto_finish;
52970         }
52971       }
52972       if( c<0 ){
52973         lwr = idx+1;
52974       }else{
52975         upr = idx-1;
52976       }
52977       if( lwr>upr ){
52978         break;
52979       }
52980       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
52981     }
52982     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
52983     assert( pPage->isInit );
52984     if( pPage->leaf ){
52985       chldPg = 0;
52986     }else if( lwr>=pPage->nCell ){
52987       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52988     }else{
52989       chldPg = get4byte(findCell(pPage, lwr));
52990     }
52991     if( chldPg==0 ){
52992       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52993       *pRes = c;
52994       rc = SQLITE_OK;
52995       goto moveto_finish;
52996     }
52997     pCur->aiIdx[pCur->iPage] = (u16)lwr;
52998     pCur->info.nSize = 0;
52999     pCur->validNKey = 0;
53000     rc = moveToChild(pCur, chldPg);
53001     if( rc ) goto moveto_finish;
53002   }
53003 moveto_finish:
53004   return rc;
53005 }
53006
53007
53008 /*
53009 ** Return TRUE if the cursor is not pointing at an entry of the table.
53010 **
53011 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
53012 ** past the last entry in the table or sqlite3BtreePrev() moves past
53013 ** the first entry.  TRUE is also returned if the table is empty.
53014 */
53015 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
53016   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
53017   ** have been deleted? This API will need to change to return an error code
53018   ** as well as the boolean result value.
53019   */
53020   return (CURSOR_VALID!=pCur->eState);
53021 }
53022
53023 /*
53024 ** Advance the cursor to the next entry in the database.  If
53025 ** successful then set *pRes=0.  If the cursor
53026 ** was already pointing to the last entry in the database before
53027 ** this routine was called, then set *pRes=1.
53028 */
53029 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
53030   int rc;
53031   int idx;
53032   MemPage *pPage;
53033
53034   assert( cursorHoldsMutex(pCur) );
53035   rc = restoreCursorPosition(pCur);
53036   if( rc!=SQLITE_OK ){
53037     return rc;
53038   }
53039   assert( pRes!=0 );
53040   if( CURSOR_INVALID==pCur->eState ){
53041     *pRes = 1;
53042     return SQLITE_OK;
53043   }
53044   if( pCur->skipNext>0 ){
53045     pCur->skipNext = 0;
53046     *pRes = 0;
53047     return SQLITE_OK;
53048   }
53049   pCur->skipNext = 0;
53050
53051   pPage = pCur->apPage[pCur->iPage];
53052   idx = ++pCur->aiIdx[pCur->iPage];
53053   assert( pPage->isInit );
53054
53055   /* If the database file is corrupt, it is possible for the value of idx 
53056   ** to be invalid here. This can only occur if a second cursor modifies
53057   ** the page while cursor pCur is holding a reference to it. Which can
53058   ** only happen if the database is corrupt in such a way as to link the
53059   ** page into more than one b-tree structure. */
53060   testcase( idx>pPage->nCell );
53061
53062   pCur->info.nSize = 0;
53063   pCur->validNKey = 0;
53064   if( idx>=pPage->nCell ){
53065     if( !pPage->leaf ){
53066       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
53067       if( rc ) return rc;
53068       rc = moveToLeftmost(pCur);
53069       *pRes = 0;
53070       return rc;
53071     }
53072     do{
53073       if( pCur->iPage==0 ){
53074         *pRes = 1;
53075         pCur->eState = CURSOR_INVALID;
53076         return SQLITE_OK;
53077       }
53078       moveToParent(pCur);
53079       pPage = pCur->apPage[pCur->iPage];
53080     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
53081     *pRes = 0;
53082     if( pPage->intKey ){
53083       rc = sqlite3BtreeNext(pCur, pRes);
53084     }else{
53085       rc = SQLITE_OK;
53086     }
53087     return rc;
53088   }
53089   *pRes = 0;
53090   if( pPage->leaf ){
53091     return SQLITE_OK;
53092   }
53093   rc = moveToLeftmost(pCur);
53094   return rc;
53095 }
53096
53097
53098 /*
53099 ** Step the cursor to the back to the previous entry in the database.  If
53100 ** successful then set *pRes=0.  If the cursor
53101 ** was already pointing to the first entry in the database before
53102 ** this routine was called, then set *pRes=1.
53103 */
53104 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
53105   int rc;
53106   MemPage *pPage;
53107
53108   assert( cursorHoldsMutex(pCur) );
53109   rc = restoreCursorPosition(pCur);
53110   if( rc!=SQLITE_OK ){
53111     return rc;
53112   }
53113   pCur->atLast = 0;
53114   if( CURSOR_INVALID==pCur->eState ){
53115     *pRes = 1;
53116     return SQLITE_OK;
53117   }
53118   if( pCur->skipNext<0 ){
53119     pCur->skipNext = 0;
53120     *pRes = 0;
53121     return SQLITE_OK;
53122   }
53123   pCur->skipNext = 0;
53124
53125   pPage = pCur->apPage[pCur->iPage];
53126   assert( pPage->isInit );
53127   if( !pPage->leaf ){
53128     int idx = pCur->aiIdx[pCur->iPage];
53129     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
53130     if( rc ){
53131       return rc;
53132     }
53133     rc = moveToRightmost(pCur);
53134   }else{
53135     while( pCur->aiIdx[pCur->iPage]==0 ){
53136       if( pCur->iPage==0 ){
53137         pCur->eState = CURSOR_INVALID;
53138         *pRes = 1;
53139         return SQLITE_OK;
53140       }
53141       moveToParent(pCur);
53142     }
53143     pCur->info.nSize = 0;
53144     pCur->validNKey = 0;
53145
53146     pCur->aiIdx[pCur->iPage]--;
53147     pPage = pCur->apPage[pCur->iPage];
53148     if( pPage->intKey && !pPage->leaf ){
53149       rc = sqlite3BtreePrevious(pCur, pRes);
53150     }else{
53151       rc = SQLITE_OK;
53152     }
53153   }
53154   *pRes = 0;
53155   return rc;
53156 }
53157
53158 /*
53159 ** Allocate a new page from the database file.
53160 **
53161 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
53162 ** has already been called on the new page.)  The new page has also
53163 ** been referenced and the calling routine is responsible for calling
53164 ** sqlite3PagerUnref() on the new page when it is done.
53165 **
53166 ** SQLITE_OK is returned on success.  Any other return value indicates
53167 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
53168 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
53169 **
53170 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
53171 ** locate a page close to the page number "nearby".  This can be used in an
53172 ** attempt to keep related pages close to each other in the database file,
53173 ** which in turn can make database access faster.
53174 **
53175 ** If the "exact" parameter is not 0, and the page-number nearby exists 
53176 ** anywhere on the free-list, then it is guarenteed to be returned. This
53177 ** is only used by auto-vacuum databases when allocating a new table.
53178 */
53179 static int allocateBtreePage(
53180   BtShared *pBt, 
53181   MemPage **ppPage, 
53182   Pgno *pPgno, 
53183   Pgno nearby,
53184   u8 exact
53185 ){
53186   MemPage *pPage1;
53187   int rc;
53188   u32 n;     /* Number of pages on the freelist */
53189   u32 k;     /* Number of leaves on the trunk of the freelist */
53190   MemPage *pTrunk = 0;
53191   MemPage *pPrevTrunk = 0;
53192   Pgno mxPage;     /* Total size of the database file */
53193
53194   assert( sqlite3_mutex_held(pBt->mutex) );
53195   pPage1 = pBt->pPage1;
53196   mxPage = btreePagecount(pBt);
53197   n = get4byte(&pPage1->aData[36]);
53198   testcase( n==mxPage-1 );
53199   if( n>=mxPage ){
53200     return SQLITE_CORRUPT_BKPT;
53201   }
53202   if( n>0 ){
53203     /* There are pages on the freelist.  Reuse one of those pages. */
53204     Pgno iTrunk;
53205     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
53206     
53207     /* If the 'exact' parameter was true and a query of the pointer-map
53208     ** shows that the page 'nearby' is somewhere on the free-list, then
53209     ** the entire-list will be searched for that page.
53210     */
53211 #ifndef SQLITE_OMIT_AUTOVACUUM
53212     if( exact && nearby<=mxPage ){
53213       u8 eType;
53214       assert( nearby>0 );
53215       assert( pBt->autoVacuum );
53216       rc = ptrmapGet(pBt, nearby, &eType, 0);
53217       if( rc ) return rc;
53218       if( eType==PTRMAP_FREEPAGE ){
53219         searchList = 1;
53220       }
53221       *pPgno = nearby;
53222     }
53223 #endif
53224
53225     /* Decrement the free-list count by 1. Set iTrunk to the index of the
53226     ** first free-list trunk page. iPrevTrunk is initially 1.
53227     */
53228     rc = sqlite3PagerWrite(pPage1->pDbPage);
53229     if( rc ) return rc;
53230     put4byte(&pPage1->aData[36], n-1);
53231
53232     /* The code within this loop is run only once if the 'searchList' variable
53233     ** is not true. Otherwise, it runs once for each trunk-page on the
53234     ** free-list until the page 'nearby' is located.
53235     */
53236     do {
53237       pPrevTrunk = pTrunk;
53238       if( pPrevTrunk ){
53239         iTrunk = get4byte(&pPrevTrunk->aData[0]);
53240       }else{
53241         iTrunk = get4byte(&pPage1->aData[32]);
53242       }
53243       testcase( iTrunk==mxPage );
53244       if( iTrunk>mxPage ){
53245         rc = SQLITE_CORRUPT_BKPT;
53246       }else{
53247         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53248       }
53249       if( rc ){
53250         pTrunk = 0;
53251         goto end_allocate_page;
53252       }
53253       assert( pTrunk!=0 );
53254       assert( pTrunk->aData!=0 );
53255
53256       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
53257       if( k==0 && !searchList ){
53258         /* The trunk has no leaves and the list is not being searched. 
53259         ** So extract the trunk page itself and use it as the newly 
53260         ** allocated page */
53261         assert( pPrevTrunk==0 );
53262         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53263         if( rc ){
53264           goto end_allocate_page;
53265         }
53266         *pPgno = iTrunk;
53267         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53268         *ppPage = pTrunk;
53269         pTrunk = 0;
53270         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53271       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
53272         /* Value of k is out of range.  Database corruption */
53273         rc = SQLITE_CORRUPT_BKPT;
53274         goto end_allocate_page;
53275 #ifndef SQLITE_OMIT_AUTOVACUUM
53276       }else if( searchList && nearby==iTrunk ){
53277         /* The list is being searched and this trunk page is the page
53278         ** to allocate, regardless of whether it has leaves.
53279         */
53280         assert( *pPgno==iTrunk );
53281         *ppPage = pTrunk;
53282         searchList = 0;
53283         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53284         if( rc ){
53285           goto end_allocate_page;
53286         }
53287         if( k==0 ){
53288           if( !pPrevTrunk ){
53289             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53290           }else{
53291             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53292             if( rc!=SQLITE_OK ){
53293               goto end_allocate_page;
53294             }
53295             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
53296           }
53297         }else{
53298           /* The trunk page is required by the caller but it contains 
53299           ** pointers to free-list leaves. The first leaf becomes a trunk
53300           ** page in this case.
53301           */
53302           MemPage *pNewTrunk;
53303           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
53304           if( iNewTrunk>mxPage ){ 
53305             rc = SQLITE_CORRUPT_BKPT;
53306             goto end_allocate_page;
53307           }
53308           testcase( iNewTrunk==mxPage );
53309           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
53310           if( rc!=SQLITE_OK ){
53311             goto end_allocate_page;
53312           }
53313           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
53314           if( rc!=SQLITE_OK ){
53315             releasePage(pNewTrunk);
53316             goto end_allocate_page;
53317           }
53318           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
53319           put4byte(&pNewTrunk->aData[4], k-1);
53320           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
53321           releasePage(pNewTrunk);
53322           if( !pPrevTrunk ){
53323             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
53324             put4byte(&pPage1->aData[32], iNewTrunk);
53325           }else{
53326             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53327             if( rc ){
53328               goto end_allocate_page;
53329             }
53330             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
53331           }
53332         }
53333         pTrunk = 0;
53334         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53335 #endif
53336       }else if( k>0 ){
53337         /* Extract a leaf from the trunk */
53338         u32 closest;
53339         Pgno iPage;
53340         unsigned char *aData = pTrunk->aData;
53341         if( nearby>0 ){
53342           u32 i;
53343           int dist;
53344           closest = 0;
53345           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
53346           for(i=1; i<k; i++){
53347             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
53348             if( d2<dist ){
53349               closest = i;
53350               dist = d2;
53351             }
53352           }
53353         }else{
53354           closest = 0;
53355         }
53356
53357         iPage = get4byte(&aData[8+closest*4]);
53358         testcase( iPage==mxPage );
53359         if( iPage>mxPage ){
53360           rc = SQLITE_CORRUPT_BKPT;
53361           goto end_allocate_page;
53362         }
53363         testcase( iPage==mxPage );
53364         if( !searchList || iPage==nearby ){
53365           int noContent;
53366           *pPgno = iPage;
53367           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
53368                  ": %d more free pages\n",
53369                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
53370           rc = sqlite3PagerWrite(pTrunk->pDbPage);
53371           if( rc ) goto end_allocate_page;
53372           if( closest<k-1 ){
53373             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
53374           }
53375           put4byte(&aData[4], k-1);
53376           noContent = !btreeGetHasContent(pBt, *pPgno);
53377           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
53378           if( rc==SQLITE_OK ){
53379             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53380             if( rc!=SQLITE_OK ){
53381               releasePage(*ppPage);
53382             }
53383           }
53384           searchList = 0;
53385         }
53386       }
53387       releasePage(pPrevTrunk);
53388       pPrevTrunk = 0;
53389     }while( searchList );
53390   }else{
53391     /* There are no pages on the freelist, so create a new page at the
53392     ** end of the file */
53393     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53394     if( rc ) return rc;
53395     pBt->nPage++;
53396     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
53397
53398 #ifndef SQLITE_OMIT_AUTOVACUUM
53399     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
53400       /* If *pPgno refers to a pointer-map page, allocate two new pages
53401       ** at the end of the file instead of one. The first allocated page
53402       ** becomes a new pointer-map page, the second is used by the caller.
53403       */
53404       MemPage *pPg = 0;
53405       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
53406       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
53407       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
53408       if( rc==SQLITE_OK ){
53409         rc = sqlite3PagerWrite(pPg->pDbPage);
53410         releasePage(pPg);
53411       }
53412       if( rc ) return rc;
53413       pBt->nPage++;
53414       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
53415     }
53416 #endif
53417     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
53418     *pPgno = pBt->nPage;
53419
53420     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53421     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
53422     if( rc ) return rc;
53423     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53424     if( rc!=SQLITE_OK ){
53425       releasePage(*ppPage);
53426     }
53427     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53428   }
53429
53430   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53431
53432 end_allocate_page:
53433   releasePage(pTrunk);
53434   releasePage(pPrevTrunk);
53435   if( rc==SQLITE_OK ){
53436     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53437       releasePage(*ppPage);
53438       return SQLITE_CORRUPT_BKPT;
53439     }
53440     (*ppPage)->isInit = 0;
53441   }else{
53442     *ppPage = 0;
53443   }
53444   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53445   return rc;
53446 }
53447
53448 /*
53449 ** This function is used to add page iPage to the database file free-list. 
53450 ** It is assumed that the page is not already a part of the free-list.
53451 **
53452 ** The value passed as the second argument to this function is optional.
53453 ** If the caller happens to have a pointer to the MemPage object 
53454 ** corresponding to page iPage handy, it may pass it as the second value. 
53455 ** Otherwise, it may pass NULL.
53456 **
53457 ** If a pointer to a MemPage object is passed as the second argument,
53458 ** its reference count is not altered by this function.
53459 */
53460 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53461   MemPage *pTrunk = 0;                /* Free-list trunk page */
53462   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
53463   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
53464   MemPage *pPage;                     /* Page being freed. May be NULL. */
53465   int rc;                             /* Return Code */
53466   int nFree;                          /* Initial number of pages on free-list */
53467
53468   assert( sqlite3_mutex_held(pBt->mutex) );
53469   assert( iPage>1 );
53470   assert( !pMemPage || pMemPage->pgno==iPage );
53471
53472   if( pMemPage ){
53473     pPage = pMemPage;
53474     sqlite3PagerRef(pPage->pDbPage);
53475   }else{
53476     pPage = btreePageLookup(pBt, iPage);
53477   }
53478
53479   /* Increment the free page count on pPage1 */
53480   rc = sqlite3PagerWrite(pPage1->pDbPage);
53481   if( rc ) goto freepage_out;
53482   nFree = get4byte(&pPage1->aData[36]);
53483   put4byte(&pPage1->aData[36], nFree+1);
53484
53485   if( pBt->btsFlags & BTS_SECURE_DELETE ){
53486     /* If the secure_delete option is enabled, then
53487     ** always fully overwrite deleted information with zeros.
53488     */
53489     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53490      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53491     ){
53492       goto freepage_out;
53493     }
53494     memset(pPage->aData, 0, pPage->pBt->pageSize);
53495   }
53496
53497   /* If the database supports auto-vacuum, write an entry in the pointer-map
53498   ** to indicate that the page is free.
53499   */
53500   if( ISAUTOVACUUM ){
53501     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53502     if( rc ) goto freepage_out;
53503   }
53504
53505   /* Now manipulate the actual database free-list structure. There are two
53506   ** possibilities. If the free-list is currently empty, or if the first
53507   ** trunk page in the free-list is full, then this page will become a
53508   ** new free-list trunk page. Otherwise, it will become a leaf of the
53509   ** first trunk page in the current free-list. This block tests if it
53510   ** is possible to add the page as a new free-list leaf.
53511   */
53512   if( nFree!=0 ){
53513     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
53514
53515     iTrunk = get4byte(&pPage1->aData[32]);
53516     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53517     if( rc!=SQLITE_OK ){
53518       goto freepage_out;
53519     }
53520
53521     nLeaf = get4byte(&pTrunk->aData[4]);
53522     assert( pBt->usableSize>32 );
53523     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53524       rc = SQLITE_CORRUPT_BKPT;
53525       goto freepage_out;
53526     }
53527     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53528       /* In this case there is room on the trunk page to insert the page
53529       ** being freed as a new leaf.
53530       **
53531       ** Note that the trunk page is not really full until it contains
53532       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53533       ** coded.  But due to a coding error in versions of SQLite prior to
53534       ** 3.6.0, databases with freelist trunk pages holding more than
53535       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
53536       ** to maintain backwards compatibility with older versions of SQLite,
53537       ** we will continue to restrict the number of entries to usableSize/4 - 8
53538       ** for now.  At some point in the future (once everyone has upgraded
53539       ** to 3.6.0 or later) we should consider fixing the conditional above
53540       ** to read "usableSize/4-2" instead of "usableSize/4-8".
53541       */
53542       rc = sqlite3PagerWrite(pTrunk->pDbPage);
53543       if( rc==SQLITE_OK ){
53544         put4byte(&pTrunk->aData[4], nLeaf+1);
53545         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53546         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
53547           sqlite3PagerDontWrite(pPage->pDbPage);
53548         }
53549         rc = btreeSetHasContent(pBt, iPage);
53550       }
53551       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53552       goto freepage_out;
53553     }
53554   }
53555
53556   /* If control flows to this point, then it was not possible to add the
53557   ** the page being freed as a leaf page of the first trunk in the free-list.
53558   ** Possibly because the free-list is empty, or possibly because the 
53559   ** first trunk in the free-list is full. Either way, the page being freed
53560   ** will become the new first trunk page in the free-list.
53561   */
53562   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53563     goto freepage_out;
53564   }
53565   rc = sqlite3PagerWrite(pPage->pDbPage);
53566   if( rc!=SQLITE_OK ){
53567     goto freepage_out;
53568   }
53569   put4byte(pPage->aData, iTrunk);
53570   put4byte(&pPage->aData[4], 0);
53571   put4byte(&pPage1->aData[32], iPage);
53572   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53573
53574 freepage_out:
53575   if( pPage ){
53576     pPage->isInit = 0;
53577   }
53578   releasePage(pPage);
53579   releasePage(pTrunk);
53580   return rc;
53581 }
53582 static void freePage(MemPage *pPage, int *pRC){
53583   if( (*pRC)==SQLITE_OK ){
53584     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53585   }
53586 }
53587
53588 /*
53589 ** Free any overflow pages associated with the given Cell.
53590 */
53591 static int clearCell(MemPage *pPage, unsigned char *pCell){
53592   BtShared *pBt = pPage->pBt;
53593   CellInfo info;
53594   Pgno ovflPgno;
53595   int rc;
53596   int nOvfl;
53597   u32 ovflPageSize;
53598
53599   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53600   btreeParseCellPtr(pPage, pCell, &info);
53601   if( info.iOverflow==0 ){
53602     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
53603   }
53604   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53605     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
53606   }
53607   ovflPgno = get4byte(&pCell[info.iOverflow]);
53608   assert( pBt->usableSize > 4 );
53609   ovflPageSize = pBt->usableSize - 4;
53610   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53611   assert( ovflPgno==0 || nOvfl>0 );
53612   while( nOvfl-- ){
53613     Pgno iNext = 0;
53614     MemPage *pOvfl = 0;
53615     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53616       /* 0 is not a legal page number and page 1 cannot be an 
53617       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
53618       ** file the database must be corrupt. */
53619       return SQLITE_CORRUPT_BKPT;
53620     }
53621     if( nOvfl ){
53622       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53623       if( rc ) return rc;
53624     }
53625
53626     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53627      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53628     ){
53629       /* There is no reason any cursor should have an outstanding reference 
53630       ** to an overflow page belonging to a cell that is being deleted/updated.
53631       ** So if there exists more than one reference to this page, then it 
53632       ** must not really be an overflow page and the database must be corrupt. 
53633       ** It is helpful to detect this before calling freePage2(), as 
53634       ** freePage2() may zero the page contents if secure-delete mode is
53635       ** enabled. If this 'overflow' page happens to be a page that the
53636       ** caller is iterating through or using in some other way, this
53637       ** can be problematic.
53638       */
53639       rc = SQLITE_CORRUPT_BKPT;
53640     }else{
53641       rc = freePage2(pBt, pOvfl, ovflPgno);
53642     }
53643
53644     if( pOvfl ){
53645       sqlite3PagerUnref(pOvfl->pDbPage);
53646     }
53647     if( rc ) return rc;
53648     ovflPgno = iNext;
53649   }
53650   return SQLITE_OK;
53651 }
53652
53653 /*
53654 ** Create the byte sequence used to represent a cell on page pPage
53655 ** and write that byte sequence into pCell[].  Overflow pages are
53656 ** allocated and filled in as necessary.  The calling procedure
53657 ** is responsible for making sure sufficient space has been allocated
53658 ** for pCell[].
53659 **
53660 ** Note that pCell does not necessary need to point to the pPage->aData
53661 ** area.  pCell might point to some temporary storage.  The cell will
53662 ** be constructed in this temporary area then copied into pPage->aData
53663 ** later.
53664 */
53665 static int fillInCell(
53666   MemPage *pPage,                /* The page that contains the cell */
53667   unsigned char *pCell,          /* Complete text of the cell */
53668   const void *pKey, i64 nKey,    /* The key */
53669   const void *pData,int nData,   /* The data */
53670   int nZero,                     /* Extra zero bytes to append to pData */
53671   int *pnSize                    /* Write cell size here */
53672 ){
53673   int nPayload;
53674   const u8 *pSrc;
53675   int nSrc, n, rc;
53676   int spaceLeft;
53677   MemPage *pOvfl = 0;
53678   MemPage *pToRelease = 0;
53679   unsigned char *pPrior;
53680   unsigned char *pPayload;
53681   BtShared *pBt = pPage->pBt;
53682   Pgno pgnoOvfl = 0;
53683   int nHeader;
53684   CellInfo info;
53685
53686   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53687
53688   /* pPage is not necessarily writeable since pCell might be auxiliary
53689   ** buffer space that is separate from the pPage buffer area */
53690   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53691             || sqlite3PagerIswriteable(pPage->pDbPage) );
53692
53693   /* Fill in the header. */
53694   nHeader = 0;
53695   if( !pPage->leaf ){
53696     nHeader += 4;
53697   }
53698   if( pPage->hasData ){
53699     nHeader += putVarint(&pCell[nHeader], nData+nZero);
53700   }else{
53701     nData = nZero = 0;
53702   }
53703   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53704   btreeParseCellPtr(pPage, pCell, &info);
53705   assert( info.nHeader==nHeader );
53706   assert( info.nKey==nKey );
53707   assert( info.nData==(u32)(nData+nZero) );
53708   
53709   /* Fill in the payload */
53710   nPayload = nData + nZero;
53711   if( pPage->intKey ){
53712     pSrc = pData;
53713     nSrc = nData;
53714     nData = 0;
53715   }else{ 
53716     if( NEVER(nKey>0x7fffffff || pKey==0) ){
53717       return SQLITE_CORRUPT_BKPT;
53718     }
53719     nPayload += (int)nKey;
53720     pSrc = pKey;
53721     nSrc = (int)nKey;
53722   }
53723   *pnSize = info.nSize;
53724   spaceLeft = info.nLocal;
53725   pPayload = &pCell[nHeader];
53726   pPrior = &pCell[info.iOverflow];
53727
53728   while( nPayload>0 ){
53729     if( spaceLeft==0 ){
53730 #ifndef SQLITE_OMIT_AUTOVACUUM
53731       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53732       if( pBt->autoVacuum ){
53733         do{
53734           pgnoOvfl++;
53735         } while( 
53736           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
53737         );
53738       }
53739 #endif
53740       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53741 #ifndef SQLITE_OMIT_AUTOVACUUM
53742       /* If the database supports auto-vacuum, and the second or subsequent
53743       ** overflow page is being allocated, add an entry to the pointer-map
53744       ** for that page now. 
53745       **
53746       ** If this is the first overflow page, then write a partial entry 
53747       ** to the pointer-map. If we write nothing to this pointer-map slot,
53748       ** then the optimistic overflow chain processing in clearCell()
53749       ** may misinterpret the uninitialised values and delete the
53750       ** wrong pages from the database.
53751       */
53752       if( pBt->autoVacuum && rc==SQLITE_OK ){
53753         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53754         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53755         if( rc ){
53756           releasePage(pOvfl);
53757         }
53758       }
53759 #endif
53760       if( rc ){
53761         releasePage(pToRelease);
53762         return rc;
53763       }
53764
53765       /* If pToRelease is not zero than pPrior points into the data area
53766       ** of pToRelease.  Make sure pToRelease is still writeable. */
53767       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53768
53769       /* If pPrior is part of the data area of pPage, then make sure pPage
53770       ** is still writeable */
53771       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53772             || sqlite3PagerIswriteable(pPage->pDbPage) );
53773
53774       put4byte(pPrior, pgnoOvfl);
53775       releasePage(pToRelease);
53776       pToRelease = pOvfl;
53777       pPrior = pOvfl->aData;
53778       put4byte(pPrior, 0);
53779       pPayload = &pOvfl->aData[4];
53780       spaceLeft = pBt->usableSize - 4;
53781     }
53782     n = nPayload;
53783     if( n>spaceLeft ) n = spaceLeft;
53784
53785     /* If pToRelease is not zero than pPayload points into the data area
53786     ** of pToRelease.  Make sure pToRelease is still writeable. */
53787     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53788
53789     /* If pPayload is part of the data area of pPage, then make sure pPage
53790     ** is still writeable */
53791     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53792             || sqlite3PagerIswriteable(pPage->pDbPage) );
53793
53794     if( nSrc>0 ){
53795       if( n>nSrc ) n = nSrc;
53796       assert( pSrc );
53797       memcpy(pPayload, pSrc, n);
53798     }else{
53799       memset(pPayload, 0, n);
53800     }
53801     nPayload -= n;
53802     pPayload += n;
53803     pSrc += n;
53804     nSrc -= n;
53805     spaceLeft -= n;
53806     if( nSrc==0 ){
53807       nSrc = nData;
53808       pSrc = pData;
53809     }
53810   }
53811   releasePage(pToRelease);
53812   return SQLITE_OK;
53813 }
53814
53815 /*
53816 ** Remove the i-th cell from pPage.  This routine effects pPage only.
53817 ** The cell content is not freed or deallocated.  It is assumed that
53818 ** the cell content has been copied someplace else.  This routine just
53819 ** removes the reference to the cell from pPage.
53820 **
53821 ** "sz" must be the number of bytes in the cell.
53822 */
53823 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53824   u32 pc;         /* Offset to cell content of cell being deleted */
53825   u8 *data;       /* pPage->aData */
53826   u8 *ptr;        /* Used to move bytes around within data[] */
53827   u8 *endPtr;     /* End of loop */
53828   int rc;         /* The return code */
53829   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
53830
53831   if( *pRC ) return;
53832
53833   assert( idx>=0 && idx<pPage->nCell );
53834   assert( sz==cellSize(pPage, idx) );
53835   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53836   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53837   data = pPage->aData;
53838   ptr = &pPage->aCellIdx[2*idx];
53839   pc = get2byte(ptr);
53840   hdr = pPage->hdrOffset;
53841   testcase( pc==get2byte(&data[hdr+5]) );
53842   testcase( pc+sz==pPage->pBt->usableSize );
53843   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
53844     *pRC = SQLITE_CORRUPT_BKPT;
53845     return;
53846   }
53847   rc = freeSpace(pPage, pc, sz);
53848   if( rc ){
53849     *pRC = rc;
53850     return;
53851   }
53852   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
53853   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53854   while( ptr<endPtr ){
53855     *(u16*)ptr = *(u16*)&ptr[2];
53856     ptr += 2;
53857   }
53858   pPage->nCell--;
53859   put2byte(&data[hdr+3], pPage->nCell);
53860   pPage->nFree += 2;
53861 }
53862
53863 /*
53864 ** Insert a new cell on pPage at cell index "i".  pCell points to the
53865 ** content of the cell.
53866 **
53867 ** If the cell content will fit on the page, then put it there.  If it
53868 ** will not fit, then make a copy of the cell content into pTemp if
53869 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
53870 ** in pPage->apOvfl[] and make it point to the cell content (either
53871 ** in pTemp or the original pCell) and also record its index. 
53872 ** Allocating a new entry in pPage->aCell[] implies that 
53873 ** pPage->nOverflow is incremented.
53874 **
53875 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
53876 ** cell. The caller will overwrite them after this function returns. If
53877 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
53878 ** (but pCell+nSkip is always valid).
53879 */
53880 static void insertCell(
53881   MemPage *pPage,   /* Page into which we are copying */
53882   int i,            /* New cell becomes the i-th cell of the page */
53883   u8 *pCell,        /* Content of the new cell */
53884   int sz,           /* Bytes of content in pCell */
53885   u8 *pTemp,        /* Temp storage space for pCell, if needed */
53886   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
53887   int *pRC          /* Read and write return code from here */
53888 ){
53889   int idx = 0;      /* Where to write new cell content in data[] */
53890   int j;            /* Loop counter */
53891   int end;          /* First byte past the last cell pointer in data[] */
53892   int ins;          /* Index in data[] where new cell pointer is inserted */
53893   int cellOffset;   /* Address of first cell pointer in data[] */
53894   u8 *data;         /* The content of the whole page */
53895   u8 *ptr;          /* Used for moving information around in data[] */
53896   u8 *endPtr;       /* End of the loop */
53897
53898   int nSkip = (iChild ? 4 : 0);
53899
53900   if( *pRC ) return;
53901
53902   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
53903   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
53904   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
53905   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
53906   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53907   /* The cell should normally be sized correctly.  However, when moving a
53908   ** malformed cell from a leaf page to an interior page, if the cell size
53909   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
53910   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
53911   ** the term after the || in the following assert(). */
53912   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
53913   if( pPage->nOverflow || sz+2>pPage->nFree ){
53914     if( pTemp ){
53915       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
53916       pCell = pTemp;
53917     }
53918     if( iChild ){
53919       put4byte(pCell, iChild);
53920     }
53921     j = pPage->nOverflow++;
53922     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
53923     pPage->apOvfl[j] = pCell;
53924     pPage->aiOvfl[j] = (u16)i;
53925   }else{
53926     int rc = sqlite3PagerWrite(pPage->pDbPage);
53927     if( rc!=SQLITE_OK ){
53928       *pRC = rc;
53929       return;
53930     }
53931     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53932     data = pPage->aData;
53933     cellOffset = pPage->cellOffset;
53934     end = cellOffset + 2*pPage->nCell;
53935     ins = cellOffset + 2*i;
53936     rc = allocateSpace(pPage, sz, &idx);
53937     if( rc ){ *pRC = rc; return; }
53938     /* The allocateSpace() routine guarantees the following two properties
53939     ** if it returns success */
53940     assert( idx >= end+2 );
53941     assert( idx+sz <= (int)pPage->pBt->usableSize );
53942     pPage->nCell++;
53943     pPage->nFree -= (u16)(2 + sz);
53944     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
53945     if( iChild ){
53946       put4byte(&data[idx], iChild);
53947     }
53948     ptr = &data[end];
53949     endPtr = &data[ins];
53950     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53951     while( ptr>endPtr ){
53952       *(u16*)ptr = *(u16*)&ptr[-2];
53953       ptr -= 2;
53954     }
53955     put2byte(&data[ins], idx);
53956     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
53957 #ifndef SQLITE_OMIT_AUTOVACUUM
53958     if( pPage->pBt->autoVacuum ){
53959       /* The cell may contain a pointer to an overflow page. If so, write
53960       ** the entry for the overflow page into the pointer map.
53961       */
53962       ptrmapPutOvflPtr(pPage, pCell, pRC);
53963     }
53964 #endif
53965   }
53966 }
53967
53968 /*
53969 ** Add a list of cells to a page.  The page should be initially empty.
53970 ** The cells are guaranteed to fit on the page.
53971 */
53972 static void assemblePage(
53973   MemPage *pPage,   /* The page to be assemblied */
53974   int nCell,        /* The number of cells to add to this page */
53975   u8 **apCell,      /* Pointers to cell bodies */
53976   u16 *aSize        /* Sizes of the cells */
53977 ){
53978   int i;            /* Loop counter */
53979   u8 *pCellptr;     /* Address of next cell pointer */
53980   int cellbody;     /* Address of next cell body */
53981   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
53982   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
53983   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
53984
53985   assert( pPage->nOverflow==0 );
53986   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53987   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
53988             && (int)MX_CELL(pPage->pBt)<=10921);
53989   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53990
53991   /* Check that the page has just been zeroed by zeroPage() */
53992   assert( pPage->nCell==0 );
53993   assert( get2byteNotZero(&data[hdr+5])==nUsable );
53994
53995   pCellptr = &pPage->aCellIdx[nCell*2];
53996   cellbody = nUsable;
53997   for(i=nCell-1; i>=0; i--){
53998     u16 sz = aSize[i];
53999     pCellptr -= 2;
54000     cellbody -= sz;
54001     put2byte(pCellptr, cellbody);
54002     memcpy(&data[cellbody], apCell[i], sz);
54003   }
54004   put2byte(&data[hdr+3], nCell);
54005   put2byte(&data[hdr+5], cellbody);
54006   pPage->nFree -= (nCell*2 + nUsable - cellbody);
54007   pPage->nCell = (u16)nCell;
54008 }
54009
54010 /*
54011 ** The following parameters determine how many adjacent pages get involved
54012 ** in a balancing operation.  NN is the number of neighbors on either side
54013 ** of the page that participate in the balancing operation.  NB is the
54014 ** total number of pages that participate, including the target page and
54015 ** NN neighbors on either side.
54016 **
54017 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
54018 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
54019 ** in exchange for a larger degradation in INSERT and UPDATE performance.
54020 ** The value of NN appears to give the best results overall.
54021 */
54022 #define NN 1             /* Number of neighbors on either side of pPage */
54023 #define NB (NN*2+1)      /* Total pages involved in the balance */
54024
54025
54026 #ifndef SQLITE_OMIT_QUICKBALANCE
54027 /*
54028 ** This version of balance() handles the common special case where
54029 ** a new entry is being inserted on the extreme right-end of the
54030 ** tree, in other words, when the new entry will become the largest
54031 ** entry in the tree.
54032 **
54033 ** Instead of trying to balance the 3 right-most leaf pages, just add
54034 ** a new page to the right-hand side and put the one new entry in
54035 ** that page.  This leaves the right side of the tree somewhat
54036 ** unbalanced.  But odds are that we will be inserting new entries
54037 ** at the end soon afterwards so the nearly empty page will quickly
54038 ** fill up.  On average.
54039 **
54040 ** pPage is the leaf page which is the right-most page in the tree.
54041 ** pParent is its parent.  pPage must have a single overflow entry
54042 ** which is also the right-most entry on the page.
54043 **
54044 ** The pSpace buffer is used to store a temporary copy of the divider
54045 ** cell that will be inserted into pParent. Such a cell consists of a 4
54046 ** byte page number followed by a variable length integer. In other
54047 ** words, at most 13 bytes. Hence the pSpace buffer must be at
54048 ** least 13 bytes in size.
54049 */
54050 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
54051   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
54052   MemPage *pNew;                       /* Newly allocated page */
54053   int rc;                              /* Return Code */
54054   Pgno pgnoNew;                        /* Page number of pNew */
54055
54056   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54057   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54058   assert( pPage->nOverflow==1 );
54059
54060   /* This error condition is now caught prior to reaching this function */
54061   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
54062
54063   /* Allocate a new page. This page will become the right-sibling of 
54064   ** pPage. Make the parent page writable, so that the new divider cell
54065   ** may be inserted. If both these operations are successful, proceed.
54066   */
54067   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
54068
54069   if( rc==SQLITE_OK ){
54070
54071     u8 *pOut = &pSpace[4];
54072     u8 *pCell = pPage->apOvfl[0];
54073     u16 szCell = cellSizePtr(pPage, pCell);
54074     u8 *pStop;
54075
54076     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
54077     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
54078     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
54079     assemblePage(pNew, 1, &pCell, &szCell);
54080
54081     /* If this is an auto-vacuum database, update the pointer map
54082     ** with entries for the new page, and any pointer from the 
54083     ** cell on the page to an overflow page. If either of these
54084     ** operations fails, the return code is set, but the contents
54085     ** of the parent page are still manipulated by thh code below.
54086     ** That is Ok, at this point the parent page is guaranteed to
54087     ** be marked as dirty. Returning an error code will cause a
54088     ** rollback, undoing any changes made to the parent page.
54089     */
54090     if( ISAUTOVACUUM ){
54091       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
54092       if( szCell>pNew->minLocal ){
54093         ptrmapPutOvflPtr(pNew, pCell, &rc);
54094       }
54095     }
54096   
54097     /* Create a divider cell to insert into pParent. The divider cell
54098     ** consists of a 4-byte page number (the page number of pPage) and
54099     ** a variable length key value (which must be the same value as the
54100     ** largest key on pPage).
54101     **
54102     ** To find the largest key value on pPage, first find the right-most 
54103     ** cell on pPage. The first two fields of this cell are the 
54104     ** record-length (a variable length integer at most 32-bits in size)
54105     ** and the key value (a variable length integer, may have any value).
54106     ** The first of the while(...) loops below skips over the record-length
54107     ** field. The second while(...) loop copies the key value from the
54108     ** cell on pPage into the pSpace buffer.
54109     */
54110     pCell = findCell(pPage, pPage->nCell-1);
54111     pStop = &pCell[9];
54112     while( (*(pCell++)&0x80) && pCell<pStop );
54113     pStop = &pCell[9];
54114     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
54115
54116     /* Insert the new divider cell into pParent. */
54117     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
54118                0, pPage->pgno, &rc);
54119
54120     /* Set the right-child pointer of pParent to point to the new page. */
54121     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
54122   
54123     /* Release the reference to the new page. */
54124     releasePage(pNew);
54125   }
54126
54127   return rc;
54128 }
54129 #endif /* SQLITE_OMIT_QUICKBALANCE */
54130
54131 #if 0
54132 /*
54133 ** This function does not contribute anything to the operation of SQLite.
54134 ** it is sometimes activated temporarily while debugging code responsible 
54135 ** for setting pointer-map entries.
54136 */
54137 static int ptrmapCheckPages(MemPage **apPage, int nPage){
54138   int i, j;
54139   for(i=0; i<nPage; i++){
54140     Pgno n;
54141     u8 e;
54142     MemPage *pPage = apPage[i];
54143     BtShared *pBt = pPage->pBt;
54144     assert( pPage->isInit );
54145
54146     for(j=0; j<pPage->nCell; j++){
54147       CellInfo info;
54148       u8 *z;
54149      
54150       z = findCell(pPage, j);
54151       btreeParseCellPtr(pPage, z, &info);
54152       if( info.iOverflow ){
54153         Pgno ovfl = get4byte(&z[info.iOverflow]);
54154         ptrmapGet(pBt, ovfl, &e, &n);
54155         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
54156       }
54157       if( !pPage->leaf ){
54158         Pgno child = get4byte(z);
54159         ptrmapGet(pBt, child, &e, &n);
54160         assert( n==pPage->pgno && e==PTRMAP_BTREE );
54161       }
54162     }
54163     if( !pPage->leaf ){
54164       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54165       ptrmapGet(pBt, child, &e, &n);
54166       assert( n==pPage->pgno && e==PTRMAP_BTREE );
54167     }
54168   }
54169   return 1;
54170 }
54171 #endif
54172
54173 /*
54174 ** This function is used to copy the contents of the b-tree node stored 
54175 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
54176 ** the pointer-map entries for each child page are updated so that the
54177 ** parent page stored in the pointer map is page pTo. If pFrom contained
54178 ** any cells with overflow page pointers, then the corresponding pointer
54179 ** map entries are also updated so that the parent page is page pTo.
54180 **
54181 ** If pFrom is currently carrying any overflow cells (entries in the
54182 ** MemPage.apOvfl[] array), they are not copied to pTo. 
54183 **
54184 ** Before returning, page pTo is reinitialized using btreeInitPage().
54185 **
54186 ** The performance of this function is not critical. It is only used by 
54187 ** the balance_shallower() and balance_deeper() procedures, neither of
54188 ** which are called often under normal circumstances.
54189 */
54190 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
54191   if( (*pRC)==SQLITE_OK ){
54192     BtShared * const pBt = pFrom->pBt;
54193     u8 * const aFrom = pFrom->aData;
54194     u8 * const aTo = pTo->aData;
54195     int const iFromHdr = pFrom->hdrOffset;
54196     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
54197     int rc;
54198     int iData;
54199   
54200   
54201     assert( pFrom->isInit );
54202     assert( pFrom->nFree>=iToHdr );
54203     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
54204   
54205     /* Copy the b-tree node content from page pFrom to page pTo. */
54206     iData = get2byte(&aFrom[iFromHdr+5]);
54207     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
54208     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
54209   
54210     /* Reinitialize page pTo so that the contents of the MemPage structure
54211     ** match the new data. The initialization of pTo can actually fail under
54212     ** fairly obscure circumstances, even though it is a copy of initialized 
54213     ** page pFrom.
54214     */
54215     pTo->isInit = 0;
54216     rc = btreeInitPage(pTo);
54217     if( rc!=SQLITE_OK ){
54218       *pRC = rc;
54219       return;
54220     }
54221   
54222     /* If this is an auto-vacuum database, update the pointer-map entries
54223     ** for any b-tree or overflow pages that pTo now contains the pointers to.
54224     */
54225     if( ISAUTOVACUUM ){
54226       *pRC = setChildPtrmaps(pTo);
54227     }
54228   }
54229 }
54230
54231 /*
54232 ** This routine redistributes cells on the iParentIdx'th child of pParent
54233 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
54234 ** same amount of free space. Usually a single sibling on either side of the
54235 ** page are used in the balancing, though both siblings might come from one
54236 ** side if the page is the first or last child of its parent. If the page 
54237 ** has fewer than 2 siblings (something which can only happen if the page
54238 ** is a root page or a child of a root page) then all available siblings
54239 ** participate in the balancing.
54240 **
54241 ** The number of siblings of the page might be increased or decreased by 
54242 ** one or two in an effort to keep pages nearly full but not over full. 
54243 **
54244 ** Note that when this routine is called, some of the cells on the page
54245 ** might not actually be stored in MemPage.aData[]. This can happen
54246 ** if the page is overfull. This routine ensures that all cells allocated
54247 ** to the page and its siblings fit into MemPage.aData[] before returning.
54248 **
54249 ** In the course of balancing the page and its siblings, cells may be
54250 ** inserted into or removed from the parent page (pParent). Doing so
54251 ** may cause the parent page to become overfull or underfull. If this
54252 ** happens, it is the responsibility of the caller to invoke the correct
54253 ** balancing routine to fix this problem (see the balance() routine). 
54254 **
54255 ** If this routine fails for any reason, it might leave the database
54256 ** in a corrupted state. So if this routine fails, the database should
54257 ** be rolled back.
54258 **
54259 ** The third argument to this function, aOvflSpace, is a pointer to a
54260 ** buffer big enough to hold one page. If while inserting cells into the parent
54261 ** page (pParent) the parent page becomes overfull, this buffer is
54262 ** used to store the parent's overflow cells. Because this function inserts
54263 ** a maximum of four divider cells into the parent page, and the maximum
54264 ** size of a cell stored within an internal node is always less than 1/4
54265 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
54266 ** enough for all overflow cells.
54267 **
54268 ** If aOvflSpace is set to a null pointer, this function returns 
54269 ** SQLITE_NOMEM.
54270 */
54271 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
54272 #pragma optimize("", off)
54273 #endif
54274 static int balance_nonroot(
54275   MemPage *pParent,               /* Parent page of siblings being balanced */
54276   int iParentIdx,                 /* Index of "the page" in pParent */
54277   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
54278   int isRoot,                     /* True if pParent is a root-page */
54279   int bBulk                       /* True if this call is part of a bulk load */
54280 ){
54281   BtShared *pBt;               /* The whole database */
54282   int nCell = 0;               /* Number of cells in apCell[] */
54283   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
54284   int nNew = 0;                /* Number of pages in apNew[] */
54285   int nOld;                    /* Number of pages in apOld[] */
54286   int i, j, k;                 /* Loop counters */
54287   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
54288   int rc = SQLITE_OK;          /* The return code */
54289   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
54290   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
54291   int usableSpace;             /* Bytes in pPage beyond the header */
54292   int pageFlags;               /* Value of pPage->aData[0] */
54293   int subtotal;                /* Subtotal of bytes in cells on one page */
54294   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
54295   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
54296   int szScratch;               /* Size of scratch memory requested */
54297   MemPage *apOld[NB];          /* pPage and up to two siblings */
54298   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
54299   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
54300   u8 *pRight;                  /* Location in parent of right-sibling pointer */
54301   u8 *apDiv[NB-1];             /* Divider cells in pParent */
54302   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
54303   int szNew[NB+2];             /* Combined size of cells place on i-th page */
54304   u8 **apCell = 0;             /* All cells begin balanced */
54305   u16 *szCell;                 /* Local size of all cells in apCell[] */
54306   u8 *aSpace1;                 /* Space for copies of dividers cells */
54307   Pgno pgno;                   /* Temp var to store a page number in */
54308
54309   pBt = pParent->pBt;
54310   assert( sqlite3_mutex_held(pBt->mutex) );
54311   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54312
54313 #if 0
54314   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
54315 #endif
54316
54317   /* At this point pParent may have at most one overflow cell. And if
54318   ** this overflow cell is present, it must be the cell with 
54319   ** index iParentIdx. This scenario comes about when this function
54320   ** is called (indirectly) from sqlite3BtreeDelete().
54321   */
54322   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
54323   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
54324
54325   if( !aOvflSpace ){
54326     return SQLITE_NOMEM;
54327   }
54328
54329   /* Find the sibling pages to balance. Also locate the cells in pParent 
54330   ** that divide the siblings. An attempt is made to find NN siblings on 
54331   ** either side of pPage. More siblings are taken from one side, however, 
54332   ** if there are fewer than NN siblings on the other side. If pParent
54333   ** has NB or fewer children then all children of pParent are taken.  
54334   **
54335   ** This loop also drops the divider cells from the parent page. This
54336   ** way, the remainder of the function does not have to deal with any
54337   ** overflow cells in the parent page, since if any existed they will
54338   ** have already been removed.
54339   */
54340   i = pParent->nOverflow + pParent->nCell;
54341   if( i<2 ){
54342     nxDiv = 0;
54343   }else{
54344     assert( bBulk==0 || bBulk==1 );
54345     if( iParentIdx==0 ){                 
54346       nxDiv = 0;
54347     }else if( iParentIdx==i ){
54348       nxDiv = i-2+bBulk;
54349     }else{
54350       assert( bBulk==0 );
54351       nxDiv = iParentIdx-1;
54352     }
54353     i = 2-bBulk;
54354   }
54355   nOld = i+1;
54356   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
54357     pRight = &pParent->aData[pParent->hdrOffset+8];
54358   }else{
54359     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
54360   }
54361   pgno = get4byte(pRight);
54362   while( 1 ){
54363     rc = getAndInitPage(pBt, pgno, &apOld[i]);
54364     if( rc ){
54365       memset(apOld, 0, (i+1)*sizeof(MemPage*));
54366       goto balance_cleanup;
54367     }
54368     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
54369     if( (i--)==0 ) break;
54370
54371     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
54372       apDiv[i] = pParent->apOvfl[0];
54373       pgno = get4byte(apDiv[i]);
54374       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54375       pParent->nOverflow = 0;
54376     }else{
54377       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
54378       pgno = get4byte(apDiv[i]);
54379       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54380
54381       /* Drop the cell from the parent page. apDiv[i] still points to
54382       ** the cell within the parent, even though it has been dropped.
54383       ** This is safe because dropping a cell only overwrites the first
54384       ** four bytes of it, and this function does not need the first
54385       ** four bytes of the divider cell. So the pointer is safe to use
54386       ** later on.  
54387       **
54388       ** But not if we are in secure-delete mode. In secure-delete mode,
54389       ** the dropCell() routine will overwrite the entire cell with zeroes.
54390       ** In this case, temporarily copy the cell into the aOvflSpace[]
54391       ** buffer. It will be copied out again as soon as the aSpace[] buffer
54392       ** is allocated.  */
54393       if( pBt->btsFlags & BTS_SECURE_DELETE ){
54394         int iOff;
54395
54396         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
54397         if( (iOff+szNew[i])>(int)pBt->usableSize ){
54398           rc = SQLITE_CORRUPT_BKPT;
54399           memset(apOld, 0, (i+1)*sizeof(MemPage*));
54400           goto balance_cleanup;
54401         }else{
54402           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
54403           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
54404         }
54405       }
54406       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
54407     }
54408   }
54409
54410   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
54411   ** alignment */
54412   nMaxCells = (nMaxCells + 3)&~3;
54413
54414   /*
54415   ** Allocate space for memory structures
54416   */
54417   k = pBt->pageSize + ROUND8(sizeof(MemPage));
54418   szScratch =
54419        nMaxCells*sizeof(u8*)                       /* apCell */
54420      + nMaxCells*sizeof(u16)                       /* szCell */
54421      + pBt->pageSize                               /* aSpace1 */
54422      + k*nOld;                                     /* Page copies (apCopy) */
54423   apCell = sqlite3ScratchMalloc( szScratch ); 
54424   if( apCell==0 ){
54425     rc = SQLITE_NOMEM;
54426     goto balance_cleanup;
54427   }
54428   szCell = (u16*)&apCell[nMaxCells];
54429   aSpace1 = (u8*)&szCell[nMaxCells];
54430   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54431
54432   /*
54433   ** Load pointers to all cells on sibling pages and the divider cells
54434   ** into the local apCell[] array.  Make copies of the divider cells
54435   ** into space obtained from aSpace1[] and remove the divider cells
54436   ** from pParent.
54437   **
54438   ** If the siblings are on leaf pages, then the child pointers of the
54439   ** divider cells are stripped from the cells before they are copied
54440   ** into aSpace1[].  In this way, all cells in apCell[] are without
54441   ** child pointers.  If siblings are not leaves, then all cell in
54442   ** apCell[] include child pointers.  Either way, all cells in apCell[]
54443   ** are alike.
54444   **
54445   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
54446   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
54447   */
54448   leafCorrection = apOld[0]->leaf*4;
54449   leafData = apOld[0]->hasData;
54450   for(i=0; i<nOld; i++){
54451     int limit;
54452     
54453     /* Before doing anything else, take a copy of the i'th original sibling
54454     ** The rest of this function will use data from the copies rather
54455     ** that the original pages since the original pages will be in the
54456     ** process of being overwritten.  */
54457     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54458     memcpy(pOld, apOld[i], sizeof(MemPage));
54459     pOld->aData = (void*)&pOld[1];
54460     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54461
54462     limit = pOld->nCell+pOld->nOverflow;
54463     if( pOld->nOverflow>0 ){
54464       for(j=0; j<limit; j++){
54465         assert( nCell<nMaxCells );
54466         apCell[nCell] = findOverflowCell(pOld, j);
54467         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54468         nCell++;
54469       }
54470     }else{
54471       u8 *aData = pOld->aData;
54472       u16 maskPage = pOld->maskPage;
54473       u16 cellOffset = pOld->cellOffset;
54474       for(j=0; j<limit; j++){
54475         assert( nCell<nMaxCells );
54476         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54477         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54478         nCell++;
54479       }
54480     }       
54481     if( i<nOld-1 && !leafData){
54482       u16 sz = (u16)szNew[i];
54483       u8 *pTemp;
54484       assert( nCell<nMaxCells );
54485       szCell[nCell] = sz;
54486       pTemp = &aSpace1[iSpace1];
54487       iSpace1 += sz;
54488       assert( sz<=pBt->maxLocal+23 );
54489       assert( iSpace1 <= (int)pBt->pageSize );
54490       memcpy(pTemp, apDiv[i], sz);
54491       apCell[nCell] = pTemp+leafCorrection;
54492       assert( leafCorrection==0 || leafCorrection==4 );
54493       szCell[nCell] = szCell[nCell] - leafCorrection;
54494       if( !pOld->leaf ){
54495         assert( leafCorrection==0 );
54496         assert( pOld->hdrOffset==0 );
54497         /* The right pointer of the child page pOld becomes the left
54498         ** pointer of the divider cell */
54499         memcpy(apCell[nCell], &pOld->aData[8], 4);
54500       }else{
54501         assert( leafCorrection==4 );
54502         if( szCell[nCell]<4 ){
54503           /* Do not allow any cells smaller than 4 bytes. */
54504           szCell[nCell] = 4;
54505         }
54506       }
54507       nCell++;
54508     }
54509   }
54510
54511   /*
54512   ** Figure out the number of pages needed to hold all nCell cells.
54513   ** Store this number in "k".  Also compute szNew[] which is the total
54514   ** size of all cells on the i-th page and cntNew[] which is the index
54515   ** in apCell[] of the cell that divides page i from page i+1.  
54516   ** cntNew[k] should equal nCell.
54517   **
54518   ** Values computed by this block:
54519   **
54520   **           k: The total number of sibling pages
54521   **    szNew[i]: Spaced used on the i-th sibling page.
54522   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54523   **              the right of the i-th sibling page.
54524   ** usableSpace: Number of bytes of space available on each sibling.
54525   ** 
54526   */
54527   usableSpace = pBt->usableSize - 12 + leafCorrection;
54528   for(subtotal=k=i=0; i<nCell; i++){
54529     assert( i<nMaxCells );
54530     subtotal += szCell[i] + 2;
54531     if( subtotal > usableSpace ){
54532       szNew[k] = subtotal - szCell[i];
54533       cntNew[k] = i;
54534       if( leafData ){ i--; }
54535       subtotal = 0;
54536       k++;
54537       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54538     }
54539   }
54540   szNew[k] = subtotal;
54541   cntNew[k] = nCell;
54542   k++;
54543
54544   /*
54545   ** The packing computed by the previous block is biased toward the siblings
54546   ** on the left side.  The left siblings are always nearly full, while the
54547   ** right-most sibling might be nearly empty.  This block of code attempts
54548   ** to adjust the packing of siblings to get a better balance.
54549   **
54550   ** This adjustment is more than an optimization.  The packing above might
54551   ** be so out of balance as to be illegal.  For example, the right-most
54552   ** sibling might be completely empty.  This adjustment is not optional.
54553   */
54554   for(i=k-1; i>0; i--){
54555     int szRight = szNew[i];  /* Size of sibling on the right */
54556     int szLeft = szNew[i-1]; /* Size of sibling on the left */
54557     int r;              /* Index of right-most cell in left sibling */
54558     int d;              /* Index of first cell to the left of right sibling */
54559
54560     r = cntNew[i-1] - 1;
54561     d = r + 1 - leafData;
54562     assert( d<nMaxCells );
54563     assert( r<nMaxCells );
54564     while( szRight==0 
54565        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
54566     ){
54567       szRight += szCell[d] + 2;
54568       szLeft -= szCell[r] + 2;
54569       cntNew[i-1]--;
54570       r = cntNew[i-1] - 1;
54571       d = r + 1 - leafData;
54572     }
54573     szNew[i] = szRight;
54574     szNew[i-1] = szLeft;
54575   }
54576
54577   /* Either we found one or more cells (cntnew[0])>0) or pPage is
54578   ** a virtual root page.  A virtual root page is when the real root
54579   ** page is page 1 and we are the only child of that page.
54580   **
54581   ** UPDATE:  The assert() below is not necessarily true if the database
54582   ** file is corrupt.  The corruption will be detected and reported later
54583   ** in this procedure so there is no need to act upon it now.
54584   */
54585 #if 0
54586   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54587 #endif
54588
54589   TRACE(("BALANCE: old: %d %d %d  ",
54590     apOld[0]->pgno, 
54591     nOld>=2 ? apOld[1]->pgno : 0,
54592     nOld>=3 ? apOld[2]->pgno : 0
54593   ));
54594
54595   /*
54596   ** Allocate k new pages.  Reuse old pages where possible.
54597   */
54598   if( apOld[0]->pgno<=1 ){
54599     rc = SQLITE_CORRUPT_BKPT;
54600     goto balance_cleanup;
54601   }
54602   pageFlags = apOld[0]->aData[0];
54603   for(i=0; i<k; i++){
54604     MemPage *pNew;
54605     if( i<nOld ){
54606       pNew = apNew[i] = apOld[i];
54607       apOld[i] = 0;
54608       rc = sqlite3PagerWrite(pNew->pDbPage);
54609       nNew++;
54610       if( rc ) goto balance_cleanup;
54611     }else{
54612       assert( i>0 );
54613       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
54614       if( rc ) goto balance_cleanup;
54615       apNew[i] = pNew;
54616       nNew++;
54617
54618       /* Set the pointer-map entry for the new sibling page. */
54619       if( ISAUTOVACUUM ){
54620         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54621         if( rc!=SQLITE_OK ){
54622           goto balance_cleanup;
54623         }
54624       }
54625     }
54626   }
54627
54628   /* Free any old pages that were not reused as new pages.
54629   */
54630   while( i<nOld ){
54631     freePage(apOld[i], &rc);
54632     if( rc ) goto balance_cleanup;
54633     releasePage(apOld[i]);
54634     apOld[i] = 0;
54635     i++;
54636   }
54637
54638   /*
54639   ** Put the new pages in accending order.  This helps to
54640   ** keep entries in the disk file in order so that a scan
54641   ** of the table is a linear scan through the file.  That
54642   ** in turn helps the operating system to deliver pages
54643   ** from the disk more rapidly.
54644   **
54645   ** An O(n^2) insertion sort algorithm is used, but since
54646   ** n is never more than NB (a small constant), that should
54647   ** not be a problem.
54648   **
54649   ** When NB==3, this one optimization makes the database
54650   ** about 25% faster for large insertions and deletions.
54651   */
54652   for(i=0; i<k-1; i++){
54653     int minV = apNew[i]->pgno;
54654     int minI = i;
54655     for(j=i+1; j<k; j++){
54656       if( apNew[j]->pgno<(unsigned)minV ){
54657         minI = j;
54658         minV = apNew[j]->pgno;
54659       }
54660     }
54661     if( minI>i ){
54662       MemPage *pT;
54663       pT = apNew[i];
54664       apNew[i] = apNew[minI];
54665       apNew[minI] = pT;
54666     }
54667   }
54668   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54669     apNew[0]->pgno, szNew[0],
54670     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54671     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54672     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54673     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54674
54675   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54676   put4byte(pRight, apNew[nNew-1]->pgno);
54677
54678   /*
54679   ** Evenly distribute the data in apCell[] across the new pages.
54680   ** Insert divider cells into pParent as necessary.
54681   */
54682   j = 0;
54683   for(i=0; i<nNew; i++){
54684     /* Assemble the new sibling page. */
54685     MemPage *pNew = apNew[i];
54686     assert( j<nMaxCells );
54687     zeroPage(pNew, pageFlags);
54688     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54689     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54690     assert( pNew->nOverflow==0 );
54691
54692     j = cntNew[i];
54693
54694     /* If the sibling page assembled above was not the right-most sibling,
54695     ** insert a divider cell into the parent page.
54696     */
54697     assert( i<nNew-1 || j==nCell );
54698     if( j<nCell ){
54699       u8 *pCell;
54700       u8 *pTemp;
54701       int sz;
54702
54703       assert( j<nMaxCells );
54704       pCell = apCell[j];
54705       sz = szCell[j] + leafCorrection;
54706       pTemp = &aOvflSpace[iOvflSpace];
54707       if( !pNew->leaf ){
54708         memcpy(&pNew->aData[8], pCell, 4);
54709       }else if( leafData ){
54710         /* If the tree is a leaf-data tree, and the siblings are leaves, 
54711         ** then there is no divider cell in apCell[]. Instead, the divider 
54712         ** cell consists of the integer key for the right-most cell of 
54713         ** the sibling-page assembled above only.
54714         */
54715         CellInfo info;
54716         j--;
54717         btreeParseCellPtr(pNew, apCell[j], &info);
54718         pCell = pTemp;
54719         sz = 4 + putVarint(&pCell[4], info.nKey);
54720         pTemp = 0;
54721       }else{
54722         pCell -= 4;
54723         /* Obscure case for non-leaf-data trees: If the cell at pCell was
54724         ** previously stored on a leaf node, and its reported size was 4
54725         ** bytes, then it may actually be smaller than this 
54726         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54727         ** any cell). But it is important to pass the correct size to 
54728         ** insertCell(), so reparse the cell now.
54729         **
54730         ** Note that this can never happen in an SQLite data file, as all
54731         ** cells are at least 4 bytes. It only happens in b-trees used
54732         ** to evaluate "IN (SELECT ...)" and similar clauses.
54733         */
54734         if( szCell[j]==4 ){
54735           assert(leafCorrection==4);
54736           sz = cellSizePtr(pParent, pCell);
54737         }
54738       }
54739       iOvflSpace += sz;
54740       assert( sz<=pBt->maxLocal+23 );
54741       assert( iOvflSpace <= (int)pBt->pageSize );
54742       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54743       if( rc!=SQLITE_OK ) goto balance_cleanup;
54744       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54745
54746       j++;
54747       nxDiv++;
54748     }
54749   }
54750   assert( j==nCell );
54751   assert( nOld>0 );
54752   assert( nNew>0 );
54753   if( (pageFlags & PTF_LEAF)==0 ){
54754     u8 *zChild = &apCopy[nOld-1]->aData[8];
54755     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54756   }
54757
54758   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54759     /* The root page of the b-tree now contains no cells. The only sibling
54760     ** page is the right-child of the parent. Copy the contents of the
54761     ** child page into the parent, decreasing the overall height of the
54762     ** b-tree structure by one. This is described as the "balance-shallower"
54763     ** sub-algorithm in some documentation.
54764     **
54765     ** If this is an auto-vacuum database, the call to copyNodeContent() 
54766     ** sets all pointer-map entries corresponding to database image pages 
54767     ** for which the pointer is stored within the content being copied.
54768     **
54769     ** The second assert below verifies that the child page is defragmented
54770     ** (it must be, as it was just reconstructed using assemblePage()). This
54771     ** is important if the parent page happens to be page 1 of the database
54772     ** image.  */
54773     assert( nNew==1 );
54774     assert( apNew[0]->nFree == 
54775         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
54776     );
54777     copyNodeContent(apNew[0], pParent, &rc);
54778     freePage(apNew[0], &rc);
54779   }else if( ISAUTOVACUUM ){
54780     /* Fix the pointer-map entries for all the cells that were shifted around. 
54781     ** There are several different types of pointer-map entries that need to
54782     ** be dealt with by this routine. Some of these have been set already, but
54783     ** many have not. The following is a summary:
54784     **
54785     **   1) The entries associated with new sibling pages that were not
54786     **      siblings when this function was called. These have already
54787     **      been set. We don't need to worry about old siblings that were
54788     **      moved to the free-list - the freePage() code has taken care
54789     **      of those.
54790     **
54791     **   2) The pointer-map entries associated with the first overflow
54792     **      page in any overflow chains used by new divider cells. These 
54793     **      have also already been taken care of by the insertCell() code.
54794     **
54795     **   3) If the sibling pages are not leaves, then the child pages of
54796     **      cells stored on the sibling pages may need to be updated.
54797     **
54798     **   4) If the sibling pages are not internal intkey nodes, then any
54799     **      overflow pages used by these cells may need to be updated
54800     **      (internal intkey nodes never contain pointers to overflow pages).
54801     **
54802     **   5) If the sibling pages are not leaves, then the pointer-map
54803     **      entries for the right-child pages of each sibling may need
54804     **      to be updated.
54805     **
54806     ** Cases 1 and 2 are dealt with above by other code. The next
54807     ** block deals with cases 3 and 4 and the one after that, case 5. Since
54808     ** setting a pointer map entry is a relatively expensive operation, this
54809     ** code only sets pointer map entries for child or overflow pages that have
54810     ** actually moved between pages.  */
54811     MemPage *pNew = apNew[0];
54812     MemPage *pOld = apCopy[0];
54813     int nOverflow = pOld->nOverflow;
54814     int iNextOld = pOld->nCell + nOverflow;
54815     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
54816     j = 0;                             /* Current 'old' sibling page */
54817     k = 0;                             /* Current 'new' sibling page */
54818     for(i=0; i<nCell; i++){
54819       int isDivider = 0;
54820       while( i==iNextOld ){
54821         /* Cell i is the cell immediately following the last cell on old
54822         ** sibling page j. If the siblings are not leaf pages of an
54823         ** intkey b-tree, then cell i was a divider cell. */
54824         assert( j+1 < ArraySize(apCopy) );
54825         assert( j+1 < nOld );
54826         pOld = apCopy[++j];
54827         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54828         if( pOld->nOverflow ){
54829           nOverflow = pOld->nOverflow;
54830           iOverflow = i + !leafData + pOld->aiOvfl[0];
54831         }
54832         isDivider = !leafData;  
54833       }
54834
54835       assert(nOverflow>0 || iOverflow<i );
54836       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
54837       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
54838       if( i==iOverflow ){
54839         isDivider = 1;
54840         if( (--nOverflow)>0 ){
54841           iOverflow++;
54842         }
54843       }
54844
54845       if( i==cntNew[k] ){
54846         /* Cell i is the cell immediately following the last cell on new
54847         ** sibling page k. If the siblings are not leaf pages of an
54848         ** intkey b-tree, then cell i is a divider cell.  */
54849         pNew = apNew[++k];
54850         if( !leafData ) continue;
54851       }
54852       assert( j<nOld );
54853       assert( k<nNew );
54854
54855       /* If the cell was originally divider cell (and is not now) or
54856       ** an overflow cell, or if the cell was located on a different sibling
54857       ** page before the balancing, then the pointer map entries associated
54858       ** with any child or overflow pages need to be updated.  */
54859       if( isDivider || pOld->pgno!=pNew->pgno ){
54860         if( !leafCorrection ){
54861           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
54862         }
54863         if( szCell[i]>pNew->minLocal ){
54864           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
54865         }
54866       }
54867     }
54868
54869     if( !leafCorrection ){
54870       for(i=0; i<nNew; i++){
54871         u32 key = get4byte(&apNew[i]->aData[8]);
54872         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
54873       }
54874     }
54875
54876 #if 0
54877     /* The ptrmapCheckPages() contains assert() statements that verify that
54878     ** all pointer map pages are set correctly. This is helpful while 
54879     ** debugging. This is usually disabled because a corrupt database may
54880     ** cause an assert() statement to fail.  */
54881     ptrmapCheckPages(apNew, nNew);
54882     ptrmapCheckPages(&pParent, 1);
54883 #endif
54884   }
54885
54886   assert( pParent->isInit );
54887   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
54888           nOld, nNew, nCell));
54889
54890   /*
54891   ** Cleanup before returning.
54892   */
54893 balance_cleanup:
54894   sqlite3ScratchFree(apCell);
54895   for(i=0; i<nOld; i++){
54896     releasePage(apOld[i]);
54897   }
54898   for(i=0; i<nNew; i++){
54899     releasePage(apNew[i]);
54900   }
54901
54902   return rc;
54903 }
54904 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
54905 #pragma optimize("", on)
54906 #endif
54907
54908
54909 /*
54910 ** This function is called when the root page of a b-tree structure is
54911 ** overfull (has one or more overflow pages).
54912 **
54913 ** A new child page is allocated and the contents of the current root
54914 ** page, including overflow cells, are copied into the child. The root
54915 ** page is then overwritten to make it an empty page with the right-child 
54916 ** pointer pointing to the new page.
54917 **
54918 ** Before returning, all pointer-map entries corresponding to pages 
54919 ** that the new child-page now contains pointers to are updated. The
54920 ** entry corresponding to the new right-child pointer of the root
54921 ** page is also updated.
54922 **
54923 ** If successful, *ppChild is set to contain a reference to the child 
54924 ** page and SQLITE_OK is returned. In this case the caller is required
54925 ** to call releasePage() on *ppChild exactly once. If an error occurs,
54926 ** an error code is returned and *ppChild is set to 0.
54927 */
54928 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
54929   int rc;                        /* Return value from subprocedures */
54930   MemPage *pChild = 0;           /* Pointer to a new child page */
54931   Pgno pgnoChild = 0;            /* Page number of the new child page */
54932   BtShared *pBt = pRoot->pBt;    /* The BTree */
54933
54934   assert( pRoot->nOverflow>0 );
54935   assert( sqlite3_mutex_held(pBt->mutex) );
54936
54937   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
54938   ** page that will become the new right-child of pPage. Copy the contents
54939   ** of the node stored on pRoot into the new child page.
54940   */
54941   rc = sqlite3PagerWrite(pRoot->pDbPage);
54942   if( rc==SQLITE_OK ){
54943     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
54944     copyNodeContent(pRoot, pChild, &rc);
54945     if( ISAUTOVACUUM ){
54946       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
54947     }
54948   }
54949   if( rc ){
54950     *ppChild = 0;
54951     releasePage(pChild);
54952     return rc;
54953   }
54954   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
54955   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54956   assert( pChild->nCell==pRoot->nCell );
54957
54958   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
54959
54960   /* Copy the overflow cells from pRoot to pChild */
54961   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
54962          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
54963   memcpy(pChild->apOvfl, pRoot->apOvfl,
54964          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
54965   pChild->nOverflow = pRoot->nOverflow;
54966
54967   /* Zero the contents of pRoot. Then install pChild as the right-child. */
54968   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
54969   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
54970
54971   *ppChild = pChild;
54972   return SQLITE_OK;
54973 }
54974
54975 /*
54976 ** The page that pCur currently points to has just been modified in
54977 ** some way. This function figures out if this modification means the
54978 ** tree needs to be balanced, and if so calls the appropriate balancing 
54979 ** routine. Balancing routines are:
54980 **
54981 **   balance_quick()
54982 **   balance_deeper()
54983 **   balance_nonroot()
54984 */
54985 static int balance(BtCursor *pCur){
54986   int rc = SQLITE_OK;
54987   const int nMin = pCur->pBt->usableSize * 2 / 3;
54988   u8 aBalanceQuickSpace[13];
54989   u8 *pFree = 0;
54990
54991   TESTONLY( int balance_quick_called = 0 );
54992   TESTONLY( int balance_deeper_called = 0 );
54993
54994   do {
54995     int iPage = pCur->iPage;
54996     MemPage *pPage = pCur->apPage[iPage];
54997
54998     if( iPage==0 ){
54999       if( pPage->nOverflow ){
55000         /* The root page of the b-tree is overfull. In this case call the
55001         ** balance_deeper() function to create a new child for the root-page
55002         ** and copy the current contents of the root-page to it. The
55003         ** next iteration of the do-loop will balance the child page.
55004         */ 
55005         assert( (balance_deeper_called++)==0 );
55006         rc = balance_deeper(pPage, &pCur->apPage[1]);
55007         if( rc==SQLITE_OK ){
55008           pCur->iPage = 1;
55009           pCur->aiIdx[0] = 0;
55010           pCur->aiIdx[1] = 0;
55011           assert( pCur->apPage[1]->nOverflow );
55012         }
55013       }else{
55014         break;
55015       }
55016     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
55017       break;
55018     }else{
55019       MemPage * const pParent = pCur->apPage[iPage-1];
55020       int const iIdx = pCur->aiIdx[iPage-1];
55021
55022       rc = sqlite3PagerWrite(pParent->pDbPage);
55023       if( rc==SQLITE_OK ){
55024 #ifndef SQLITE_OMIT_QUICKBALANCE
55025         if( pPage->hasData
55026          && pPage->nOverflow==1
55027          && pPage->aiOvfl[0]==pPage->nCell
55028          && pParent->pgno!=1
55029          && pParent->nCell==iIdx
55030         ){
55031           /* Call balance_quick() to create a new sibling of pPage on which
55032           ** to store the overflow cell. balance_quick() inserts a new cell
55033           ** into pParent, which may cause pParent overflow. If this
55034           ** happens, the next interation of the do-loop will balance pParent 
55035           ** use either balance_nonroot() or balance_deeper(). Until this
55036           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
55037           ** buffer. 
55038           **
55039           ** The purpose of the following assert() is to check that only a
55040           ** single call to balance_quick() is made for each call to this
55041           ** function. If this were not verified, a subtle bug involving reuse
55042           ** of the aBalanceQuickSpace[] might sneak in.
55043           */
55044           assert( (balance_quick_called++)==0 );
55045           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
55046         }else
55047 #endif
55048         {
55049           /* In this case, call balance_nonroot() to redistribute cells
55050           ** between pPage and up to 2 of its sibling pages. This involves
55051           ** modifying the contents of pParent, which may cause pParent to
55052           ** become overfull or underfull. The next iteration of the do-loop
55053           ** will balance the parent page to correct this.
55054           ** 
55055           ** If the parent page becomes overfull, the overflow cell or cells
55056           ** are stored in the pSpace buffer allocated immediately below. 
55057           ** A subsequent iteration of the do-loop will deal with this by
55058           ** calling balance_nonroot() (balance_deeper() may be called first,
55059           ** but it doesn't deal with overflow cells - just moves them to a
55060           ** different page). Once this subsequent call to balance_nonroot() 
55061           ** has completed, it is safe to release the pSpace buffer used by
55062           ** the previous call, as the overflow cell data will have been 
55063           ** copied either into the body of a database page or into the new
55064           ** pSpace buffer passed to the latter call to balance_nonroot().
55065           */
55066           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
55067           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
55068           if( pFree ){
55069             /* If pFree is not NULL, it points to the pSpace buffer used 
55070             ** by a previous call to balance_nonroot(). Its contents are
55071             ** now stored either on real database pages or within the 
55072             ** new pSpace buffer, so it may be safely freed here. */
55073             sqlite3PageFree(pFree);
55074           }
55075
55076           /* The pSpace buffer will be freed after the next call to
55077           ** balance_nonroot(), or just before this function returns, whichever
55078           ** comes first. */
55079           pFree = pSpace;
55080         }
55081       }
55082
55083       pPage->nOverflow = 0;
55084
55085       /* The next iteration of the do-loop balances the parent page. */
55086       releasePage(pPage);
55087       pCur->iPage--;
55088     }
55089   }while( rc==SQLITE_OK );
55090
55091   if( pFree ){
55092     sqlite3PageFree(pFree);
55093   }
55094   return rc;
55095 }
55096
55097
55098 /*
55099 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
55100 ** and the data is given by (pData,nData).  The cursor is used only to
55101 ** define what table the record should be inserted into.  The cursor
55102 ** is left pointing at a random location.
55103 **
55104 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
55105 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
55106 **
55107 ** If the seekResult parameter is non-zero, then a successful call to
55108 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
55109 ** been performed. seekResult is the search result returned (a negative
55110 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
55111 ** a positive value if pCur points at an etry that is larger than 
55112 ** (pKey, nKey)). 
55113 **
55114 ** If the seekResult parameter is non-zero, then the caller guarantees that
55115 ** cursor pCur is pointing at the existing copy of a row that is to be
55116 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
55117 ** point to any entry or to no entry at all and so this function has to seek
55118 ** the cursor before the new key can be inserted.
55119 */
55120 SQLITE_PRIVATE int sqlite3BtreeInsert(
55121   BtCursor *pCur,                /* Insert data into the table of this cursor */
55122   const void *pKey, i64 nKey,    /* The key of the new record */
55123   const void *pData, int nData,  /* The data of the new record */
55124   int nZero,                     /* Number of extra 0 bytes to append to data */
55125   int appendBias,                /* True if this is likely an append */
55126   int seekResult                 /* Result of prior MovetoUnpacked() call */
55127 ){
55128   int rc;
55129   int loc = seekResult;          /* -1: before desired location  +1: after */
55130   int szNew = 0;
55131   int idx;
55132   MemPage *pPage;
55133   Btree *p = pCur->pBtree;
55134   BtShared *pBt = p->pBt;
55135   unsigned char *oldCell;
55136   unsigned char *newCell = 0;
55137
55138   if( pCur->eState==CURSOR_FAULT ){
55139     assert( pCur->skipNext!=SQLITE_OK );
55140     return pCur->skipNext;
55141   }
55142
55143   assert( cursorHoldsMutex(pCur) );
55144   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
55145               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
55146   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55147
55148   /* Assert that the caller has been consistent. If this cursor was opened
55149   ** expecting an index b-tree, then the caller should be inserting blob
55150   ** keys with no associated data. If the cursor was opened expecting an
55151   ** intkey table, the caller should be inserting integer keys with a
55152   ** blob of associated data.  */
55153   assert( (pKey==0)==(pCur->pKeyInfo==0) );
55154
55155   /* Save the positions of any other cursors open on this table.
55156   **
55157   ** In some cases, the call to btreeMoveto() below is a no-op. For
55158   ** example, when inserting data into a table with auto-generated integer
55159   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
55160   ** integer key to use. It then calls this function to actually insert the 
55161   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
55162   ** that the cursor is already where it needs to be and returns without
55163   ** doing any work. To avoid thwarting these optimizations, it is important
55164   ** not to clear the cursor here.
55165   */
55166   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55167   if( rc ) return rc;
55168
55169   /* If this is an insert into a table b-tree, invalidate any incrblob 
55170   ** cursors open on the row being replaced (assuming this is a replace
55171   ** operation - if it is not, the following is a no-op).  */
55172   if( pCur->pKeyInfo==0 ){
55173     invalidateIncrblobCursors(p, nKey, 0);
55174   }
55175
55176   if( !loc ){
55177     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
55178     if( rc ) return rc;
55179   }
55180   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
55181
55182   pPage = pCur->apPage[pCur->iPage];
55183   assert( pPage->intKey || nKey>=0 );
55184   assert( pPage->leaf || !pPage->intKey );
55185
55186   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
55187           pCur->pgnoRoot, nKey, nData, pPage->pgno,
55188           loc==0 ? "overwrite" : "new entry"));
55189   assert( pPage->isInit );
55190   allocateTempSpace(pBt);
55191   newCell = pBt->pTmpSpace;
55192   if( newCell==0 ) return SQLITE_NOMEM;
55193   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
55194   if( rc ) goto end_insert;
55195   assert( szNew==cellSizePtr(pPage, newCell) );
55196   assert( szNew <= MX_CELL_SIZE(pBt) );
55197   idx = pCur->aiIdx[pCur->iPage];
55198   if( loc==0 ){
55199     u16 szOld;
55200     assert( idx<pPage->nCell );
55201     rc = sqlite3PagerWrite(pPage->pDbPage);
55202     if( rc ){
55203       goto end_insert;
55204     }
55205     oldCell = findCell(pPage, idx);
55206     if( !pPage->leaf ){
55207       memcpy(newCell, oldCell, 4);
55208     }
55209     szOld = cellSizePtr(pPage, oldCell);
55210     rc = clearCell(pPage, oldCell);
55211     dropCell(pPage, idx, szOld, &rc);
55212     if( rc ) goto end_insert;
55213   }else if( loc<0 && pPage->nCell>0 ){
55214     assert( pPage->leaf );
55215     idx = ++pCur->aiIdx[pCur->iPage];
55216   }else{
55217     assert( pPage->leaf );
55218   }
55219   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
55220   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
55221
55222   /* If no error has occured and pPage has an overflow cell, call balance() 
55223   ** to redistribute the cells within the tree. Since balance() may move
55224   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
55225   ** variables.
55226   **
55227   ** Previous versions of SQLite called moveToRoot() to move the cursor
55228   ** back to the root page as balance() used to invalidate the contents
55229   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
55230   ** set the cursor state to "invalid". This makes common insert operations
55231   ** slightly faster.
55232   **
55233   ** There is a subtle but important optimization here too. When inserting
55234   ** multiple records into an intkey b-tree using a single cursor (as can
55235   ** happen while processing an "INSERT INTO ... SELECT" statement), it
55236   ** is advantageous to leave the cursor pointing to the last entry in
55237   ** the b-tree if possible. If the cursor is left pointing to the last
55238   ** entry in the table, and the next row inserted has an integer key
55239   ** larger than the largest existing key, it is possible to insert the
55240   ** row without seeking the cursor. This can be a big performance boost.
55241   */
55242   pCur->info.nSize = 0;
55243   pCur->validNKey = 0;
55244   if( rc==SQLITE_OK && pPage->nOverflow ){
55245     rc = balance(pCur);
55246
55247     /* Must make sure nOverflow is reset to zero even if the balance()
55248     ** fails. Internal data structure corruption will result otherwise. 
55249     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
55250     ** from trying to save the current position of the cursor.  */
55251     pCur->apPage[pCur->iPage]->nOverflow = 0;
55252     pCur->eState = CURSOR_INVALID;
55253   }
55254   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
55255
55256 end_insert:
55257   return rc;
55258 }
55259
55260 /*
55261 ** Delete the entry that the cursor is pointing to.  The cursor
55262 ** is left pointing at a arbitrary location.
55263 */
55264 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
55265   Btree *p = pCur->pBtree;
55266   BtShared *pBt = p->pBt;              
55267   int rc;                              /* Return code */
55268   MemPage *pPage;                      /* Page to delete cell from */
55269   unsigned char *pCell;                /* Pointer to cell to delete */
55270   int iCellIdx;                        /* Index of cell to delete */
55271   int iCellDepth;                      /* Depth of node containing pCell */ 
55272
55273   assert( cursorHoldsMutex(pCur) );
55274   assert( pBt->inTransaction==TRANS_WRITE );
55275   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55276   assert( pCur->wrFlag );
55277   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55278   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
55279
55280   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
55281    || NEVER(pCur->eState!=CURSOR_VALID)
55282   ){
55283     return SQLITE_ERROR;  /* Something has gone awry. */
55284   }
55285
55286   iCellDepth = pCur->iPage;
55287   iCellIdx = pCur->aiIdx[iCellDepth];
55288   pPage = pCur->apPage[iCellDepth];
55289   pCell = findCell(pPage, iCellIdx);
55290
55291   /* If the page containing the entry to delete is not a leaf page, move
55292   ** the cursor to the largest entry in the tree that is smaller than
55293   ** the entry being deleted. This cell will replace the cell being deleted
55294   ** from the internal node. The 'previous' entry is used for this instead
55295   ** of the 'next' entry, as the previous entry is always a part of the
55296   ** sub-tree headed by the child page of the cell being deleted. This makes
55297   ** balancing the tree following the delete operation easier.  */
55298   if( !pPage->leaf ){
55299     int notUsed;
55300     rc = sqlite3BtreePrevious(pCur, &notUsed);
55301     if( rc ) return rc;
55302   }
55303
55304   /* Save the positions of any other cursors open on this table before
55305   ** making any modifications. Make the page containing the entry to be 
55306   ** deleted writable. Then free any overflow pages associated with the 
55307   ** entry and finally remove the cell itself from within the page.  
55308   */
55309   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55310   if( rc ) return rc;
55311
55312   /* If this is a delete operation to remove a row from a table b-tree,
55313   ** invalidate any incrblob cursors open on the row being deleted.  */
55314   if( pCur->pKeyInfo==0 ){
55315     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
55316   }
55317
55318   rc = sqlite3PagerWrite(pPage->pDbPage);
55319   if( rc ) return rc;
55320   rc = clearCell(pPage, pCell);
55321   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
55322   if( rc ) return rc;
55323
55324   /* If the cell deleted was not located on a leaf page, then the cursor
55325   ** is currently pointing to the largest entry in the sub-tree headed
55326   ** by the child-page of the cell that was just deleted from an internal
55327   ** node. The cell from the leaf node needs to be moved to the internal
55328   ** node to replace the deleted cell.  */
55329   if( !pPage->leaf ){
55330     MemPage *pLeaf = pCur->apPage[pCur->iPage];
55331     int nCell;
55332     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
55333     unsigned char *pTmp;
55334
55335     pCell = findCell(pLeaf, pLeaf->nCell-1);
55336     nCell = cellSizePtr(pLeaf, pCell);
55337     assert( MX_CELL_SIZE(pBt) >= nCell );
55338
55339     allocateTempSpace(pBt);
55340     pTmp = pBt->pTmpSpace;
55341
55342     rc = sqlite3PagerWrite(pLeaf->pDbPage);
55343     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
55344     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
55345     if( rc ) return rc;
55346   }
55347
55348   /* Balance the tree. If the entry deleted was located on a leaf page,
55349   ** then the cursor still points to that page. In this case the first
55350   ** call to balance() repairs the tree, and the if(...) condition is
55351   ** never true.
55352   **
55353   ** Otherwise, if the entry deleted was on an internal node page, then
55354   ** pCur is pointing to the leaf page from which a cell was removed to
55355   ** replace the cell deleted from the internal node. This is slightly
55356   ** tricky as the leaf node may be underfull, and the internal node may
55357   ** be either under or overfull. In this case run the balancing algorithm
55358   ** on the leaf node first. If the balance proceeds far enough up the
55359   ** tree that we can be sure that any problem in the internal node has
55360   ** been corrected, so be it. Otherwise, after balancing the leaf node,
55361   ** walk the cursor up the tree to the internal node and balance it as 
55362   ** well.  */
55363   rc = balance(pCur);
55364   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
55365     while( pCur->iPage>iCellDepth ){
55366       releasePage(pCur->apPage[pCur->iPage--]);
55367     }
55368     rc = balance(pCur);
55369   }
55370
55371   if( rc==SQLITE_OK ){
55372     moveToRoot(pCur);
55373   }
55374   return rc;
55375 }
55376
55377 /*
55378 ** Create a new BTree table.  Write into *piTable the page
55379 ** number for the root page of the new table.
55380 **
55381 ** The type of type is determined by the flags parameter.  Only the
55382 ** following values of flags are currently in use.  Other values for
55383 ** flags might not work:
55384 **
55385 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
55386 **     BTREE_ZERODATA                  Used for SQL indices
55387 */
55388 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
55389   BtShared *pBt = p->pBt;
55390   MemPage *pRoot;
55391   Pgno pgnoRoot;
55392   int rc;
55393   int ptfFlags;          /* Page-type flage for the root page of new table */
55394
55395   assert( sqlite3BtreeHoldsMutex(p) );
55396   assert( pBt->inTransaction==TRANS_WRITE );
55397   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55398
55399 #ifdef SQLITE_OMIT_AUTOVACUUM
55400   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55401   if( rc ){
55402     return rc;
55403   }
55404 #else
55405   if( pBt->autoVacuum ){
55406     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
55407     MemPage *pPageMove; /* The page to move to. */
55408
55409     /* Creating a new table may probably require moving an existing database
55410     ** to make room for the new tables root page. In case this page turns
55411     ** out to be an overflow page, delete all overflow page-map caches
55412     ** held by open cursors.
55413     */
55414     invalidateAllOverflowCache(pBt);
55415
55416     /* Read the value of meta[3] from the database to determine where the
55417     ** root page of the new table should go. meta[3] is the largest root-page
55418     ** created so far, so the new root-page is (meta[3]+1).
55419     */
55420     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55421     pgnoRoot++;
55422
55423     /* The new root-page may not be allocated on a pointer-map page, or the
55424     ** PENDING_BYTE page.
55425     */
55426     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55427         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55428       pgnoRoot++;
55429     }
55430     assert( pgnoRoot>=3 );
55431
55432     /* Allocate a page. The page that currently resides at pgnoRoot will
55433     ** be moved to the allocated page (unless the allocated page happens
55434     ** to reside at pgnoRoot).
55435     */
55436     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
55437     if( rc!=SQLITE_OK ){
55438       return rc;
55439     }
55440
55441     if( pgnoMove!=pgnoRoot ){
55442       /* pgnoRoot is the page that will be used for the root-page of
55443       ** the new table (assuming an error did not occur). But we were
55444       ** allocated pgnoMove. If required (i.e. if it was not allocated
55445       ** by extending the file), the current page at position pgnoMove
55446       ** is already journaled.
55447       */
55448       u8 eType = 0;
55449       Pgno iPtrPage = 0;
55450
55451       releasePage(pPageMove);
55452
55453       /* Move the page currently at pgnoRoot to pgnoMove. */
55454       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55455       if( rc!=SQLITE_OK ){
55456         return rc;
55457       }
55458       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55459       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55460         rc = SQLITE_CORRUPT_BKPT;
55461       }
55462       if( rc!=SQLITE_OK ){
55463         releasePage(pRoot);
55464         return rc;
55465       }
55466       assert( eType!=PTRMAP_ROOTPAGE );
55467       assert( eType!=PTRMAP_FREEPAGE );
55468       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55469       releasePage(pRoot);
55470
55471       /* Obtain the page at pgnoRoot */
55472       if( rc!=SQLITE_OK ){
55473         return rc;
55474       }
55475       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55476       if( rc!=SQLITE_OK ){
55477         return rc;
55478       }
55479       rc = sqlite3PagerWrite(pRoot->pDbPage);
55480       if( rc!=SQLITE_OK ){
55481         releasePage(pRoot);
55482         return rc;
55483       }
55484     }else{
55485       pRoot = pPageMove;
55486     } 
55487
55488     /* Update the pointer-map and meta-data with the new root-page number. */
55489     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55490     if( rc ){
55491       releasePage(pRoot);
55492       return rc;
55493     }
55494
55495     /* When the new root page was allocated, page 1 was made writable in
55496     ** order either to increase the database filesize, or to decrement the
55497     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55498     */
55499     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55500     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55501     if( NEVER(rc) ){
55502       releasePage(pRoot);
55503       return rc;
55504     }
55505
55506   }else{
55507     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55508     if( rc ) return rc;
55509   }
55510 #endif
55511   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55512   if( createTabFlags & BTREE_INTKEY ){
55513     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55514   }else{
55515     ptfFlags = PTF_ZERODATA | PTF_LEAF;
55516   }
55517   zeroPage(pRoot, ptfFlags);
55518   sqlite3PagerUnref(pRoot->pDbPage);
55519   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55520   *piTable = (int)pgnoRoot;
55521   return SQLITE_OK;
55522 }
55523 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55524   int rc;
55525   sqlite3BtreeEnter(p);
55526   rc = btreeCreateTable(p, piTable, flags);
55527   sqlite3BtreeLeave(p);
55528   return rc;
55529 }
55530
55531 /*
55532 ** Erase the given database page and all its children.  Return
55533 ** the page to the freelist.
55534 */
55535 static int clearDatabasePage(
55536   BtShared *pBt,           /* The BTree that contains the table */
55537   Pgno pgno,               /* Page number to clear */
55538   int freePageFlag,        /* Deallocate page if true */
55539   int *pnChange            /* Add number of Cells freed to this counter */
55540 ){
55541   MemPage *pPage;
55542   int rc;
55543   unsigned char *pCell;
55544   int i;
55545
55546   assert( sqlite3_mutex_held(pBt->mutex) );
55547   if( pgno>btreePagecount(pBt) ){
55548     return SQLITE_CORRUPT_BKPT;
55549   }
55550
55551   rc = getAndInitPage(pBt, pgno, &pPage);
55552   if( rc ) return rc;
55553   for(i=0; i<pPage->nCell; i++){
55554     pCell = findCell(pPage, i);
55555     if( !pPage->leaf ){
55556       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55557       if( rc ) goto cleardatabasepage_out;
55558     }
55559     rc = clearCell(pPage, pCell);
55560     if( rc ) goto cleardatabasepage_out;
55561   }
55562   if( !pPage->leaf ){
55563     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55564     if( rc ) goto cleardatabasepage_out;
55565   }else if( pnChange ){
55566     assert( pPage->intKey );
55567     *pnChange += pPage->nCell;
55568   }
55569   if( freePageFlag ){
55570     freePage(pPage, &rc);
55571   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55572     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55573   }
55574
55575 cleardatabasepage_out:
55576   releasePage(pPage);
55577   return rc;
55578 }
55579
55580 /*
55581 ** Delete all information from a single table in the database.  iTable is
55582 ** the page number of the root of the table.  After this routine returns,
55583 ** the root page is empty, but still exists.
55584 **
55585 ** This routine will fail with SQLITE_LOCKED if there are any open
55586 ** read cursors on the table.  Open write cursors are moved to the
55587 ** root of the table.
55588 **
55589 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55590 ** integer value pointed to by pnChange is incremented by the number of
55591 ** entries in the table.
55592 */
55593 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55594   int rc;
55595   BtShared *pBt = p->pBt;
55596   sqlite3BtreeEnter(p);
55597   assert( p->inTrans==TRANS_WRITE );
55598
55599   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55600
55601   if( SQLITE_OK==rc ){
55602     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55603     ** is the root of a table b-tree - if it is not, the following call is
55604     ** a no-op).  */
55605     invalidateIncrblobCursors(p, 0, 1);
55606     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55607   }
55608   sqlite3BtreeLeave(p);
55609   return rc;
55610 }
55611
55612 /*
55613 ** Erase all information in a table and add the root of the table to
55614 ** the freelist.  Except, the root of the principle table (the one on
55615 ** page 1) is never added to the freelist.
55616 **
55617 ** This routine will fail with SQLITE_LOCKED if there are any open
55618 ** cursors on the table.
55619 **
55620 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55621 ** root page in the database file, then the last root page 
55622 ** in the database file is moved into the slot formerly occupied by
55623 ** iTable and that last slot formerly occupied by the last root page
55624 ** is added to the freelist instead of iTable.  In this say, all
55625 ** root pages are kept at the beginning of the database file, which
55626 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
55627 ** page number that used to be the last root page in the file before
55628 ** the move.  If no page gets moved, *piMoved is set to 0.
55629 ** The last root page is recorded in meta[3] and the value of
55630 ** meta[3] is updated by this procedure.
55631 */
55632 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55633   int rc;
55634   MemPage *pPage = 0;
55635   BtShared *pBt = p->pBt;
55636
55637   assert( sqlite3BtreeHoldsMutex(p) );
55638   assert( p->inTrans==TRANS_WRITE );
55639
55640   /* It is illegal to drop a table if any cursors are open on the
55641   ** database. This is because in auto-vacuum mode the backend may
55642   ** need to move another root-page to fill a gap left by the deleted
55643   ** root page. If an open cursor was using this page a problem would 
55644   ** occur.
55645   **
55646   ** This error is caught long before control reaches this point.
55647   */
55648   if( NEVER(pBt->pCursor) ){
55649     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55650     return SQLITE_LOCKED_SHAREDCACHE;
55651   }
55652
55653   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55654   if( rc ) return rc;
55655   rc = sqlite3BtreeClearTable(p, iTable, 0);
55656   if( rc ){
55657     releasePage(pPage);
55658     return rc;
55659   }
55660
55661   *piMoved = 0;
55662
55663   if( iTable>1 ){
55664 #ifdef SQLITE_OMIT_AUTOVACUUM
55665     freePage(pPage, &rc);
55666     releasePage(pPage);
55667 #else
55668     if( pBt->autoVacuum ){
55669       Pgno maxRootPgno;
55670       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55671
55672       if( iTable==maxRootPgno ){
55673         /* If the table being dropped is the table with the largest root-page
55674         ** number in the database, put the root page on the free list. 
55675         */
55676         freePage(pPage, &rc);
55677         releasePage(pPage);
55678         if( rc!=SQLITE_OK ){
55679           return rc;
55680         }
55681       }else{
55682         /* The table being dropped does not have the largest root-page
55683         ** number in the database. So move the page that does into the 
55684         ** gap left by the deleted root-page.
55685         */
55686         MemPage *pMove;
55687         releasePage(pPage);
55688         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55689         if( rc!=SQLITE_OK ){
55690           return rc;
55691         }
55692         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55693         releasePage(pMove);
55694         if( rc!=SQLITE_OK ){
55695           return rc;
55696         }
55697         pMove = 0;
55698         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55699         freePage(pMove, &rc);
55700         releasePage(pMove);
55701         if( rc!=SQLITE_OK ){
55702           return rc;
55703         }
55704         *piMoved = maxRootPgno;
55705       }
55706
55707       /* Set the new 'max-root-page' value in the database header. This
55708       ** is the old value less one, less one more if that happens to
55709       ** be a root-page number, less one again if that is the
55710       ** PENDING_BYTE_PAGE.
55711       */
55712       maxRootPgno--;
55713       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55714              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55715         maxRootPgno--;
55716       }
55717       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55718
55719       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55720     }else{
55721       freePage(pPage, &rc);
55722       releasePage(pPage);
55723     }
55724 #endif
55725   }else{
55726     /* If sqlite3BtreeDropTable was called on page 1.
55727     ** This really never should happen except in a corrupt
55728     ** database. 
55729     */
55730     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55731     releasePage(pPage);
55732   }
55733   return rc;  
55734 }
55735 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55736   int rc;
55737   sqlite3BtreeEnter(p);
55738   rc = btreeDropTable(p, iTable, piMoved);
55739   sqlite3BtreeLeave(p);
55740   return rc;
55741 }
55742
55743
55744 /*
55745 ** This function may only be called if the b-tree connection already
55746 ** has a read or write transaction open on the database.
55747 **
55748 ** Read the meta-information out of a database file.  Meta[0]
55749 ** is the number of free pages currently in the database.  Meta[1]
55750 ** through meta[15] are available for use by higher layers.  Meta[0]
55751 ** is read-only, the others are read/write.
55752 ** 
55753 ** The schema layer numbers meta values differently.  At the schema
55754 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55755 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
55756 */
55757 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55758   BtShared *pBt = p->pBt;
55759
55760   sqlite3BtreeEnter(p);
55761   assert( p->inTrans>TRANS_NONE );
55762   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55763   assert( pBt->pPage1 );
55764   assert( idx>=0 && idx<=15 );
55765
55766   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55767
55768   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55769   ** database, mark the database as read-only.  */
55770 #ifdef SQLITE_OMIT_AUTOVACUUM
55771   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
55772     pBt->btsFlags |= BTS_READ_ONLY;
55773   }
55774 #endif
55775
55776   sqlite3BtreeLeave(p);
55777 }
55778
55779 /*
55780 ** Write meta-information back into the database.  Meta[0] is
55781 ** read-only and may not be written.
55782 */
55783 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55784   BtShared *pBt = p->pBt;
55785   unsigned char *pP1;
55786   int rc;
55787   assert( idx>=1 && idx<=15 );
55788   sqlite3BtreeEnter(p);
55789   assert( p->inTrans==TRANS_WRITE );
55790   assert( pBt->pPage1!=0 );
55791   pP1 = pBt->pPage1->aData;
55792   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55793   if( rc==SQLITE_OK ){
55794     put4byte(&pP1[36 + idx*4], iMeta);
55795 #ifndef SQLITE_OMIT_AUTOVACUUM
55796     if( idx==BTREE_INCR_VACUUM ){
55797       assert( pBt->autoVacuum || iMeta==0 );
55798       assert( iMeta==0 || iMeta==1 );
55799       pBt->incrVacuum = (u8)iMeta;
55800     }
55801 #endif
55802   }
55803   sqlite3BtreeLeave(p);
55804   return rc;
55805 }
55806
55807 #ifndef SQLITE_OMIT_BTREECOUNT
55808 /*
55809 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55810 ** number of entries in the b-tree and write the result to *pnEntry.
55811 **
55812 ** SQLITE_OK is returned if the operation is successfully executed. 
55813 ** Otherwise, if an error is encountered (i.e. an IO error or database
55814 ** corruption) an SQLite error code is returned.
55815 */
55816 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55817   i64 nEntry = 0;                      /* Value to return in *pnEntry */
55818   int rc;                              /* Return code */
55819
55820   if( pCur->pgnoRoot==0 ){
55821     *pnEntry = 0;
55822     return SQLITE_OK;
55823   }
55824   rc = moveToRoot(pCur);
55825
55826   /* Unless an error occurs, the following loop runs one iteration for each
55827   ** page in the B-Tree structure (not including overflow pages). 
55828   */
55829   while( rc==SQLITE_OK ){
55830     int iIdx;                          /* Index of child node in parent */
55831     MemPage *pPage;                    /* Current page of the b-tree */
55832
55833     /* If this is a leaf page or the tree is not an int-key tree, then 
55834     ** this page contains countable entries. Increment the entry counter
55835     ** accordingly.
55836     */
55837     pPage = pCur->apPage[pCur->iPage];
55838     if( pPage->leaf || !pPage->intKey ){
55839       nEntry += pPage->nCell;
55840     }
55841
55842     /* pPage is a leaf node. This loop navigates the cursor so that it 
55843     ** points to the first interior cell that it points to the parent of
55844     ** the next page in the tree that has not yet been visited. The
55845     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
55846     ** of the page, or to the number of cells in the page if the next page
55847     ** to visit is the right-child of its parent.
55848     **
55849     ** If all pages in the tree have been visited, return SQLITE_OK to the
55850     ** caller.
55851     */
55852     if( pPage->leaf ){
55853       do {
55854         if( pCur->iPage==0 ){
55855           /* All pages of the b-tree have been visited. Return successfully. */
55856           *pnEntry = nEntry;
55857           return SQLITE_OK;
55858         }
55859         moveToParent(pCur);
55860       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
55861
55862       pCur->aiIdx[pCur->iPage]++;
55863       pPage = pCur->apPage[pCur->iPage];
55864     }
55865
55866     /* Descend to the child node of the cell that the cursor currently 
55867     ** points at. This is the right-child if (iIdx==pPage->nCell).
55868     */
55869     iIdx = pCur->aiIdx[pCur->iPage];
55870     if( iIdx==pPage->nCell ){
55871       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
55872     }else{
55873       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
55874     }
55875   }
55876
55877   /* An error has occurred. Return an error code. */
55878   return rc;
55879 }
55880 #endif
55881
55882 /*
55883 ** Return the pager associated with a BTree.  This routine is used for
55884 ** testing and debugging only.
55885 */
55886 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
55887   return p->pBt->pPager;
55888 }
55889
55890 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55891 /*
55892 ** Append a message to the error message string.
55893 */
55894 static void checkAppendMsg(
55895   IntegrityCk *pCheck,
55896   char *zMsg1,
55897   const char *zFormat,
55898   ...
55899 ){
55900   va_list ap;
55901   if( !pCheck->mxErr ) return;
55902   pCheck->mxErr--;
55903   pCheck->nErr++;
55904   va_start(ap, zFormat);
55905   if( pCheck->errMsg.nChar ){
55906     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
55907   }
55908   if( zMsg1 ){
55909     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
55910   }
55911   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
55912   va_end(ap);
55913   if( pCheck->errMsg.mallocFailed ){
55914     pCheck->mallocFailed = 1;
55915   }
55916 }
55917 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55918
55919 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55920
55921 /*
55922 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
55923 ** corresponds to page iPg is already set.
55924 */
55925 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
55926   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
55927   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
55928 }
55929
55930 /*
55931 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
55932 */
55933 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
55934   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
55935   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
55936 }
55937
55938
55939 /*
55940 ** Add 1 to the reference count for page iPage.  If this is the second
55941 ** reference to the page, add an error message to pCheck->zErrMsg.
55942 ** Return 1 if there are 2 ore more references to the page and 0 if
55943 ** if this is the first reference to the page.
55944 **
55945 ** Also check that the page number is in bounds.
55946 */
55947 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
55948   if( iPage==0 ) return 1;
55949   if( iPage>pCheck->nPage ){
55950     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
55951     return 1;
55952   }
55953   if( getPageReferenced(pCheck, iPage) ){
55954     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
55955     return 1;
55956   }
55957   setPageReferenced(pCheck, iPage);
55958   return 0;
55959 }
55960
55961 #ifndef SQLITE_OMIT_AUTOVACUUM
55962 /*
55963 ** Check that the entry in the pointer-map for page iChild maps to 
55964 ** page iParent, pointer type ptrType. If not, append an error message
55965 ** to pCheck.
55966 */
55967 static void checkPtrmap(
55968   IntegrityCk *pCheck,   /* Integrity check context */
55969   Pgno iChild,           /* Child page number */
55970   u8 eType,              /* Expected pointer map type */
55971   Pgno iParent,          /* Expected pointer map parent page number */
55972   char *zContext         /* Context description (used for error msg) */
55973 ){
55974   int rc;
55975   u8 ePtrmapType;
55976   Pgno iPtrmapParent;
55977
55978   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
55979   if( rc!=SQLITE_OK ){
55980     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
55981     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
55982     return;
55983   }
55984
55985   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
55986     checkAppendMsg(pCheck, zContext, 
55987       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
55988       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
55989   }
55990 }
55991 #endif
55992
55993 /*
55994 ** Check the integrity of the freelist or of an overflow page list.
55995 ** Verify that the number of pages on the list is N.
55996 */
55997 static void checkList(
55998   IntegrityCk *pCheck,  /* Integrity checking context */
55999   int isFreeList,       /* True for a freelist.  False for overflow page list */
56000   int iPage,            /* Page number for first page in the list */
56001   int N,                /* Expected number of pages in the list */
56002   char *zContext        /* Context for error messages */
56003 ){
56004   int i;
56005   int expected = N;
56006   int iFirst = iPage;
56007   while( N-- > 0 && pCheck->mxErr ){
56008     DbPage *pOvflPage;
56009     unsigned char *pOvflData;
56010     if( iPage<1 ){
56011       checkAppendMsg(pCheck, zContext,
56012          "%d of %d pages missing from overflow list starting at %d",
56013           N+1, expected, iFirst);
56014       break;
56015     }
56016     if( checkRef(pCheck, iPage, zContext) ) break;
56017     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
56018       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
56019       break;
56020     }
56021     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
56022     if( isFreeList ){
56023       int n = get4byte(&pOvflData[4]);
56024 #ifndef SQLITE_OMIT_AUTOVACUUM
56025       if( pCheck->pBt->autoVacuum ){
56026         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
56027       }
56028 #endif
56029       if( n>(int)pCheck->pBt->usableSize/4-2 ){
56030         checkAppendMsg(pCheck, zContext,
56031            "freelist leaf count too big on page %d", iPage);
56032         N--;
56033       }else{
56034         for(i=0; i<n; i++){
56035           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
56036 #ifndef SQLITE_OMIT_AUTOVACUUM
56037           if( pCheck->pBt->autoVacuum ){
56038             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
56039           }
56040 #endif
56041           checkRef(pCheck, iFreePage, zContext);
56042         }
56043         N -= n;
56044       }
56045     }
56046 #ifndef SQLITE_OMIT_AUTOVACUUM
56047     else{
56048       /* If this database supports auto-vacuum and iPage is not the last
56049       ** page in this overflow list, check that the pointer-map entry for
56050       ** the following page matches iPage.
56051       */
56052       if( pCheck->pBt->autoVacuum && N>0 ){
56053         i = get4byte(pOvflData);
56054         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
56055       }
56056     }
56057 #endif
56058     iPage = get4byte(pOvflData);
56059     sqlite3PagerUnref(pOvflPage);
56060   }
56061 }
56062 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56063
56064 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56065 /*
56066 ** Do various sanity checks on a single page of a tree.  Return
56067 ** the tree depth.  Root pages return 0.  Parents of root pages
56068 ** return 1, and so forth.
56069 ** 
56070 ** These checks are done:
56071 **
56072 **      1.  Make sure that cells and freeblocks do not overlap
56073 **          but combine to completely cover the page.
56074 **  NO  2.  Make sure cell keys are in order.
56075 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
56076 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
56077 **      5.  Check the integrity of overflow pages.
56078 **      6.  Recursively call checkTreePage on all children.
56079 **      7.  Verify that the depth of all children is the same.
56080 **      8.  Make sure this page is at least 33% full or else it is
56081 **          the root of the tree.
56082 */
56083 static int checkTreePage(
56084   IntegrityCk *pCheck,  /* Context for the sanity check */
56085   int iPage,            /* Page number of the page to check */
56086   char *zParentContext, /* Parent context */
56087   i64 *pnParentMinKey, 
56088   i64 *pnParentMaxKey
56089 ){
56090   MemPage *pPage;
56091   int i, rc, depth, d2, pgno, cnt;
56092   int hdr, cellStart;
56093   int nCell;
56094   u8 *data;
56095   BtShared *pBt;
56096   int usableSize;
56097   char zContext[100];
56098   char *hit = 0;
56099   i64 nMinKey = 0;
56100   i64 nMaxKey = 0;
56101
56102   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
56103
56104   /* Check that the page exists
56105   */
56106   pBt = pCheck->pBt;
56107   usableSize = pBt->usableSize;
56108   if( iPage==0 ) return 0;
56109   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
56110   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
56111     checkAppendMsg(pCheck, zContext,
56112        "unable to get the page. error code=%d", rc);
56113     return 0;
56114   }
56115
56116   /* Clear MemPage.isInit to make sure the corruption detection code in
56117   ** btreeInitPage() is executed.  */
56118   pPage->isInit = 0;
56119   if( (rc = btreeInitPage(pPage))!=0 ){
56120     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
56121     checkAppendMsg(pCheck, zContext, 
56122                    "btreeInitPage() returns error code %d", rc);
56123     releasePage(pPage);
56124     return 0;
56125   }
56126
56127   /* Check out all the cells.
56128   */
56129   depth = 0;
56130   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
56131     u8 *pCell;
56132     u32 sz;
56133     CellInfo info;
56134
56135     /* Check payload overflow pages
56136     */
56137     sqlite3_snprintf(sizeof(zContext), zContext,
56138              "On tree page %d cell %d: ", iPage, i);
56139     pCell = findCell(pPage,i);
56140     btreeParseCellPtr(pPage, pCell, &info);
56141     sz = info.nData;
56142     if( !pPage->intKey ) sz += (int)info.nKey;
56143     /* For intKey pages, check that the keys are in order.
56144     */
56145     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
56146     else{
56147       if( info.nKey <= nMaxKey ){
56148         checkAppendMsg(pCheck, zContext, 
56149             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
56150       }
56151       nMaxKey = info.nKey;
56152     }
56153     assert( sz==info.nPayload );
56154     if( (sz>info.nLocal) 
56155      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
56156     ){
56157       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
56158       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
56159 #ifndef SQLITE_OMIT_AUTOVACUUM
56160       if( pBt->autoVacuum ){
56161         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
56162       }
56163 #endif
56164       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
56165     }
56166
56167     /* Check sanity of left child page.
56168     */
56169     if( !pPage->leaf ){
56170       pgno = get4byte(pCell);
56171 #ifndef SQLITE_OMIT_AUTOVACUUM
56172       if( pBt->autoVacuum ){
56173         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56174       }
56175 #endif
56176       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
56177       if( i>0 && d2!=depth ){
56178         checkAppendMsg(pCheck, zContext, "Child page depth differs");
56179       }
56180       depth = d2;
56181     }
56182   }
56183
56184   if( !pPage->leaf ){
56185     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56186     sqlite3_snprintf(sizeof(zContext), zContext, 
56187                      "On page %d at right child: ", iPage);
56188 #ifndef SQLITE_OMIT_AUTOVACUUM
56189     if( pBt->autoVacuum ){
56190       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56191     }
56192 #endif
56193     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
56194   }
56195  
56196   /* For intKey leaf pages, check that the min/max keys are in order
56197   ** with any left/parent/right pages.
56198   */
56199   if( pPage->leaf && pPage->intKey ){
56200     /* if we are a left child page */
56201     if( pnParentMinKey ){
56202       /* if we are the left most child page */
56203       if( !pnParentMaxKey ){
56204         if( nMaxKey > *pnParentMinKey ){
56205           checkAppendMsg(pCheck, zContext, 
56206               "Rowid %lld out of order (max larger than parent min of %lld)",
56207               nMaxKey, *pnParentMinKey);
56208         }
56209       }else{
56210         if( nMinKey <= *pnParentMinKey ){
56211           checkAppendMsg(pCheck, zContext, 
56212               "Rowid %lld out of order (min less than parent min of %lld)",
56213               nMinKey, *pnParentMinKey);
56214         }
56215         if( nMaxKey > *pnParentMaxKey ){
56216           checkAppendMsg(pCheck, zContext, 
56217               "Rowid %lld out of order (max larger than parent max of %lld)",
56218               nMaxKey, *pnParentMaxKey);
56219         }
56220         *pnParentMinKey = nMaxKey;
56221       }
56222     /* else if we're a right child page */
56223     } else if( pnParentMaxKey ){
56224       if( nMinKey <= *pnParentMaxKey ){
56225         checkAppendMsg(pCheck, zContext, 
56226             "Rowid %lld out of order (min less than parent max of %lld)",
56227             nMinKey, *pnParentMaxKey);
56228       }
56229     }
56230   }
56231
56232   /* Check for complete coverage of the page
56233   */
56234   data = pPage->aData;
56235   hdr = pPage->hdrOffset;
56236   hit = sqlite3PageMalloc( pBt->pageSize );
56237   if( hit==0 ){
56238     pCheck->mallocFailed = 1;
56239   }else{
56240     int contentOffset = get2byteNotZero(&data[hdr+5]);
56241     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
56242     memset(hit+contentOffset, 0, usableSize-contentOffset);
56243     memset(hit, 1, contentOffset);
56244     nCell = get2byte(&data[hdr+3]);
56245     cellStart = hdr + 12 - 4*pPage->leaf;
56246     for(i=0; i<nCell; i++){
56247       int pc = get2byte(&data[cellStart+i*2]);
56248       u32 size = 65536;
56249       int j;
56250       if( pc<=usableSize-4 ){
56251         size = cellSizePtr(pPage, &data[pc]);
56252       }
56253       if( (int)(pc+size-1)>=usableSize ){
56254         checkAppendMsg(pCheck, 0, 
56255             "Corruption detected in cell %d on page %d",i,iPage);
56256       }else{
56257         for(j=pc+size-1; j>=pc; j--) hit[j]++;
56258       }
56259     }
56260     i = get2byte(&data[hdr+1]);
56261     while( i>0 ){
56262       int size, j;
56263       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
56264       size = get2byte(&data[i+2]);
56265       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
56266       for(j=i+size-1; j>=i; j--) hit[j]++;
56267       j = get2byte(&data[i]);
56268       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
56269       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
56270       i = j;
56271     }
56272     for(i=cnt=0; i<usableSize; i++){
56273       if( hit[i]==0 ){
56274         cnt++;
56275       }else if( hit[i]>1 ){
56276         checkAppendMsg(pCheck, 0,
56277           "Multiple uses for byte %d of page %d", i, iPage);
56278         break;
56279       }
56280     }
56281     if( cnt!=data[hdr+7] ){
56282       checkAppendMsg(pCheck, 0, 
56283           "Fragmentation of %d bytes reported as %d on page %d",
56284           cnt, data[hdr+7], iPage);
56285     }
56286   }
56287   sqlite3PageFree(hit);
56288   releasePage(pPage);
56289   return depth+1;
56290 }
56291 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56292
56293 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56294 /*
56295 ** This routine does a complete check of the given BTree file.  aRoot[] is
56296 ** an array of pages numbers were each page number is the root page of
56297 ** a table.  nRoot is the number of entries in aRoot.
56298 **
56299 ** A read-only or read-write transaction must be opened before calling
56300 ** this function.
56301 **
56302 ** Write the number of error seen in *pnErr.  Except for some memory
56303 ** allocation errors,  an error message held in memory obtained from
56304 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
56305 ** returned.  If a memory allocation error occurs, NULL is returned.
56306 */
56307 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
56308   Btree *p,     /* The btree to be checked */
56309   int *aRoot,   /* An array of root pages numbers for individual trees */
56310   int nRoot,    /* Number of entries in aRoot[] */
56311   int mxErr,    /* Stop reporting errors after this many */
56312   int *pnErr    /* Write number of errors seen to this variable */
56313 ){
56314   Pgno i;
56315   int nRef;
56316   IntegrityCk sCheck;
56317   BtShared *pBt = p->pBt;
56318   char zErr[100];
56319
56320   sqlite3BtreeEnter(p);
56321   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
56322   nRef = sqlite3PagerRefcount(pBt->pPager);
56323   sCheck.pBt = pBt;
56324   sCheck.pPager = pBt->pPager;
56325   sCheck.nPage = btreePagecount(sCheck.pBt);
56326   sCheck.mxErr = mxErr;
56327   sCheck.nErr = 0;
56328   sCheck.mallocFailed = 0;
56329   *pnErr = 0;
56330   if( sCheck.nPage==0 ){
56331     sqlite3BtreeLeave(p);
56332     return 0;
56333   }
56334
56335   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
56336   if( !sCheck.aPgRef ){
56337     *pnErr = 1;
56338     sqlite3BtreeLeave(p);
56339     return 0;
56340   }
56341   i = PENDING_BYTE_PAGE(pBt);
56342   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
56343   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
56344   sCheck.errMsg.useMalloc = 2;
56345
56346   /* Check the integrity of the freelist
56347   */
56348   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
56349             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
56350
56351   /* Check all the tables.
56352   */
56353   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
56354     if( aRoot[i]==0 ) continue;
56355 #ifndef SQLITE_OMIT_AUTOVACUUM
56356     if( pBt->autoVacuum && aRoot[i]>1 ){
56357       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
56358     }
56359 #endif
56360     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
56361   }
56362
56363   /* Make sure every page in the file is referenced
56364   */
56365   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
56366 #ifdef SQLITE_OMIT_AUTOVACUUM
56367     if( getPageReferenced(&sCheck, i)==0 ){
56368       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56369     }
56370 #else
56371     /* If the database supports auto-vacuum, make sure no tables contain
56372     ** references to pointer-map pages.
56373     */
56374     if( getPageReferenced(&sCheck, i)==0 && 
56375        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
56376       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56377     }
56378     if( getPageReferenced(&sCheck, i)!=0 && 
56379        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
56380       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
56381     }
56382 #endif
56383   }
56384
56385   /* Make sure this analysis did not leave any unref() pages.
56386   ** This is an internal consistency check; an integrity check
56387   ** of the integrity check.
56388   */
56389   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
56390     checkAppendMsg(&sCheck, 0, 
56391       "Outstanding page count goes from %d to %d during this analysis",
56392       nRef, sqlite3PagerRefcount(pBt->pPager)
56393     );
56394   }
56395
56396   /* Clean  up and report errors.
56397   */
56398   sqlite3BtreeLeave(p);
56399   sqlite3_free(sCheck.aPgRef);
56400   if( sCheck.mallocFailed ){
56401     sqlite3StrAccumReset(&sCheck.errMsg);
56402     *pnErr = sCheck.nErr+1;
56403     return 0;
56404   }
56405   *pnErr = sCheck.nErr;
56406   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
56407   return sqlite3StrAccumFinish(&sCheck.errMsg);
56408 }
56409 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56410
56411 /*
56412 ** Return the full pathname of the underlying database file.  Return
56413 ** an empty string if the database is in-memory or a TEMP database.
56414 **
56415 ** The pager filename is invariant as long as the pager is
56416 ** open so it is safe to access without the BtShared mutex.
56417 */
56418 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56419   assert( p->pBt->pPager!=0 );
56420   return sqlite3PagerFilename(p->pBt->pPager, 1);
56421 }
56422
56423 /*
56424 ** Return the pathname of the journal file for this database. The return
56425 ** value of this routine is the same regardless of whether the journal file
56426 ** has been created or not.
56427 **
56428 ** The pager journal filename is invariant as long as the pager is
56429 ** open so it is safe to access without the BtShared mutex.
56430 */
56431 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56432   assert( p->pBt->pPager!=0 );
56433   return sqlite3PagerJournalname(p->pBt->pPager);
56434 }
56435
56436 /*
56437 ** Return non-zero if a transaction is active.
56438 */
56439 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56440   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56441   return (p && (p->inTrans==TRANS_WRITE));
56442 }
56443
56444 #ifndef SQLITE_OMIT_WAL
56445 /*
56446 ** Run a checkpoint on the Btree passed as the first argument.
56447 **
56448 ** Return SQLITE_LOCKED if this or any other connection has an open 
56449 ** transaction on the shared-cache the argument Btree is connected to.
56450 **
56451 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56452 */
56453 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56454   int rc = SQLITE_OK;
56455   if( p ){
56456     BtShared *pBt = p->pBt;
56457     sqlite3BtreeEnter(p);
56458     if( pBt->inTransaction!=TRANS_NONE ){
56459       rc = SQLITE_LOCKED;
56460     }else{
56461       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56462     }
56463     sqlite3BtreeLeave(p);
56464   }
56465   return rc;
56466 }
56467 #endif
56468
56469 /*
56470 ** Return non-zero if a read (or write) transaction is active.
56471 */
56472 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56473   assert( p );
56474   assert( sqlite3_mutex_held(p->db->mutex) );
56475   return p->inTrans!=TRANS_NONE;
56476 }
56477
56478 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56479   assert( p );
56480   assert( sqlite3_mutex_held(p->db->mutex) );
56481   return p->nBackup!=0;
56482 }
56483
56484 /*
56485 ** This function returns a pointer to a blob of memory associated with
56486 ** a single shared-btree. The memory is used by client code for its own
56487 ** purposes (for example, to store a high-level schema associated with 
56488 ** the shared-btree). The btree layer manages reference counting issues.
56489 **
56490 ** The first time this is called on a shared-btree, nBytes bytes of memory
56491 ** are allocated, zeroed, and returned to the caller. For each subsequent 
56492 ** call the nBytes parameter is ignored and a pointer to the same blob
56493 ** of memory returned. 
56494 **
56495 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56496 ** allocated, a null pointer is returned. If the blob has already been
56497 ** allocated, it is returned as normal.
56498 **
56499 ** Just before the shared-btree is closed, the function passed as the 
56500 ** xFree argument when the memory allocation was made is invoked on the 
56501 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56502 ** on the memory, the btree layer does that.
56503 */
56504 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56505   BtShared *pBt = p->pBt;
56506   sqlite3BtreeEnter(p);
56507   if( !pBt->pSchema && nBytes ){
56508     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56509     pBt->xFreeSchema = xFree;
56510   }
56511   sqlite3BtreeLeave(p);
56512   return pBt->pSchema;
56513 }
56514
56515 /*
56516 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
56517 ** btree as the argument handle holds an exclusive lock on the 
56518 ** sqlite_master table. Otherwise SQLITE_OK.
56519 */
56520 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56521   int rc;
56522   assert( sqlite3_mutex_held(p->db->mutex) );
56523   sqlite3BtreeEnter(p);
56524   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56525   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56526   sqlite3BtreeLeave(p);
56527   return rc;
56528 }
56529
56530
56531 #ifndef SQLITE_OMIT_SHARED_CACHE
56532 /*
56533 ** Obtain a lock on the table whose root page is iTab.  The
56534 ** lock is a write lock if isWritelock is true or a read lock
56535 ** if it is false.
56536 */
56537 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56538   int rc = SQLITE_OK;
56539   assert( p->inTrans!=TRANS_NONE );
56540   if( p->sharable ){
56541     u8 lockType = READ_LOCK + isWriteLock;
56542     assert( READ_LOCK+1==WRITE_LOCK );
56543     assert( isWriteLock==0 || isWriteLock==1 );
56544
56545     sqlite3BtreeEnter(p);
56546     rc = querySharedCacheTableLock(p, iTab, lockType);
56547     if( rc==SQLITE_OK ){
56548       rc = setSharedCacheTableLock(p, iTab, lockType);
56549     }
56550     sqlite3BtreeLeave(p);
56551   }
56552   return rc;
56553 }
56554 #endif
56555
56556 #ifndef SQLITE_OMIT_INCRBLOB
56557 /*
56558 ** Argument pCsr must be a cursor opened for writing on an 
56559 ** INTKEY table currently pointing at a valid table entry. 
56560 ** This function modifies the data stored as part of that entry.
56561 **
56562 ** Only the data content may only be modified, it is not possible to 
56563 ** change the length of the data stored. If this function is called with
56564 ** parameters that attempt to write past the end of the existing data,
56565 ** no modifications are made and SQLITE_CORRUPT is returned.
56566 */
56567 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56568   int rc;
56569   assert( cursorHoldsMutex(pCsr) );
56570   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56571   assert( pCsr->isIncrblobHandle );
56572
56573   rc = restoreCursorPosition(pCsr);
56574   if( rc!=SQLITE_OK ){
56575     return rc;
56576   }
56577   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56578   if( pCsr->eState!=CURSOR_VALID ){
56579     return SQLITE_ABORT;
56580   }
56581
56582   /* Check some assumptions: 
56583   **   (a) the cursor is open for writing,
56584   **   (b) there is a read/write transaction open,
56585   **   (c) the connection holds a write-lock on the table (if required),
56586   **   (d) there are no conflicting read-locks, and
56587   **   (e) the cursor points at a valid row of an intKey table.
56588   */
56589   if( !pCsr->wrFlag ){
56590     return SQLITE_READONLY;
56591   }
56592   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
56593               && pCsr->pBt->inTransaction==TRANS_WRITE );
56594   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56595   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56596   assert( pCsr->apPage[pCsr->iPage]->intKey );
56597
56598   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56599 }
56600
56601 /* 
56602 ** Set a flag on this cursor to cache the locations of pages from the 
56603 ** overflow list for the current row. This is used by cursors opened
56604 ** for incremental blob IO only.
56605 **
56606 ** This function sets a flag only. The actual page location cache
56607 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56608 ** accessPayload() (the worker function for sqlite3BtreeData() and
56609 ** sqlite3BtreePutData()).
56610 */
56611 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56612   assert( cursorHoldsMutex(pCur) );
56613   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56614   invalidateOverflowCache(pCur);
56615   pCur->isIncrblobHandle = 1;
56616 }
56617 #endif
56618
56619 /*
56620 ** Set both the "read version" (single byte at byte offset 18) and 
56621 ** "write version" (single byte at byte offset 19) fields in the database
56622 ** header to iVersion.
56623 */
56624 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56625   BtShared *pBt = pBtree->pBt;
56626   int rc;                         /* Return code */
56627  
56628   assert( iVersion==1 || iVersion==2 );
56629
56630   /* If setting the version fields to 1, do not automatically open the
56631   ** WAL connection, even if the version fields are currently set to 2.
56632   */
56633   pBt->btsFlags &= ~BTS_NO_WAL;
56634   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
56635
56636   rc = sqlite3BtreeBeginTrans(pBtree, 0);
56637   if( rc==SQLITE_OK ){
56638     u8 *aData = pBt->pPage1->aData;
56639     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56640       rc = sqlite3BtreeBeginTrans(pBtree, 2);
56641       if( rc==SQLITE_OK ){
56642         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56643         if( rc==SQLITE_OK ){
56644           aData[18] = (u8)iVersion;
56645           aData[19] = (u8)iVersion;
56646         }
56647       }
56648     }
56649   }
56650
56651   pBt->btsFlags &= ~BTS_NO_WAL;
56652   return rc;
56653 }
56654
56655 /*
56656 ** set the mask of hint flags for cursor pCsr. Currently the only valid
56657 ** values are 0 and BTREE_BULKLOAD.
56658 */
56659 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
56660   assert( mask==BTREE_BULKLOAD || mask==0 );
56661   pCsr->hints = mask;
56662 }
56663
56664 /************** End of btree.c ***********************************************/
56665 /************** Begin file backup.c ******************************************/
56666 /*
56667 ** 2009 January 28
56668 **
56669 ** The author disclaims copyright to this source code.  In place of
56670 ** a legal notice, here is a blessing:
56671 **
56672 **    May you do good and not evil.
56673 **    May you find forgiveness for yourself and forgive others.
56674 **    May you share freely, never taking more than you give.
56675 **
56676 *************************************************************************
56677 ** This file contains the implementation of the sqlite3_backup_XXX() 
56678 ** API functions and the related features.
56679 */
56680
56681 /* Macro to find the minimum of two numeric values.
56682 */
56683 #ifndef MIN
56684 # define MIN(x,y) ((x)<(y)?(x):(y))
56685 #endif
56686
56687 /*
56688 ** Structure allocated for each backup operation.
56689 */
56690 struct sqlite3_backup {
56691   sqlite3* pDestDb;        /* Destination database handle */
56692   Btree *pDest;            /* Destination b-tree file */
56693   u32 iDestSchema;         /* Original schema cookie in destination */
56694   int bDestLocked;         /* True once a write-transaction is open on pDest */
56695
56696   Pgno iNext;              /* Page number of the next source page to copy */
56697   sqlite3* pSrcDb;         /* Source database handle */
56698   Btree *pSrc;             /* Source b-tree file */
56699
56700   int rc;                  /* Backup process error code */
56701
56702   /* These two variables are set by every call to backup_step(). They are
56703   ** read by calls to backup_remaining() and backup_pagecount().
56704   */
56705   Pgno nRemaining;         /* Number of pages left to copy */
56706   Pgno nPagecount;         /* Total number of pages to copy */
56707
56708   int isAttached;          /* True once backup has been registered with pager */
56709   sqlite3_backup *pNext;   /* Next backup associated with source pager */
56710 };
56711
56712 /*
56713 ** THREAD SAFETY NOTES:
56714 **
56715 **   Once it has been created using backup_init(), a single sqlite3_backup
56716 **   structure may be accessed via two groups of thread-safe entry points:
56717 **
56718 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
56719 **       backup_finish(). Both these functions obtain the source database
56720 **       handle mutex and the mutex associated with the source BtShared 
56721 **       structure, in that order.
56722 **
56723 **     * Via the BackupUpdate() and BackupRestart() functions, which are
56724 **       invoked by the pager layer to report various state changes in
56725 **       the page cache associated with the source database. The mutex
56726 **       associated with the source database BtShared structure will always 
56727 **       be held when either of these functions are invoked.
56728 **
56729 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
56730 **   backup_pagecount() are not thread-safe functions. If they are called
56731 **   while some other thread is calling backup_step() or backup_finish(),
56732 **   the values returned may be invalid. There is no way for a call to
56733 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56734 **   or backup_pagecount().
56735 **
56736 **   Depending on the SQLite configuration, the database handles and/or
56737 **   the Btree objects may have their own mutexes that require locking.
56738 **   Non-sharable Btrees (in-memory databases for example), do not have
56739 **   associated mutexes.
56740 */
56741
56742 /*
56743 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56744 ** in connection handle pDb. If such a database cannot be found, return
56745 ** a NULL pointer and write an error message to pErrorDb.
56746 **
56747 ** If the "temp" database is requested, it may need to be opened by this 
56748 ** function. If an error occurs while doing so, return 0 and write an 
56749 ** error message to pErrorDb.
56750 */
56751 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56752   int i = sqlite3FindDbName(pDb, zDb);
56753
56754   if( i==1 ){
56755     Parse *pParse;
56756     int rc = 0;
56757     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56758     if( pParse==0 ){
56759       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56760       rc = SQLITE_NOMEM;
56761     }else{
56762       pParse->db = pDb;
56763       if( sqlite3OpenTempDatabase(pParse) ){
56764         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56765         rc = SQLITE_ERROR;
56766       }
56767       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56768       sqlite3StackFree(pErrorDb, pParse);
56769     }
56770     if( rc ){
56771       return 0;
56772     }
56773   }
56774
56775   if( i<0 ){
56776     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56777     return 0;
56778   }
56779
56780   return pDb->aDb[i].pBt;
56781 }
56782
56783 /*
56784 ** Attempt to set the page size of the destination to match the page size
56785 ** of the source.
56786 */
56787 static int setDestPgsz(sqlite3_backup *p){
56788   int rc;
56789   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56790   return rc;
56791 }
56792
56793 /*
56794 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56795 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56796 ** a pointer to the new sqlite3_backup object.
56797 **
56798 ** If an error occurs, NULL is returned and an error code and error message
56799 ** stored in database handle pDestDb.
56800 */
56801 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56802   sqlite3* pDestDb,                     /* Database to write to */
56803   const char *zDestDb,                  /* Name of database within pDestDb */
56804   sqlite3* pSrcDb,                      /* Database connection to read from */
56805   const char *zSrcDb                    /* Name of database within pSrcDb */
56806 ){
56807   sqlite3_backup *p;                    /* Value to return */
56808
56809   /* Lock the source database handle. The destination database
56810   ** handle is not locked in this routine, but it is locked in
56811   ** sqlite3_backup_step(). The user is required to ensure that no
56812   ** other thread accesses the destination handle for the duration
56813   ** of the backup operation.  Any attempt to use the destination
56814   ** database connection while a backup is in progress may cause
56815   ** a malfunction or a deadlock.
56816   */
56817   sqlite3_mutex_enter(pSrcDb->mutex);
56818   sqlite3_mutex_enter(pDestDb->mutex);
56819
56820   if( pSrcDb==pDestDb ){
56821     sqlite3Error(
56822         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56823     );
56824     p = 0;
56825   }else {
56826     /* Allocate space for a new sqlite3_backup object...
56827     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56828     ** call to sqlite3_backup_init() and is destroyed by a call to
56829     ** sqlite3_backup_finish(). */
56830     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
56831     if( !p ){
56832       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56833     }
56834   }
56835
56836   /* If the allocation succeeded, populate the new object. */
56837   if( p ){
56838     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56839     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
56840     p->pDestDb = pDestDb;
56841     p->pSrcDb = pSrcDb;
56842     p->iNext = 1;
56843     p->isAttached = 0;
56844
56845     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
56846       /* One (or both) of the named databases did not exist or an OOM
56847       ** error was hit.  The error has already been written into the
56848       ** pDestDb handle.  All that is left to do here is free the
56849       ** sqlite3_backup structure.
56850       */
56851       sqlite3_free(p);
56852       p = 0;
56853     }
56854   }
56855   if( p ){
56856     p->pSrc->nBackup++;
56857   }
56858
56859   sqlite3_mutex_leave(pDestDb->mutex);
56860   sqlite3_mutex_leave(pSrcDb->mutex);
56861   return p;
56862 }
56863
56864 /*
56865 ** Argument rc is an SQLite error code. Return true if this error is 
56866 ** considered fatal if encountered during a backup operation. All errors
56867 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
56868 */
56869 static int isFatalError(int rc){
56870   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
56871 }
56872
56873 /*
56874 ** Parameter zSrcData points to a buffer containing the data for 
56875 ** page iSrcPg from the source database. Copy this data into the 
56876 ** destination database.
56877 */
56878 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
56879   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
56880   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
56881   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
56882   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
56883   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
56884 #ifdef SQLITE_HAS_CODEC
56885   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
56886   ** guaranteed that the shared-mutex is held by this thread, handle
56887   ** p->pSrc may not actually be the owner.  */
56888   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
56889   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
56890 #endif
56891   int rc = SQLITE_OK;
56892   i64 iOff;
56893
56894   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
56895   assert( p->bDestLocked );
56896   assert( !isFatalError(p->rc) );
56897   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
56898   assert( zSrcData );
56899
56900   /* Catch the case where the destination is an in-memory database and the
56901   ** page sizes of the source and destination differ. 
56902   */
56903   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
56904     rc = SQLITE_READONLY;
56905   }
56906
56907 #ifdef SQLITE_HAS_CODEC
56908   /* Backup is not possible if the page size of the destination is changing
56909   ** and a codec is in use.
56910   */
56911   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
56912     rc = SQLITE_READONLY;
56913   }
56914
56915   /* Backup is not possible if the number of bytes of reserve space differ
56916   ** between source and destination.  If there is a difference, try to
56917   ** fix the destination to agree with the source.  If that is not possible,
56918   ** then the backup cannot proceed.
56919   */
56920   if( nSrcReserve!=nDestReserve ){
56921     u32 newPgsz = nSrcPgsz;
56922     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
56923     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
56924   }
56925 #endif
56926
56927   /* This loop runs once for each destination page spanned by the source 
56928   ** page. For each iteration, variable iOff is set to the byte offset
56929   ** of the destination page.
56930   */
56931   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
56932     DbPage *pDestPg = 0;
56933     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
56934     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
56935     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
56936      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
56937     ){
56938       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
56939       u8 *zDestData = sqlite3PagerGetData(pDestPg);
56940       u8 *zOut = &zDestData[iOff%nDestPgsz];
56941
56942       /* Copy the data from the source page into the destination page.
56943       ** Then clear the Btree layer MemPage.isInit flag. Both this module
56944       ** and the pager code use this trick (clearing the first byte
56945       ** of the page 'extra' space to invalidate the Btree layers
56946       ** cached parse of the page). MemPage.isInit is marked 
56947       ** "MUST BE FIRST" for this purpose.
56948       */
56949       memcpy(zOut, zIn, nCopy);
56950       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
56951     }
56952     sqlite3PagerUnref(pDestPg);
56953   }
56954
56955   return rc;
56956 }
56957
56958 /*
56959 ** If pFile is currently larger than iSize bytes, then truncate it to
56960 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
56961 ** this function is a no-op.
56962 **
56963 ** Return SQLITE_OK if everything is successful, or an SQLite error 
56964 ** code if an error occurs.
56965 */
56966 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
56967   i64 iCurrent;
56968   int rc = sqlite3OsFileSize(pFile, &iCurrent);
56969   if( rc==SQLITE_OK && iCurrent>iSize ){
56970     rc = sqlite3OsTruncate(pFile, iSize);
56971   }
56972   return rc;
56973 }
56974
56975 /*
56976 ** Register this backup object with the associated source pager for
56977 ** callbacks when pages are changed or the cache invalidated.
56978 */
56979 static void attachBackupObject(sqlite3_backup *p){
56980   sqlite3_backup **pp;
56981   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
56982   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56983   p->pNext = *pp;
56984   *pp = p;
56985   p->isAttached = 1;
56986 }
56987
56988 /*
56989 ** Copy nPage pages from the source b-tree to the destination.
56990 */
56991 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
56992   int rc;
56993   int destMode;       /* Destination journal mode */
56994   int pgszSrc = 0;    /* Source page size */
56995   int pgszDest = 0;   /* Destination page size */
56996
56997   sqlite3_mutex_enter(p->pSrcDb->mutex);
56998   sqlite3BtreeEnter(p->pSrc);
56999   if( p->pDestDb ){
57000     sqlite3_mutex_enter(p->pDestDb->mutex);
57001   }
57002
57003   rc = p->rc;
57004   if( !isFatalError(rc) ){
57005     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
57006     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
57007     int ii;                            /* Iterator variable */
57008     int nSrcPage = -1;                 /* Size of source db in pages */
57009     int bCloseTrans = 0;               /* True if src db requires unlocking */
57010
57011     /* If the source pager is currently in a write-transaction, return
57012     ** SQLITE_BUSY immediately.
57013     */
57014     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
57015       rc = SQLITE_BUSY;
57016     }else{
57017       rc = SQLITE_OK;
57018     }
57019
57020     /* Lock the destination database, if it is not locked already. */
57021     if( SQLITE_OK==rc && p->bDestLocked==0
57022      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
57023     ){
57024       p->bDestLocked = 1;
57025       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
57026     }
57027
57028     /* If there is no open read-transaction on the source database, open
57029     ** one now. If a transaction is opened here, then it will be closed
57030     ** before this function exits.
57031     */
57032     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
57033       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
57034       bCloseTrans = 1;
57035     }
57036
57037     /* Do not allow backup if the destination database is in WAL mode
57038     ** and the page sizes are different between source and destination */
57039     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
57040     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
57041     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
57042     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
57043       rc = SQLITE_READONLY;
57044     }
57045   
57046     /* Now that there is a read-lock on the source database, query the
57047     ** source pager for the number of pages in the database.
57048     */
57049     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
57050     assert( nSrcPage>=0 );
57051     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
57052       const Pgno iSrcPg = p->iNext;                 /* Source page number */
57053       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
57054         DbPage *pSrcPg;                             /* Source page object */
57055         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57056         if( rc==SQLITE_OK ){
57057           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
57058           sqlite3PagerUnref(pSrcPg);
57059         }
57060       }
57061       p->iNext++;
57062     }
57063     if( rc==SQLITE_OK ){
57064       p->nPagecount = nSrcPage;
57065       p->nRemaining = nSrcPage+1-p->iNext;
57066       if( p->iNext>(Pgno)nSrcPage ){
57067         rc = SQLITE_DONE;
57068       }else if( !p->isAttached ){
57069         attachBackupObject(p);
57070       }
57071     }
57072   
57073     /* Update the schema version field in the destination database. This
57074     ** is to make sure that the schema-version really does change in
57075     ** the case where the source and destination databases have the
57076     ** same schema version.
57077     */
57078     if( rc==SQLITE_DONE ){
57079       if( nSrcPage==0 ){
57080         rc = sqlite3BtreeNewDb(p->pDest);
57081         nSrcPage = 1;
57082       }
57083       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
57084         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
57085       }
57086       if( rc==SQLITE_OK ){
57087         if( p->pDestDb ){
57088           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
57089         }
57090         if( destMode==PAGER_JOURNALMODE_WAL ){
57091           rc = sqlite3BtreeSetVersion(p->pDest, 2);
57092         }
57093       }
57094       if( rc==SQLITE_OK ){
57095         int nDestTruncate;
57096         /* Set nDestTruncate to the final number of pages in the destination
57097         ** database. The complication here is that the destination page
57098         ** size may be different to the source page size. 
57099         **
57100         ** If the source page size is smaller than the destination page size, 
57101         ** round up. In this case the call to sqlite3OsTruncate() below will
57102         ** fix the size of the file. However it is important to call
57103         ** sqlite3PagerTruncateImage() here so that any pages in the 
57104         ** destination file that lie beyond the nDestTruncate page mark are
57105         ** journalled by PagerCommitPhaseOne() before they are destroyed
57106         ** by the file truncation.
57107         */
57108         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
57109         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
57110         if( pgszSrc<pgszDest ){
57111           int ratio = pgszDest/pgszSrc;
57112           nDestTruncate = (nSrcPage+ratio-1)/ratio;
57113           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
57114             nDestTruncate--;
57115           }
57116         }else{
57117           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
57118         }
57119         assert( nDestTruncate>0 );
57120         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
57121
57122         if( pgszSrc<pgszDest ){
57123           /* If the source page-size is smaller than the destination page-size,
57124           ** two extra things may need to happen:
57125           **
57126           **   * The destination may need to be truncated, and
57127           **
57128           **   * Data stored on the pages immediately following the 
57129           **     pending-byte page in the source database may need to be
57130           **     copied into the destination database.
57131           */
57132           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
57133           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
57134           i64 iOff;
57135           i64 iEnd;
57136
57137           assert( pFile );
57138           assert( nDestTruncate==0 
57139               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
57140                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
57141              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
57142           ));
57143
57144           /* This call ensures that all data required to recreate the original
57145           ** database has been stored in the journal for pDestPager and the
57146           ** journal synced to disk. So at this point we may safely modify
57147           ** the database file in any way, knowing that if a power failure
57148           ** occurs, the original database will be reconstructed from the 
57149           ** journal file.  */
57150           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
57151
57152           /* Write the extra pages and truncate the database file as required */
57153           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
57154           for(
57155             iOff=PENDING_BYTE+pgszSrc; 
57156             rc==SQLITE_OK && iOff<iEnd; 
57157             iOff+=pgszSrc
57158           ){
57159             PgHdr *pSrcPg = 0;
57160             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
57161             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57162             if( rc==SQLITE_OK ){
57163               u8 *zData = sqlite3PagerGetData(pSrcPg);
57164               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
57165             }
57166             sqlite3PagerUnref(pSrcPg);
57167           }
57168           if( rc==SQLITE_OK ){
57169             rc = backupTruncateFile(pFile, iSize);
57170           }
57171
57172           /* Sync the database file to disk. */
57173           if( rc==SQLITE_OK ){
57174             rc = sqlite3PagerSync(pDestPager);
57175           }
57176         }else{
57177           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
57178         }
57179     
57180         /* Finish committing the transaction to the destination database. */
57181         if( SQLITE_OK==rc
57182          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
57183         ){
57184           rc = SQLITE_DONE;
57185         }
57186       }
57187     }
57188   
57189     /* If bCloseTrans is true, then this function opened a read transaction
57190     ** on the source database. Close the read transaction here. There is
57191     ** no need to check the return values of the btree methods here, as
57192     ** "committing" a read-only transaction cannot fail.
57193     */
57194     if( bCloseTrans ){
57195       TESTONLY( int rc2 );
57196       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
57197       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
57198       assert( rc2==SQLITE_OK );
57199     }
57200   
57201     if( rc==SQLITE_IOERR_NOMEM ){
57202       rc = SQLITE_NOMEM;
57203     }
57204     p->rc = rc;
57205   }
57206   if( p->pDestDb ){
57207     sqlite3_mutex_leave(p->pDestDb->mutex);
57208   }
57209   sqlite3BtreeLeave(p->pSrc);
57210   sqlite3_mutex_leave(p->pSrcDb->mutex);
57211   return rc;
57212 }
57213
57214 /*
57215 ** Release all resources associated with an sqlite3_backup* handle.
57216 */
57217 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
57218   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
57219   sqlite3 *pSrcDb;                     /* Source database connection */
57220   int rc;                              /* Value to return */
57221
57222   /* Enter the mutexes */
57223   if( p==0 ) return SQLITE_OK;
57224   pSrcDb = p->pSrcDb;
57225   sqlite3_mutex_enter(pSrcDb->mutex);
57226   sqlite3BtreeEnter(p->pSrc);
57227   if( p->pDestDb ){
57228     sqlite3_mutex_enter(p->pDestDb->mutex);
57229   }
57230
57231   /* Detach this backup from the source pager. */
57232   if( p->pDestDb ){
57233     p->pSrc->nBackup--;
57234   }
57235   if( p->isAttached ){
57236     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57237     while( *pp!=p ){
57238       pp = &(*pp)->pNext;
57239     }
57240     *pp = p->pNext;
57241   }
57242
57243   /* If a transaction is still open on the Btree, roll it back. */
57244   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
57245
57246   /* Set the error code of the destination database handle. */
57247   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
57248   sqlite3Error(p->pDestDb, rc, 0);
57249
57250   /* Exit the mutexes and free the backup context structure. */
57251   if( p->pDestDb ){
57252     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
57253   }
57254   sqlite3BtreeLeave(p->pSrc);
57255   if( p->pDestDb ){
57256     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57257     ** call to sqlite3_backup_init() and is destroyed by a call to
57258     ** sqlite3_backup_finish(). */
57259     sqlite3_free(p);
57260   }
57261   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
57262   return rc;
57263 }
57264
57265 /*
57266 ** Return the number of pages still to be backed up as of the most recent
57267 ** call to sqlite3_backup_step().
57268 */
57269 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
57270   return p->nRemaining;
57271 }
57272
57273 /*
57274 ** Return the total number of pages in the source database as of the most 
57275 ** recent call to sqlite3_backup_step().
57276 */
57277 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
57278   return p->nPagecount;
57279 }
57280
57281 /*
57282 ** This function is called after the contents of page iPage of the
57283 ** source database have been modified. If page iPage has already been 
57284 ** copied into the destination database, then the data written to the
57285 ** destination is now invalidated. The destination copy of iPage needs
57286 ** to be updated with the new data before the backup operation is
57287 ** complete.
57288 **
57289 ** It is assumed that the mutex associated with the BtShared object
57290 ** corresponding to the source database is held when this function is
57291 ** called.
57292 */
57293 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
57294   sqlite3_backup *p;                   /* Iterator variable */
57295   for(p=pBackup; p; p=p->pNext){
57296     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57297     if( !isFatalError(p->rc) && iPage<p->iNext ){
57298       /* The backup process p has already copied page iPage. But now it
57299       ** has been modified by a transaction on the source pager. Copy
57300       ** the new data into the backup.
57301       */
57302       int rc;
57303       assert( p->pDestDb );
57304       sqlite3_mutex_enter(p->pDestDb->mutex);
57305       rc = backupOnePage(p, iPage, aData);
57306       sqlite3_mutex_leave(p->pDestDb->mutex);
57307       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
57308       if( rc!=SQLITE_OK ){
57309         p->rc = rc;
57310       }
57311     }
57312   }
57313 }
57314
57315 /*
57316 ** Restart the backup process. This is called when the pager layer
57317 ** detects that the database has been modified by an external database
57318 ** connection. In this case there is no way of knowing which of the
57319 ** pages that have been copied into the destination database are still 
57320 ** valid and which are not, so the entire process needs to be restarted.
57321 **
57322 ** It is assumed that the mutex associated with the BtShared object
57323 ** corresponding to the source database is held when this function is
57324 ** called.
57325 */
57326 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
57327   sqlite3_backup *p;                   /* Iterator variable */
57328   for(p=pBackup; p; p=p->pNext){
57329     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57330     p->iNext = 1;
57331   }
57332 }
57333
57334 #ifndef SQLITE_OMIT_VACUUM
57335 /*
57336 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
57337 ** must be active for both files.
57338 **
57339 ** The size of file pTo may be reduced by this operation. If anything 
57340 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
57341 ** transaction is committed before returning.
57342 */
57343 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
57344   int rc;
57345   sqlite3_file *pFd;              /* File descriptor for database pTo */
57346   sqlite3_backup b;
57347   sqlite3BtreeEnter(pTo);
57348   sqlite3BtreeEnter(pFrom);
57349
57350   assert( sqlite3BtreeIsInTrans(pTo) );
57351   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
57352   if( pFd->pMethods ){
57353     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
57354     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
57355     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
57356     if( rc ) goto copy_finished;
57357   }
57358
57359   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
57360   ** to 0. This is used by the implementations of sqlite3_backup_step()
57361   ** and sqlite3_backup_finish() to detect that they are being called
57362   ** from this function, not directly by the user.
57363   */
57364   memset(&b, 0, sizeof(b));
57365   b.pSrcDb = pFrom->db;
57366   b.pSrc = pFrom;
57367   b.pDest = pTo;
57368   b.iNext = 1;
57369
57370   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
57371   ** file. By passing this as the number of pages to copy to
57372   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
57373   ** within a single call (unless an error occurs). The assert() statement
57374   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
57375   ** or an error code.
57376   */
57377   sqlite3_backup_step(&b, 0x7FFFFFFF);
57378   assert( b.rc!=SQLITE_OK );
57379   rc = sqlite3_backup_finish(&b);
57380   if( rc==SQLITE_OK ){
57381     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
57382   }else{
57383     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
57384   }
57385
57386   assert( sqlite3BtreeIsInTrans(pTo)==0 );
57387 copy_finished:
57388   sqlite3BtreeLeave(pFrom);
57389   sqlite3BtreeLeave(pTo);
57390   return rc;
57391 }
57392 #endif /* SQLITE_OMIT_VACUUM */
57393
57394 /************** End of backup.c **********************************************/
57395 /************** Begin file vdbemem.c *****************************************/
57396 /*
57397 ** 2004 May 26
57398 **
57399 ** The author disclaims copyright to this source code.  In place of
57400 ** a legal notice, here is a blessing:
57401 **
57402 **    May you do good and not evil.
57403 **    May you find forgiveness for yourself and forgive others.
57404 **    May you share freely, never taking more than you give.
57405 **
57406 *************************************************************************
57407 **
57408 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
57409 ** stores a single value in the VDBE.  Mem is an opaque structure visible
57410 ** only within the VDBE.  Interface routines refer to a Mem using the
57411 ** name sqlite_value
57412 */
57413
57414 /*
57415 ** If pMem is an object with a valid string representation, this routine
57416 ** ensures the internal encoding for the string representation is
57417 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
57418 **
57419 ** If pMem is not a string object, or the encoding of the string
57420 ** representation is already stored using the requested encoding, then this
57421 ** routine is a no-op.
57422 **
57423 ** SQLITE_OK is returned if the conversion is successful (or not required).
57424 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
57425 ** between formats.
57426 */
57427 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
57428   int rc;
57429   assert( (pMem->flags&MEM_RowSet)==0 );
57430   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57431            || desiredEnc==SQLITE_UTF16BE );
57432   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57433     return SQLITE_OK;
57434   }
57435   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57436 #ifdef SQLITE_OMIT_UTF16
57437   return SQLITE_ERROR;
57438 #else
57439
57440   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57441   ** then the encoding of the value may not have changed.
57442   */
57443   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57444   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
57445   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57446   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57447   return rc;
57448 #endif
57449 }
57450
57451 /*
57452 ** Make sure pMem->z points to a writable allocation of at least 
57453 ** n bytes.
57454 **
57455 ** If the third argument passed to this function is true, then memory
57456 ** cell pMem must contain a string or blob. In this case the content is
57457 ** preserved. Otherwise, if the third parameter to this function is false,
57458 ** any current string or blob value may be discarded.
57459 **
57460 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57461 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
57462 ** not set, Mem.n is zeroed.
57463 */
57464 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57465   assert( 1 >=
57466     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57467     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
57468     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
57469     ((pMem->flags&MEM_Static) ? 1 : 0)
57470   );
57471   assert( (pMem->flags&MEM_RowSet)==0 );
57472
57473   /* If the preserve flag is set to true, then the memory cell must already
57474   ** contain a valid string or blob value.  */
57475   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
57476
57477   if( n<32 ) n = 32;
57478   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57479     if( preserve && pMem->z==pMem->zMalloc ){
57480       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57481       preserve = 0;
57482     }else{
57483       sqlite3DbFree(pMem->db, pMem->zMalloc);
57484       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57485     }
57486   }
57487
57488   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57489     memcpy(pMem->zMalloc, pMem->z, pMem->n);
57490   }
57491   if( pMem->flags&MEM_Dyn && pMem->xDel ){
57492     assert( pMem->xDel!=SQLITE_DYNAMIC );
57493     pMem->xDel((void *)(pMem->z));
57494   }
57495
57496   pMem->z = pMem->zMalloc;
57497   if( pMem->z==0 ){
57498     pMem->flags = MEM_Null;
57499   }else{
57500     pMem->flags &= ~(MEM_Ephem|MEM_Static);
57501   }
57502   pMem->xDel = 0;
57503   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57504 }
57505
57506 /*
57507 ** Make the given Mem object MEM_Dyn.  In other words, make it so
57508 ** that any TEXT or BLOB content is stored in memory obtained from
57509 ** malloc().  In this way, we know that the memory is safe to be
57510 ** overwritten or altered.
57511 **
57512 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57513 */
57514 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57515   int f;
57516   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57517   assert( (pMem->flags&MEM_RowSet)==0 );
57518   ExpandBlob(pMem);
57519   f = pMem->flags;
57520   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57521     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57522       return SQLITE_NOMEM;
57523     }
57524     pMem->z[pMem->n] = 0;
57525     pMem->z[pMem->n+1] = 0;
57526     pMem->flags |= MEM_Term;
57527 #ifdef SQLITE_DEBUG
57528     pMem->pScopyFrom = 0;
57529 #endif
57530   }
57531
57532   return SQLITE_OK;
57533 }
57534
57535 /*
57536 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57537 ** blob stored in dynamically allocated space.
57538 */
57539 #ifndef SQLITE_OMIT_INCRBLOB
57540 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57541   if( pMem->flags & MEM_Zero ){
57542     int nByte;
57543     assert( pMem->flags&MEM_Blob );
57544     assert( (pMem->flags&MEM_RowSet)==0 );
57545     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57546
57547     /* Set nByte to the number of bytes required to store the expanded blob. */
57548     nByte = pMem->n + pMem->u.nZero;
57549     if( nByte<=0 ){
57550       nByte = 1;
57551     }
57552     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57553       return SQLITE_NOMEM;
57554     }
57555
57556     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57557     pMem->n += pMem->u.nZero;
57558     pMem->flags &= ~(MEM_Zero|MEM_Term);
57559   }
57560   return SQLITE_OK;
57561 }
57562 #endif
57563
57564
57565 /*
57566 ** Make sure the given Mem is \u0000 terminated.
57567 */
57568 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57569   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57570   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57571     return SQLITE_OK;   /* Nothing to do */
57572   }
57573   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57574     return SQLITE_NOMEM;
57575   }
57576   pMem->z[pMem->n] = 0;
57577   pMem->z[pMem->n+1] = 0;
57578   pMem->flags |= MEM_Term;
57579   return SQLITE_OK;
57580 }
57581
57582 /*
57583 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
57584 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
57585 ** is a no-op.
57586 **
57587 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57588 **
57589 ** A MEM_Null value will never be passed to this function. This function is
57590 ** used for converting values to text for returning to the user (i.e. via
57591 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57592 ** keys are strings. In the former case a NULL pointer is returned the
57593 ** user and the later is an internal programming error.
57594 */
57595 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57596   int rc = SQLITE_OK;
57597   int fg = pMem->flags;
57598   const int nByte = 32;
57599
57600   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57601   assert( !(fg&MEM_Zero) );
57602   assert( !(fg&(MEM_Str|MEM_Blob)) );
57603   assert( fg&(MEM_Int|MEM_Real) );
57604   assert( (pMem->flags&MEM_RowSet)==0 );
57605   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57606
57607
57608   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57609     return SQLITE_NOMEM;
57610   }
57611
57612   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57613   ** string representation of the value. Then, if the required encoding
57614   ** is UTF-16le or UTF-16be do a translation.
57615   ** 
57616   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57617   */
57618   if( fg & MEM_Int ){
57619     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57620   }else{
57621     assert( fg & MEM_Real );
57622     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57623   }
57624   pMem->n = sqlite3Strlen30(pMem->z);
57625   pMem->enc = SQLITE_UTF8;
57626   pMem->flags |= MEM_Str|MEM_Term;
57627   sqlite3VdbeChangeEncoding(pMem, enc);
57628   return rc;
57629 }
57630
57631 /*
57632 ** Memory cell pMem contains the context of an aggregate function.
57633 ** This routine calls the finalize method for that function.  The
57634 ** result of the aggregate is stored back into pMem.
57635 **
57636 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
57637 ** otherwise.
57638 */
57639 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57640   int rc = SQLITE_OK;
57641   if( ALWAYS(pFunc && pFunc->xFinalize) ){
57642     sqlite3_context ctx;
57643     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57644     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57645     memset(&ctx, 0, sizeof(ctx));
57646     ctx.s.flags = MEM_Null;
57647     ctx.s.db = pMem->db;
57648     ctx.pMem = pMem;
57649     ctx.pFunc = pFunc;
57650     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57651     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57652     sqlite3DbFree(pMem->db, pMem->zMalloc);
57653     memcpy(pMem, &ctx.s, sizeof(ctx.s));
57654     rc = ctx.isError;
57655   }
57656   return rc;
57657 }
57658
57659 /*
57660 ** If the memory cell contains a string value that must be freed by
57661 ** invoking an external callback, free it now. Calling this function
57662 ** does not free any Mem.zMalloc buffer.
57663 */
57664 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57665   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57666   if( p->flags&MEM_Agg ){
57667     sqlite3VdbeMemFinalize(p, p->u.pDef);
57668     assert( (p->flags & MEM_Agg)==0 );
57669     sqlite3VdbeMemRelease(p);
57670   }else if( p->flags&MEM_Dyn && p->xDel ){
57671     assert( (p->flags&MEM_RowSet)==0 );
57672     assert( p->xDel!=SQLITE_DYNAMIC );
57673     p->xDel((void *)p->z);
57674     p->xDel = 0;
57675   }else if( p->flags&MEM_RowSet ){
57676     sqlite3RowSetClear(p->u.pRowSet);
57677   }else if( p->flags&MEM_Frame ){
57678     sqlite3VdbeMemSetNull(p);
57679   }
57680 }
57681
57682 /*
57683 ** Release any memory held by the Mem. This may leave the Mem in an
57684 ** inconsistent state, for example with (Mem.z==0) and
57685 ** (Mem.type==SQLITE_TEXT).
57686 */
57687 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57688   VdbeMemRelease(p);
57689   sqlite3DbFree(p->db, p->zMalloc);
57690   p->z = 0;
57691   p->zMalloc = 0;
57692   p->xDel = 0;
57693 }
57694
57695 /*
57696 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57697 ** If the double is too large, return 0x8000000000000000.
57698 **
57699 ** Most systems appear to do this simply by assigning
57700 ** variables and without the extra range tests.  But
57701 ** there are reports that windows throws an expection
57702 ** if the floating point value is out of range. (See ticket #2880.)
57703 ** Because we do not completely understand the problem, we will
57704 ** take the conservative approach and always do range tests
57705 ** before attempting the conversion.
57706 */
57707 static i64 doubleToInt64(double r){
57708 #ifdef SQLITE_OMIT_FLOATING_POINT
57709   /* When floating-point is omitted, double and int64 are the same thing */
57710   return r;
57711 #else
57712   /*
57713   ** Many compilers we encounter do not define constants for the
57714   ** minimum and maximum 64-bit integers, or they define them
57715   ** inconsistently.  And many do not understand the "LL" notation.
57716   ** So we define our own static constants here using nothing
57717   ** larger than a 32-bit integer constant.
57718   */
57719   static const i64 maxInt = LARGEST_INT64;
57720   static const i64 minInt = SMALLEST_INT64;
57721
57722   if( r<(double)minInt ){
57723     return minInt;
57724   }else if( r>(double)maxInt ){
57725     /* minInt is correct here - not maxInt.  It turns out that assigning
57726     ** a very large positive number to an integer results in a very large
57727     ** negative integer.  This makes no sense, but it is what x86 hardware
57728     ** does so for compatibility we will do the same in software. */
57729     return minInt;
57730   }else{
57731     return (i64)r;
57732   }
57733 #endif
57734 }
57735
57736 /*
57737 ** Return some kind of integer value which is the best we can do
57738 ** at representing the value that *pMem describes as an integer.
57739 ** If pMem is an integer, then the value is exact.  If pMem is
57740 ** a floating-point then the value returned is the integer part.
57741 ** If pMem is a string or blob, then we make an attempt to convert
57742 ** it into a integer and return that.  If pMem represents an
57743 ** an SQL-NULL value, return 0.
57744 **
57745 ** If pMem represents a string value, its encoding might be changed.
57746 */
57747 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57748   int flags;
57749   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57750   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57751   flags = pMem->flags;
57752   if( flags & MEM_Int ){
57753     return pMem->u.i;
57754   }else if( flags & MEM_Real ){
57755     return doubleToInt64(pMem->r);
57756   }else if( flags & (MEM_Str|MEM_Blob) ){
57757     i64 value = 0;
57758     assert( pMem->z || pMem->n==0 );
57759     testcase( pMem->z==0 );
57760     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57761     return value;
57762   }else{
57763     return 0;
57764   }
57765 }
57766
57767 /*
57768 ** Return the best representation of pMem that we can get into a
57769 ** double.  If pMem is already a double or an integer, return its
57770 ** value.  If it is a string or blob, try to convert it to a double.
57771 ** If it is a NULL, return 0.0.
57772 */
57773 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57774   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57775   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57776   if( pMem->flags & MEM_Real ){
57777     return pMem->r;
57778   }else if( pMem->flags & MEM_Int ){
57779     return (double)pMem->u.i;
57780   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57781     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57782     double val = (double)0;
57783     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57784     return val;
57785   }else{
57786     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57787     return (double)0;
57788   }
57789 }
57790
57791 /*
57792 ** The MEM structure is already a MEM_Real.  Try to also make it a
57793 ** MEM_Int if we can.
57794 */
57795 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57796   assert( pMem->flags & MEM_Real );
57797   assert( (pMem->flags & MEM_RowSet)==0 );
57798   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57799   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57800
57801   pMem->u.i = doubleToInt64(pMem->r);
57802
57803   /* Only mark the value as an integer if
57804   **
57805   **    (1) the round-trip conversion real->int->real is a no-op, and
57806   **    (2) The integer is neither the largest nor the smallest
57807   **        possible integer (ticket #3922)
57808   **
57809   ** The second and third terms in the following conditional enforces
57810   ** the second condition under the assumption that addition overflow causes
57811   ** values to wrap around.  On x86 hardware, the third term is always
57812   ** true and could be omitted.  But we leave it in because other
57813   ** architectures might behave differently.
57814   */
57815   if( pMem->r==(double)pMem->u.i
57816    && pMem->u.i>SMALLEST_INT64
57817 #if defined(__i486__) || defined(__x86_64__)
57818    && ALWAYS(pMem->u.i<LARGEST_INT64)
57819 #else
57820    && pMem->u.i<LARGEST_INT64
57821 #endif
57822   ){
57823     pMem->flags |= MEM_Int;
57824   }
57825 }
57826
57827 /*
57828 ** Convert pMem to type integer.  Invalidate any prior representations.
57829 */
57830 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
57831   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57832   assert( (pMem->flags & MEM_RowSet)==0 );
57833   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57834
57835   pMem->u.i = sqlite3VdbeIntValue(pMem);
57836   MemSetTypeFlag(pMem, MEM_Int);
57837   return SQLITE_OK;
57838 }
57839
57840 /*
57841 ** Convert pMem so that it is of type MEM_Real.
57842 ** Invalidate any prior representations.
57843 */
57844 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
57845   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57846   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57847
57848   pMem->r = sqlite3VdbeRealValue(pMem);
57849   MemSetTypeFlag(pMem, MEM_Real);
57850   return SQLITE_OK;
57851 }
57852
57853 /*
57854 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
57855 ** Invalidate any prior representations.
57856 **
57857 ** Every effort is made to force the conversion, even if the input
57858 ** is a string that does not look completely like a number.  Convert
57859 ** as much of the string as we can and ignore the rest.
57860 */
57861 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
57862   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
57863     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
57864     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57865     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
57866       MemSetTypeFlag(pMem, MEM_Int);
57867     }else{
57868       pMem->r = sqlite3VdbeRealValue(pMem);
57869       MemSetTypeFlag(pMem, MEM_Real);
57870       sqlite3VdbeIntegerAffinity(pMem);
57871     }
57872   }
57873   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
57874   pMem->flags &= ~(MEM_Str|MEM_Blob);
57875   return SQLITE_OK;
57876 }
57877
57878 /*
57879 ** Delete any previous value and set the value stored in *pMem to NULL.
57880 */
57881 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
57882   if( pMem->flags & MEM_Frame ){
57883     VdbeFrame *pFrame = pMem->u.pFrame;
57884     pFrame->pParent = pFrame->v->pDelFrame;
57885     pFrame->v->pDelFrame = pFrame;
57886   }
57887   if( pMem->flags & MEM_RowSet ){
57888     sqlite3RowSetClear(pMem->u.pRowSet);
57889   }
57890   MemSetTypeFlag(pMem, MEM_Null);
57891   pMem->type = SQLITE_NULL;
57892 }
57893
57894 /*
57895 ** Delete any previous value and set the value to be a BLOB of length
57896 ** n containing all zeros.
57897 */
57898 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
57899   sqlite3VdbeMemRelease(pMem);
57900   pMem->flags = MEM_Blob|MEM_Zero;
57901   pMem->type = SQLITE_BLOB;
57902   pMem->n = 0;
57903   if( n<0 ) n = 0;
57904   pMem->u.nZero = n;
57905   pMem->enc = SQLITE_UTF8;
57906
57907 #ifdef SQLITE_OMIT_INCRBLOB
57908   sqlite3VdbeMemGrow(pMem, n, 0);
57909   if( pMem->z ){
57910     pMem->n = n;
57911     memset(pMem->z, 0, n);
57912   }
57913 #endif
57914 }
57915
57916 /*
57917 ** Delete any previous value and set the value stored in *pMem to val,
57918 ** manifest type INTEGER.
57919 */
57920 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
57921   sqlite3VdbeMemRelease(pMem);
57922   pMem->u.i = val;
57923   pMem->flags = MEM_Int;
57924   pMem->type = SQLITE_INTEGER;
57925 }
57926
57927 #ifndef SQLITE_OMIT_FLOATING_POINT
57928 /*
57929 ** Delete any previous value and set the value stored in *pMem to val,
57930 ** manifest type REAL.
57931 */
57932 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
57933   if( sqlite3IsNaN(val) ){
57934     sqlite3VdbeMemSetNull(pMem);
57935   }else{
57936     sqlite3VdbeMemRelease(pMem);
57937     pMem->r = val;
57938     pMem->flags = MEM_Real;
57939     pMem->type = SQLITE_FLOAT;
57940   }
57941 }
57942 #endif
57943
57944 /*
57945 ** Delete any previous value and set the value of pMem to be an
57946 ** empty boolean index.
57947 */
57948 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
57949   sqlite3 *db = pMem->db;
57950   assert( db!=0 );
57951   assert( (pMem->flags & MEM_RowSet)==0 );
57952   sqlite3VdbeMemRelease(pMem);
57953   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
57954   if( db->mallocFailed ){
57955     pMem->flags = MEM_Null;
57956   }else{
57957     assert( pMem->zMalloc );
57958     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
57959                                        sqlite3DbMallocSize(db, pMem->zMalloc));
57960     assert( pMem->u.pRowSet!=0 );
57961     pMem->flags = MEM_RowSet;
57962   }
57963 }
57964
57965 /*
57966 ** Return true if the Mem object contains a TEXT or BLOB that is
57967 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
57968 */
57969 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
57970   assert( p->db!=0 );
57971   if( p->flags & (MEM_Str|MEM_Blob) ){
57972     int n = p->n;
57973     if( p->flags & MEM_Zero ){
57974       n += p->u.nZero;
57975     }
57976     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
57977   }
57978   return 0; 
57979 }
57980
57981 #ifdef SQLITE_DEBUG
57982 /*
57983 ** This routine prepares a memory cell for modication by breaking
57984 ** its link to a shallow copy and by marking any current shallow
57985 ** copies of this cell as invalid.
57986 **
57987 ** This is used for testing and debugging only - to make sure shallow
57988 ** copies are not misused.
57989 */
57990 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
57991   int i;
57992   Mem *pX;
57993   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
57994     if( pX->pScopyFrom==pMem ){
57995       pX->flags |= MEM_Invalid;
57996       pX->pScopyFrom = 0;
57997     }
57998   }
57999   pMem->pScopyFrom = 0;
58000 }
58001 #endif /* SQLITE_DEBUG */
58002
58003 /*
58004 ** Size of struct Mem not including the Mem.zMalloc member.
58005 */
58006 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
58007
58008 /*
58009 ** Make an shallow copy of pFrom into pTo.  Prior contents of
58010 ** pTo are freed.  The pFrom->z field is not duplicated.  If
58011 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
58012 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
58013 */
58014 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
58015   assert( (pFrom->flags & MEM_RowSet)==0 );
58016   VdbeMemRelease(pTo);
58017   memcpy(pTo, pFrom, MEMCELLSIZE);
58018   pTo->xDel = 0;
58019   if( (pFrom->flags&MEM_Static)==0 ){
58020     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
58021     assert( srcType==MEM_Ephem || srcType==MEM_Static );
58022     pTo->flags |= srcType;
58023   }
58024 }
58025
58026 /*
58027 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
58028 ** freed before the copy is made.
58029 */
58030 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
58031   int rc = SQLITE_OK;
58032
58033   assert( (pFrom->flags & MEM_RowSet)==0 );
58034   VdbeMemRelease(pTo);
58035   memcpy(pTo, pFrom, MEMCELLSIZE);
58036   pTo->flags &= ~MEM_Dyn;
58037
58038   if( pTo->flags&(MEM_Str|MEM_Blob) ){
58039     if( 0==(pFrom->flags&MEM_Static) ){
58040       pTo->flags |= MEM_Ephem;
58041       rc = sqlite3VdbeMemMakeWriteable(pTo);
58042     }
58043   }
58044
58045   return rc;
58046 }
58047
58048 /*
58049 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
58050 ** freed. If pFrom contains ephemeral data, a copy is made.
58051 **
58052 ** pFrom contains an SQL NULL when this routine returns.
58053 */
58054 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
58055   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
58056   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
58057   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
58058
58059   sqlite3VdbeMemRelease(pTo);
58060   memcpy(pTo, pFrom, sizeof(Mem));
58061   pFrom->flags = MEM_Null;
58062   pFrom->xDel = 0;
58063   pFrom->zMalloc = 0;
58064 }
58065
58066 /*
58067 ** Change the value of a Mem to be a string or a BLOB.
58068 **
58069 ** The memory management strategy depends on the value of the xDel
58070 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
58071 ** string is copied into a (possibly existing) buffer managed by the 
58072 ** Mem structure. Otherwise, any existing buffer is freed and the
58073 ** pointer copied.
58074 **
58075 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
58076 ** size limit) then no memory allocation occurs.  If the string can be
58077 ** stored without allocating memory, then it is.  If a memory allocation
58078 ** is required to store the string, then value of pMem is unchanged.  In
58079 ** either case, SQLITE_TOOBIG is returned.
58080 */
58081 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
58082   Mem *pMem,          /* Memory cell to set to string value */
58083   const char *z,      /* String pointer */
58084   int n,              /* Bytes in string, or negative */
58085   u8 enc,             /* Encoding of z.  0 for BLOBs */
58086   void (*xDel)(void*) /* Destructor function */
58087 ){
58088   int nByte = n;      /* New value for pMem->n */
58089   int iLimit;         /* Maximum allowed string or blob size */
58090   u16 flags = 0;      /* New value for pMem->flags */
58091
58092   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58093   assert( (pMem->flags & MEM_RowSet)==0 );
58094
58095   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
58096   if( !z ){
58097     sqlite3VdbeMemSetNull(pMem);
58098     return SQLITE_OK;
58099   }
58100
58101   if( pMem->db ){
58102     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
58103   }else{
58104     iLimit = SQLITE_MAX_LENGTH;
58105   }
58106   flags = (enc==0?MEM_Blob:MEM_Str);
58107   if( nByte<0 ){
58108     assert( enc!=0 );
58109     if( enc==SQLITE_UTF8 ){
58110       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
58111     }else{
58112       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
58113     }
58114     flags |= MEM_Term;
58115   }
58116
58117   /* The following block sets the new values of Mem.z and Mem.xDel. It
58118   ** also sets a flag in local variable "flags" to indicate the memory
58119   ** management (one of MEM_Dyn or MEM_Static).
58120   */
58121   if( xDel==SQLITE_TRANSIENT ){
58122     int nAlloc = nByte;
58123     if( flags&MEM_Term ){
58124       nAlloc += (enc==SQLITE_UTF8?1:2);
58125     }
58126     if( nByte>iLimit ){
58127       return SQLITE_TOOBIG;
58128     }
58129     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
58130       return SQLITE_NOMEM;
58131     }
58132     memcpy(pMem->z, z, nAlloc);
58133   }else if( xDel==SQLITE_DYNAMIC ){
58134     sqlite3VdbeMemRelease(pMem);
58135     pMem->zMalloc = pMem->z = (char *)z;
58136     pMem->xDel = 0;
58137   }else{
58138     sqlite3VdbeMemRelease(pMem);
58139     pMem->z = (char *)z;
58140     pMem->xDel = xDel;
58141     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
58142   }
58143
58144   pMem->n = nByte;
58145   pMem->flags = flags;
58146   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
58147   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
58148
58149 #ifndef SQLITE_OMIT_UTF16
58150   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
58151     return SQLITE_NOMEM;
58152   }
58153 #endif
58154
58155   if( nByte>iLimit ){
58156     return SQLITE_TOOBIG;
58157   }
58158
58159   return SQLITE_OK;
58160 }
58161
58162 /*
58163 ** Compare the values contained by the two memory cells, returning
58164 ** negative, zero or positive if pMem1 is less than, equal to, or greater
58165 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
58166 ** and reals) sorted numerically, followed by text ordered by the collating
58167 ** sequence pColl and finally blob's ordered by memcmp().
58168 **
58169 ** Two NULL values are considered equal by this function.
58170 */
58171 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
58172   int rc;
58173   int f1, f2;
58174   int combined_flags;
58175
58176   f1 = pMem1->flags;
58177   f2 = pMem2->flags;
58178   combined_flags = f1|f2;
58179   assert( (combined_flags & MEM_RowSet)==0 );
58180  
58181   /* If one value is NULL, it is less than the other. If both values
58182   ** are NULL, return 0.
58183   */
58184   if( combined_flags&MEM_Null ){
58185     return (f2&MEM_Null) - (f1&MEM_Null);
58186   }
58187
58188   /* If one value is a number and the other is not, the number is less.
58189   ** If both are numbers, compare as reals if one is a real, or as integers
58190   ** if both values are integers.
58191   */
58192   if( combined_flags&(MEM_Int|MEM_Real) ){
58193     if( !(f1&(MEM_Int|MEM_Real)) ){
58194       return 1;
58195     }
58196     if( !(f2&(MEM_Int|MEM_Real)) ){
58197       return -1;
58198     }
58199     if( (f1 & f2 & MEM_Int)==0 ){
58200       double r1, r2;
58201       if( (f1&MEM_Real)==0 ){
58202         r1 = (double)pMem1->u.i;
58203       }else{
58204         r1 = pMem1->r;
58205       }
58206       if( (f2&MEM_Real)==0 ){
58207         r2 = (double)pMem2->u.i;
58208       }else{
58209         r2 = pMem2->r;
58210       }
58211       if( r1<r2 ) return -1;
58212       if( r1>r2 ) return 1;
58213       return 0;
58214     }else{
58215       assert( f1&MEM_Int );
58216       assert( f2&MEM_Int );
58217       if( pMem1->u.i < pMem2->u.i ) return -1;
58218       if( pMem1->u.i > pMem2->u.i ) return 1;
58219       return 0;
58220     }
58221   }
58222
58223   /* If one value is a string and the other is a blob, the string is less.
58224   ** If both are strings, compare using the collating functions.
58225   */
58226   if( combined_flags&MEM_Str ){
58227     if( (f1 & MEM_Str)==0 ){
58228       return 1;
58229     }
58230     if( (f2 & MEM_Str)==0 ){
58231       return -1;
58232     }
58233
58234     assert( pMem1->enc==pMem2->enc );
58235     assert( pMem1->enc==SQLITE_UTF8 || 
58236             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
58237
58238     /* The collation sequence must be defined at this point, even if
58239     ** the user deletes the collation sequence after the vdbe program is
58240     ** compiled (this was not always the case).
58241     */
58242     assert( !pColl || pColl->xCmp );
58243
58244     if( pColl ){
58245       if( pMem1->enc==pColl->enc ){
58246         /* The strings are already in the correct encoding.  Call the
58247         ** comparison function directly */
58248         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
58249       }else{
58250         const void *v1, *v2;
58251         int n1, n2;
58252         Mem c1;
58253         Mem c2;
58254         memset(&c1, 0, sizeof(c1));
58255         memset(&c2, 0, sizeof(c2));
58256         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
58257         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
58258         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
58259         n1 = v1==0 ? 0 : c1.n;
58260         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
58261         n2 = v2==0 ? 0 : c2.n;
58262         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
58263         sqlite3VdbeMemRelease(&c1);
58264         sqlite3VdbeMemRelease(&c2);
58265         return rc;
58266       }
58267     }
58268     /* If a NULL pointer was passed as the collate function, fall through
58269     ** to the blob case and use memcmp().  */
58270   }
58271  
58272   /* Both values must be blobs.  Compare using memcmp().  */
58273   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
58274   if( rc==0 ){
58275     rc = pMem1->n - pMem2->n;
58276   }
58277   return rc;
58278 }
58279
58280 /*
58281 ** Move data out of a btree key or data field and into a Mem structure.
58282 ** The data or key is taken from the entry that pCur is currently pointing
58283 ** to.  offset and amt determine what portion of the data or key to retrieve.
58284 ** key is true to get the key or false to get data.  The result is written
58285 ** into the pMem element.
58286 **
58287 ** The pMem structure is assumed to be uninitialized.  Any prior content
58288 ** is overwritten without being freed.
58289 **
58290 ** If this routine fails for any reason (malloc returns NULL or unable
58291 ** to read from the disk) then the pMem is left in an inconsistent state.
58292 */
58293 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
58294   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
58295   int offset,       /* Offset from the start of data to return bytes from. */
58296   int amt,          /* Number of bytes to return. */
58297   int key,          /* If true, retrieve from the btree key, not data. */
58298   Mem *pMem         /* OUT: Return data in this Mem structure. */
58299 ){
58300   char *zData;        /* Data from the btree layer */
58301   int available = 0;  /* Number of bytes available on the local btree page */
58302   int rc = SQLITE_OK; /* Return code */
58303
58304   assert( sqlite3BtreeCursorIsValid(pCur) );
58305
58306   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
58307   ** that both the BtShared and database handle mutexes are held. */
58308   assert( (pMem->flags & MEM_RowSet)==0 );
58309   if( key ){
58310     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
58311   }else{
58312     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
58313   }
58314   assert( zData!=0 );
58315
58316   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
58317     sqlite3VdbeMemRelease(pMem);
58318     pMem->z = &zData[offset];
58319     pMem->flags = MEM_Blob|MEM_Ephem;
58320   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
58321     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
58322     pMem->enc = 0;
58323     pMem->type = SQLITE_BLOB;
58324     if( key ){
58325       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
58326     }else{
58327       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
58328     }
58329     pMem->z[amt] = 0;
58330     pMem->z[amt+1] = 0;
58331     if( rc!=SQLITE_OK ){
58332       sqlite3VdbeMemRelease(pMem);
58333     }
58334   }
58335   pMem->n = amt;
58336
58337   return rc;
58338 }
58339
58340 /* This function is only available internally, it is not part of the
58341 ** external API. It works in a similar way to sqlite3_value_text(),
58342 ** except the data returned is in the encoding specified by the second
58343 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
58344 ** SQLITE_UTF8.
58345 **
58346 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
58347 ** If that is the case, then the result must be aligned on an even byte
58348 ** boundary.
58349 */
58350 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
58351   if( !pVal ) return 0;
58352
58353   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
58354   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
58355   assert( (pVal->flags & MEM_RowSet)==0 );
58356
58357   if( pVal->flags&MEM_Null ){
58358     return 0;
58359   }
58360   assert( (MEM_Blob>>3) == MEM_Str );
58361   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
58362   ExpandBlob(pVal);
58363   if( pVal->flags&MEM_Str ){
58364     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
58365     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
58366       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
58367       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
58368         return 0;
58369       }
58370     }
58371     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
58372   }else{
58373     assert( (pVal->flags&MEM_Blob)==0 );
58374     sqlite3VdbeMemStringify(pVal, enc);
58375     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
58376   }
58377   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
58378               || pVal->db->mallocFailed );
58379   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
58380     return pVal->z;
58381   }else{
58382     return 0;
58383   }
58384 }
58385
58386 /*
58387 ** Create a new sqlite3_value object.
58388 */
58389 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
58390   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
58391   if( p ){
58392     p->flags = MEM_Null;
58393     p->type = SQLITE_NULL;
58394     p->db = db;
58395   }
58396   return p;
58397 }
58398
58399 /*
58400 ** Create a new sqlite3_value object, containing the value of pExpr.
58401 **
58402 ** This only works for very simple expressions that consist of one constant
58403 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
58404 ** be converted directly into a value, then the value is allocated and
58405 ** a pointer written to *ppVal. The caller is responsible for deallocating
58406 ** the value by passing it to sqlite3ValueFree() later on. If the expression
58407 ** cannot be converted to a value, then *ppVal is set to NULL.
58408 */
58409 SQLITE_PRIVATE int sqlite3ValueFromExpr(
58410   sqlite3 *db,              /* The database connection */
58411   Expr *pExpr,              /* The expression to evaluate */
58412   u8 enc,                   /* Encoding to use */
58413   u8 affinity,              /* Affinity to use */
58414   sqlite3_value **ppVal     /* Write the new value here */
58415 ){
58416   int op;
58417   char *zVal = 0;
58418   sqlite3_value *pVal = 0;
58419   int negInt = 1;
58420   const char *zNeg = "";
58421
58422   if( !pExpr ){
58423     *ppVal = 0;
58424     return SQLITE_OK;
58425   }
58426   op = pExpr->op;
58427
58428   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
58429   ** The ifdef here is to enable us to achieve 100% branch test coverage even
58430   ** when SQLITE_ENABLE_STAT3 is omitted.
58431   */
58432 #ifdef SQLITE_ENABLE_STAT3
58433   if( op==TK_REGISTER ) op = pExpr->op2;
58434 #else
58435   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58436 #endif
58437
58438   /* Handle negative integers in a single step.  This is needed in the
58439   ** case when the value is -9223372036854775808.
58440   */
58441   if( op==TK_UMINUS
58442    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58443     pExpr = pExpr->pLeft;
58444     op = pExpr->op;
58445     negInt = -1;
58446     zNeg = "-";
58447   }
58448
58449   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58450     pVal = sqlite3ValueNew(db);
58451     if( pVal==0 ) goto no_mem;
58452     if( ExprHasProperty(pExpr, EP_IntValue) ){
58453       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58454     }else{
58455       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58456       if( zVal==0 ) goto no_mem;
58457       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58458       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58459     }
58460     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58461       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58462     }else{
58463       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58464     }
58465     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58466     if( enc!=SQLITE_UTF8 ){
58467       sqlite3VdbeChangeEncoding(pVal, enc);
58468     }
58469   }else if( op==TK_UMINUS ) {
58470     /* This branch happens for multiple negative signs.  Ex: -(-5) */
58471     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58472       sqlite3VdbeMemNumerify(pVal);
58473       if( pVal->u.i==SMALLEST_INT64 ){
58474         pVal->flags &= MEM_Int;
58475         pVal->flags |= MEM_Real;
58476         pVal->r = (double)LARGEST_INT64;
58477       }else{
58478         pVal->u.i = -pVal->u.i;
58479       }
58480       pVal->r = -pVal->r;
58481       sqlite3ValueApplyAffinity(pVal, affinity, enc);
58482     }
58483   }else if( op==TK_NULL ){
58484     pVal = sqlite3ValueNew(db);
58485     if( pVal==0 ) goto no_mem;
58486   }
58487 #ifndef SQLITE_OMIT_BLOB_LITERAL
58488   else if( op==TK_BLOB ){
58489     int nVal;
58490     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58491     assert( pExpr->u.zToken[1]=='\'' );
58492     pVal = sqlite3ValueNew(db);
58493     if( !pVal ) goto no_mem;
58494     zVal = &pExpr->u.zToken[2];
58495     nVal = sqlite3Strlen30(zVal)-1;
58496     assert( zVal[nVal]=='\'' );
58497     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58498                          0, SQLITE_DYNAMIC);
58499   }
58500 #endif
58501
58502   if( pVal ){
58503     sqlite3VdbeMemStoreType(pVal);
58504   }
58505   *ppVal = pVal;
58506   return SQLITE_OK;
58507
58508 no_mem:
58509   db->mallocFailed = 1;
58510   sqlite3DbFree(db, zVal);
58511   sqlite3ValueFree(pVal);
58512   *ppVal = 0;
58513   return SQLITE_NOMEM;
58514 }
58515
58516 /*
58517 ** Change the string value of an sqlite3_value object
58518 */
58519 SQLITE_PRIVATE void sqlite3ValueSetStr(
58520   sqlite3_value *v,     /* Value to be set */
58521   int n,                /* Length of string z */
58522   const void *z,        /* Text of the new string */
58523   u8 enc,               /* Encoding to use */
58524   void (*xDel)(void*)   /* Destructor for the string */
58525 ){
58526   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58527 }
58528
58529 /*
58530 ** Free an sqlite3_value object
58531 */
58532 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58533   if( !v ) return;
58534   sqlite3VdbeMemRelease((Mem *)v);
58535   sqlite3DbFree(((Mem*)v)->db, v);
58536 }
58537
58538 /*
58539 ** Return the number of bytes in the sqlite3_value object assuming
58540 ** that it uses the encoding "enc"
58541 */
58542 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58543   Mem *p = (Mem*)pVal;
58544   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58545     if( p->flags & MEM_Zero ){
58546       return p->n + p->u.nZero;
58547     }else{
58548       return p->n;
58549     }
58550   }
58551   return 0;
58552 }
58553
58554 /************** End of vdbemem.c *********************************************/
58555 /************** Begin file vdbeaux.c *****************************************/
58556 /*
58557 ** 2003 September 6
58558 **
58559 ** The author disclaims copyright to this source code.  In place of
58560 ** a legal notice, here is a blessing:
58561 **
58562 **    May you do good and not evil.
58563 **    May you find forgiveness for yourself and forgive others.
58564 **    May you share freely, never taking more than you give.
58565 **
58566 *************************************************************************
58567 ** This file contains code used for creating, destroying, and populating
58568 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
58569 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58570 ** But that file was getting too big so this subroutines were split out.
58571 */
58572
58573
58574
58575 /*
58576 ** When debugging the code generator in a symbolic debugger, one can
58577 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
58578 ** as they are added to the instruction stream.
58579 */
58580 #ifdef SQLITE_DEBUG
58581 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
58582 #endif
58583
58584
58585 /*
58586 ** Create a new virtual database engine.
58587 */
58588 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58589   Vdbe *p;
58590   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58591   if( p==0 ) return 0;
58592   p->db = db;
58593   if( db->pVdbe ){
58594     db->pVdbe->pPrev = p;
58595   }
58596   p->pNext = db->pVdbe;
58597   p->pPrev = 0;
58598   db->pVdbe = p;
58599   p->magic = VDBE_MAGIC_INIT;
58600   return p;
58601 }
58602
58603 /*
58604 ** Remember the SQL string for a prepared statement.
58605 */
58606 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58607   assert( isPrepareV2==1 || isPrepareV2==0 );
58608   if( p==0 ) return;
58609 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
58610   if( !isPrepareV2 ) return;
58611 #endif
58612   assert( p->zSql==0 );
58613   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58614   p->isPrepareV2 = (u8)isPrepareV2;
58615 }
58616
58617 /*
58618 ** Return the SQL associated with a prepared statement
58619 */
58620 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58621   Vdbe *p = (Vdbe *)pStmt;
58622   return (p && p->isPrepareV2) ? p->zSql : 0;
58623 }
58624
58625 /*
58626 ** Swap all content between two VDBE structures.
58627 */
58628 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58629   Vdbe tmp, *pTmp;
58630   char *zTmp;
58631   tmp = *pA;
58632   *pA = *pB;
58633   *pB = tmp;
58634   pTmp = pA->pNext;
58635   pA->pNext = pB->pNext;
58636   pB->pNext = pTmp;
58637   pTmp = pA->pPrev;
58638   pA->pPrev = pB->pPrev;
58639   pB->pPrev = pTmp;
58640   zTmp = pA->zSql;
58641   pA->zSql = pB->zSql;
58642   pB->zSql = zTmp;
58643   pB->isPrepareV2 = pA->isPrepareV2;
58644 }
58645
58646 #ifdef SQLITE_DEBUG
58647 /*
58648 ** Turn tracing on or off
58649 */
58650 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58651   p->trace = trace;
58652 }
58653 #endif
58654
58655 /*
58656 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
58657 ** it was.
58658 **
58659 ** If an out-of-memory error occurs while resizing the array, return
58660 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
58661 ** unchanged (this is so that any opcodes already allocated can be 
58662 ** correctly deallocated along with the rest of the Vdbe).
58663 */
58664 static int growOpArray(Vdbe *p){
58665   VdbeOp *pNew;
58666   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58667   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58668   if( pNew ){
58669     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58670     p->aOp = pNew;
58671   }
58672   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58673 }
58674
58675 /*
58676 ** Add a new instruction to the list of instructions current in the
58677 ** VDBE.  Return the address of the new instruction.
58678 **
58679 ** Parameters:
58680 **
58681 **    p               Pointer to the VDBE
58682 **
58683 **    op              The opcode for this instruction
58684 **
58685 **    p1, p2, p3      Operands
58686 **
58687 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58688 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58689 ** operand.
58690 */
58691 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58692   int i;
58693   VdbeOp *pOp;
58694
58695   i = p->nOp;
58696   assert( p->magic==VDBE_MAGIC_INIT );
58697   assert( op>0 && op<0xff );
58698   if( p->nOpAlloc<=i ){
58699     if( growOpArray(p) ){
58700       return 1;
58701     }
58702   }
58703   p->nOp++;
58704   pOp = &p->aOp[i];
58705   pOp->opcode = (u8)op;
58706   pOp->p5 = 0;
58707   pOp->p1 = p1;
58708   pOp->p2 = p2;
58709   pOp->p3 = p3;
58710   pOp->p4.p = 0;
58711   pOp->p4type = P4_NOTUSED;
58712 #ifdef SQLITE_DEBUG
58713   pOp->zComment = 0;
58714   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58715 #endif
58716 #ifdef VDBE_PROFILE
58717   pOp->cycles = 0;
58718   pOp->cnt = 0;
58719 #endif
58720   return i;
58721 }
58722 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58723   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58724 }
58725 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58726   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58727 }
58728 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58729   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58730 }
58731
58732
58733 /*
58734 ** Add an opcode that includes the p4 value as a pointer.
58735 */
58736 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58737   Vdbe *p,            /* Add the opcode to this VM */
58738   int op,             /* The new opcode */
58739   int p1,             /* The P1 operand */
58740   int p2,             /* The P2 operand */
58741   int p3,             /* The P3 operand */
58742   const char *zP4,    /* The P4 operand */
58743   int p4type          /* P4 operand type */
58744 ){
58745   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58746   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58747   return addr;
58748 }
58749
58750 /*
58751 ** Add an OP_ParseSchema opcode.  This routine is broken out from
58752 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
58753 ** as having been used.
58754 **
58755 ** The zWhere string must have been obtained from sqlite3_malloc().
58756 ** This routine will take ownership of the allocated memory.
58757 */
58758 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58759   int j;
58760   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58761   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58762   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58763 }
58764
58765 /*
58766 ** Add an opcode that includes the p4 value as an integer.
58767 */
58768 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58769   Vdbe *p,            /* Add the opcode to this VM */
58770   int op,             /* The new opcode */
58771   int p1,             /* The P1 operand */
58772   int p2,             /* The P2 operand */
58773   int p3,             /* The P3 operand */
58774   int p4              /* The P4 operand as an integer */
58775 ){
58776   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58777   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58778   return addr;
58779 }
58780
58781 /*
58782 ** Create a new symbolic label for an instruction that has yet to be
58783 ** coded.  The symbolic label is really just a negative number.  The
58784 ** label can be used as the P2 value of an operation.  Later, when
58785 ** the label is resolved to a specific address, the VDBE will scan
58786 ** through its operation list and change all values of P2 which match
58787 ** the label into the resolved address.
58788 **
58789 ** The VDBE knows that a P2 value is a label because labels are
58790 ** always negative and P2 values are suppose to be non-negative.
58791 ** Hence, a negative P2 value is a label that has yet to be resolved.
58792 **
58793 ** Zero is returned if a malloc() fails.
58794 */
58795 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58796   int i = p->nLabel++;
58797   assert( p->magic==VDBE_MAGIC_INIT );
58798   if( (i & (i-1))==0 ){
58799     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
58800                                        (i*2+1)*sizeof(p->aLabel[0]));
58801   }
58802   if( p->aLabel ){
58803     p->aLabel[i] = -1;
58804   }
58805   return -1-i;
58806 }
58807
58808 /*
58809 ** Resolve label "x" to be the address of the next instruction to
58810 ** be inserted.  The parameter "x" must have been obtained from
58811 ** a prior call to sqlite3VdbeMakeLabel().
58812 */
58813 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58814   int j = -1-x;
58815   assert( p->magic==VDBE_MAGIC_INIT );
58816   assert( j>=0 && j<p->nLabel );
58817   if( p->aLabel ){
58818     p->aLabel[j] = p->nOp;
58819   }
58820 }
58821
58822 /*
58823 ** Mark the VDBE as one that can only be run one time.
58824 */
58825 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
58826   p->runOnlyOnce = 1;
58827 }
58828
58829 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
58830
58831 /*
58832 ** The following type and function are used to iterate through all opcodes
58833 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
58834 ** invoke directly or indirectly. It should be used as follows:
58835 **
58836 **   Op *pOp;
58837 **   VdbeOpIter sIter;
58838 **
58839 **   memset(&sIter, 0, sizeof(sIter));
58840 **   sIter.v = v;                            // v is of type Vdbe* 
58841 **   while( (pOp = opIterNext(&sIter)) ){
58842 **     // Do something with pOp
58843 **   }
58844 **   sqlite3DbFree(v->db, sIter.apSub);
58845 ** 
58846 */
58847 typedef struct VdbeOpIter VdbeOpIter;
58848 struct VdbeOpIter {
58849   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
58850   SubProgram **apSub;        /* Array of subprograms */
58851   int nSub;                  /* Number of entries in apSub */
58852   int iAddr;                 /* Address of next instruction to return */
58853   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
58854 };
58855 static Op *opIterNext(VdbeOpIter *p){
58856   Vdbe *v = p->v;
58857   Op *pRet = 0;
58858   Op *aOp;
58859   int nOp;
58860
58861   if( p->iSub<=p->nSub ){
58862
58863     if( p->iSub==0 ){
58864       aOp = v->aOp;
58865       nOp = v->nOp;
58866     }else{
58867       aOp = p->apSub[p->iSub-1]->aOp;
58868       nOp = p->apSub[p->iSub-1]->nOp;
58869     }
58870     assert( p->iAddr<nOp );
58871
58872     pRet = &aOp[p->iAddr];
58873     p->iAddr++;
58874     if( p->iAddr==nOp ){
58875       p->iSub++;
58876       p->iAddr = 0;
58877     }
58878   
58879     if( pRet->p4type==P4_SUBPROGRAM ){
58880       int nByte = (p->nSub+1)*sizeof(SubProgram*);
58881       int j;
58882       for(j=0; j<p->nSub; j++){
58883         if( p->apSub[j]==pRet->p4.pProgram ) break;
58884       }
58885       if( j==p->nSub ){
58886         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
58887         if( !p->apSub ){
58888           pRet = 0;
58889         }else{
58890           p->apSub[p->nSub++] = pRet->p4.pProgram;
58891         }
58892       }
58893     }
58894   }
58895
58896   return pRet;
58897 }
58898
58899 /*
58900 ** Check if the program stored in the VM associated with pParse may
58901 ** throw an ABORT exception (causing the statement, but not entire transaction
58902 ** to be rolled back). This condition is true if the main program or any
58903 ** sub-programs contains any of the following:
58904 **
58905 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58906 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58907 **   *  OP_Destroy
58908 **   *  OP_VUpdate
58909 **   *  OP_VRename
58910 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
58911 **
58912 ** Then check that the value of Parse.mayAbort is true if an
58913 ** ABORT may be thrown, or false otherwise. Return true if it does
58914 ** match, or false otherwise. This function is intended to be used as
58915 ** part of an assert statement in the compiler. Similar to:
58916 **
58917 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
58918 */
58919 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
58920   int hasAbort = 0;
58921   Op *pOp;
58922   VdbeOpIter sIter;
58923   memset(&sIter, 0, sizeof(sIter));
58924   sIter.v = v;
58925
58926   while( (pOp = opIterNext(&sIter))!=0 ){
58927     int opcode = pOp->opcode;
58928     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
58929 #ifndef SQLITE_OMIT_FOREIGN_KEY
58930      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
58931 #endif
58932      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
58933       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
58934     ){
58935       hasAbort = 1;
58936       break;
58937     }
58938   }
58939   sqlite3DbFree(v->db, sIter.apSub);
58940
58941   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
58942   ** If malloc failed, then the while() loop above may not have iterated
58943   ** through all opcodes and hasAbort may be set incorrectly. Return
58944   ** true for this case to prevent the assert() in the callers frame
58945   ** from failing.  */
58946   return ( v->db->mallocFailed || hasAbort==mayAbort );
58947 }
58948 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
58949
58950 /*
58951 ** Loop through the program looking for P2 values that are negative
58952 ** on jump instructions.  Each such value is a label.  Resolve the
58953 ** label by setting the P2 value to its correct non-zero value.
58954 **
58955 ** This routine is called once after all opcodes have been inserted.
58956 **
58957 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
58958 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
58959 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
58960 **
58961 ** The Op.opflags field is set on all opcodes.
58962 */
58963 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
58964   int i;
58965   int nMaxArgs = *pMaxFuncArgs;
58966   Op *pOp;
58967   int *aLabel = p->aLabel;
58968   p->readOnly = 1;
58969   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
58970     u8 opcode = pOp->opcode;
58971
58972     pOp->opflags = sqlite3OpcodeProperty[opcode];
58973     if( opcode==OP_Function || opcode==OP_AggStep ){
58974       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
58975     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
58976       p->readOnly = 0;
58977 #ifndef SQLITE_OMIT_VIRTUALTABLE
58978     }else if( opcode==OP_VUpdate ){
58979       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
58980     }else if( opcode==OP_VFilter ){
58981       int n;
58982       assert( p->nOp - i >= 3 );
58983       assert( pOp[-1].opcode==OP_Integer );
58984       n = pOp[-1].p1;
58985       if( n>nMaxArgs ) nMaxArgs = n;
58986 #endif
58987     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
58988       pOp->p4.xAdvance = sqlite3BtreeNext;
58989       pOp->p4type = P4_ADVANCE;
58990     }else if( opcode==OP_Prev ){
58991       pOp->p4.xAdvance = sqlite3BtreePrevious;
58992       pOp->p4type = P4_ADVANCE;
58993     }
58994
58995     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
58996       assert( -1-pOp->p2<p->nLabel );
58997       pOp->p2 = aLabel[-1-pOp->p2];
58998     }
58999   }
59000   sqlite3DbFree(p->db, p->aLabel);
59001   p->aLabel = 0;
59002
59003   *pMaxFuncArgs = nMaxArgs;
59004 }
59005
59006 /*
59007 ** Return the address of the next instruction to be inserted.
59008 */
59009 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
59010   assert( p->magic==VDBE_MAGIC_INIT );
59011   return p->nOp;
59012 }
59013
59014 /*
59015 ** This function returns a pointer to the array of opcodes associated with
59016 ** the Vdbe passed as the first argument. It is the callers responsibility
59017 ** to arrange for the returned array to be eventually freed using the 
59018 ** vdbeFreeOpArray() function.
59019 **
59020 ** Before returning, *pnOp is set to the number of entries in the returned
59021 ** array. Also, *pnMaxArg is set to the larger of its current value and 
59022 ** the number of entries in the Vdbe.apArg[] array required to execute the 
59023 ** returned program.
59024 */
59025 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
59026   VdbeOp *aOp = p->aOp;
59027   assert( aOp && !p->db->mallocFailed );
59028
59029   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
59030   assert( p->btreeMask==0 );
59031
59032   resolveP2Values(p, pnMaxArg);
59033   *pnOp = p->nOp;
59034   p->aOp = 0;
59035   return aOp;
59036 }
59037
59038 /*
59039 ** Add a whole list of operations to the operation stack.  Return the
59040 ** address of the first operation added.
59041 */
59042 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
59043   int addr;
59044   assert( p->magic==VDBE_MAGIC_INIT );
59045   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
59046     return 0;
59047   }
59048   addr = p->nOp;
59049   if( ALWAYS(nOp>0) ){
59050     int i;
59051     VdbeOpList const *pIn = aOp;
59052     for(i=0; i<nOp; i++, pIn++){
59053       int p2 = pIn->p2;
59054       VdbeOp *pOut = &p->aOp[i+addr];
59055       pOut->opcode = pIn->opcode;
59056       pOut->p1 = pIn->p1;
59057       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
59058         pOut->p2 = addr + ADDR(p2);
59059       }else{
59060         pOut->p2 = p2;
59061       }
59062       pOut->p3 = pIn->p3;
59063       pOut->p4type = P4_NOTUSED;
59064       pOut->p4.p = 0;
59065       pOut->p5 = 0;
59066 #ifdef SQLITE_DEBUG
59067       pOut->zComment = 0;
59068       if( sqlite3VdbeAddopTrace ){
59069         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
59070       }
59071 #endif
59072     }
59073     p->nOp += nOp;
59074   }
59075   return addr;
59076 }
59077
59078 /*
59079 ** Change the value of the P1 operand for a specific instruction.
59080 ** This routine is useful when a large program is loaded from a
59081 ** static array using sqlite3VdbeAddOpList but we want to make a
59082 ** few minor changes to the program.
59083 */
59084 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
59085   assert( p!=0 );
59086   if( ((u32)p->nOp)>addr ){
59087     p->aOp[addr].p1 = val;
59088   }
59089 }
59090
59091 /*
59092 ** Change the value of the P2 operand for a specific instruction.
59093 ** This routine is useful for setting a jump destination.
59094 */
59095 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
59096   assert( p!=0 );
59097   if( ((u32)p->nOp)>addr ){
59098     p->aOp[addr].p2 = val;
59099   }
59100 }
59101
59102 /*
59103 ** Change the value of the P3 operand for a specific instruction.
59104 */
59105 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
59106   assert( p!=0 );
59107   if( ((u32)p->nOp)>addr ){
59108     p->aOp[addr].p3 = val;
59109   }
59110 }
59111
59112 /*
59113 ** Change the value of the P5 operand for the most recently
59114 ** added operation.
59115 */
59116 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
59117   assert( p!=0 );
59118   if( p->aOp ){
59119     assert( p->nOp>0 );
59120     p->aOp[p->nOp-1].p5 = val;
59121   }
59122 }
59123
59124 /*
59125 ** Change the P2 operand of instruction addr so that it points to
59126 ** the address of the next instruction to be coded.
59127 */
59128 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
59129   assert( addr>=0 || p->db->mallocFailed );
59130   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
59131 }
59132
59133
59134 /*
59135 ** If the input FuncDef structure is ephemeral, then free it.  If
59136 ** the FuncDef is not ephermal, then do nothing.
59137 */
59138 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
59139   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
59140     sqlite3DbFree(db, pDef);
59141   }
59142 }
59143
59144 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
59145
59146 /*
59147 ** Delete a P4 value if necessary.
59148 */
59149 static void freeP4(sqlite3 *db, int p4type, void *p4){
59150   if( p4 ){
59151     assert( db );
59152     switch( p4type ){
59153       case P4_REAL:
59154       case P4_INT64:
59155       case P4_DYNAMIC:
59156       case P4_KEYINFO:
59157       case P4_INTARRAY:
59158       case P4_KEYINFO_HANDOFF: {
59159         sqlite3DbFree(db, p4);
59160         break;
59161       }
59162       case P4_MPRINTF: {
59163         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
59164         break;
59165       }
59166       case P4_VDBEFUNC: {
59167         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
59168         freeEphemeralFunction(db, pVdbeFunc->pFunc);
59169         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
59170         sqlite3DbFree(db, pVdbeFunc);
59171         break;
59172       }
59173       case P4_FUNCDEF: {
59174         freeEphemeralFunction(db, (FuncDef*)p4);
59175         break;
59176       }
59177       case P4_MEM: {
59178         if( db->pnBytesFreed==0 ){
59179           sqlite3ValueFree((sqlite3_value*)p4);
59180         }else{
59181           Mem *p = (Mem*)p4;
59182           sqlite3DbFree(db, p->zMalloc);
59183           sqlite3DbFree(db, p);
59184         }
59185         break;
59186       }
59187       case P4_VTAB : {
59188         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
59189         break;
59190       }
59191     }
59192   }
59193 }
59194
59195 /*
59196 ** Free the space allocated for aOp and any p4 values allocated for the
59197 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
59198 ** nOp entries. 
59199 */
59200 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
59201   if( aOp ){
59202     Op *pOp;
59203     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
59204       freeP4(db, pOp->p4type, pOp->p4.p);
59205 #ifdef SQLITE_DEBUG
59206       sqlite3DbFree(db, pOp->zComment);
59207 #endif     
59208     }
59209   }
59210   sqlite3DbFree(db, aOp);
59211 }
59212
59213 /*
59214 ** Link the SubProgram object passed as the second argument into the linked
59215 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
59216 ** objects when the VM is no longer required.
59217 */
59218 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
59219   p->pNext = pVdbe->pProgram;
59220   pVdbe->pProgram = p;
59221 }
59222
59223 /*
59224 ** Change the opcode at addr into OP_Noop
59225 */
59226 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
59227   if( p->aOp ){
59228     VdbeOp *pOp = &p->aOp[addr];
59229     sqlite3 *db = p->db;
59230     freeP4(db, pOp->p4type, pOp->p4.p);
59231     memset(pOp, 0, sizeof(pOp[0]));
59232     pOp->opcode = OP_Noop;
59233   }
59234 }
59235
59236 /*
59237 ** Change the value of the P4 operand for a specific instruction.
59238 ** This routine is useful when a large program is loaded from a
59239 ** static array using sqlite3VdbeAddOpList but we want to make a
59240 ** few minor changes to the program.
59241 **
59242 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
59243 ** the string is made into memory obtained from sqlite3_malloc().
59244 ** A value of n==0 means copy bytes of zP4 up to and including the
59245 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
59246 **
59247 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
59248 ** A copy is made of the KeyInfo structure into memory obtained from
59249 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
59250 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
59251 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
59252 ** caller should not free the allocation, it will be freed when the Vdbe is
59253 ** finalized.
59254 ** 
59255 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
59256 ** to a string or structure that is guaranteed to exist for the lifetime of
59257 ** the Vdbe. In these cases we can just copy the pointer.
59258 **
59259 ** If addr<0 then change P4 on the most recently inserted instruction.
59260 */
59261 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
59262   Op *pOp;
59263   sqlite3 *db;
59264   assert( p!=0 );
59265   db = p->db;
59266   assert( p->magic==VDBE_MAGIC_INIT );
59267   if( p->aOp==0 || db->mallocFailed ){
59268     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
59269       freeP4(db, n, (void*)*(char**)&zP4);
59270     }
59271     return;
59272   }
59273   assert( p->nOp>0 );
59274   assert( addr<p->nOp );
59275   if( addr<0 ){
59276     addr = p->nOp - 1;
59277   }
59278   pOp = &p->aOp[addr];
59279   assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
59280   freeP4(db, pOp->p4type, pOp->p4.p);
59281   pOp->p4.p = 0;
59282   if( n==P4_INT32 ){
59283     /* Note: this cast is safe, because the origin data point was an int
59284     ** that was cast to a (const char *). */
59285     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
59286     pOp->p4type = P4_INT32;
59287   }else if( zP4==0 ){
59288     pOp->p4.p = 0;
59289     pOp->p4type = P4_NOTUSED;
59290   }else if( n==P4_KEYINFO ){
59291     KeyInfo *pKeyInfo;
59292     int nField, nByte;
59293
59294     nField = ((KeyInfo*)zP4)->nField;
59295     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
59296     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
59297     pOp->p4.pKeyInfo = pKeyInfo;
59298     if( pKeyInfo ){
59299       u8 *aSortOrder;
59300       memcpy((char*)pKeyInfo, zP4, nByte - nField);
59301       aSortOrder = pKeyInfo->aSortOrder;
59302       assert( aSortOrder!=0 );
59303       pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
59304       memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
59305       pOp->p4type = P4_KEYINFO;
59306     }else{
59307       p->db->mallocFailed = 1;
59308       pOp->p4type = P4_NOTUSED;
59309     }
59310   }else if( n==P4_KEYINFO_HANDOFF ){
59311     pOp->p4.p = (void*)zP4;
59312     pOp->p4type = P4_KEYINFO;
59313   }else if( n==P4_VTAB ){
59314     pOp->p4.p = (void*)zP4;
59315     pOp->p4type = P4_VTAB;
59316     sqlite3VtabLock((VTable *)zP4);
59317     assert( ((VTable *)zP4)->db==p->db );
59318   }else if( n<0 ){
59319     pOp->p4.p = (void*)zP4;
59320     pOp->p4type = (signed char)n;
59321   }else{
59322     if( n==0 ) n = sqlite3Strlen30(zP4);
59323     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
59324     pOp->p4type = P4_DYNAMIC;
59325   }
59326 }
59327
59328 #ifndef NDEBUG
59329 /*
59330 ** Change the comment on the most recently coded instruction.  Or
59331 ** insert a No-op and add the comment to that new instruction.  This
59332 ** makes the code easier to read during debugging.  None of this happens
59333 ** in a production build.
59334 */
59335 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
59336   assert( p->nOp>0 || p->aOp==0 );
59337   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
59338   if( p->nOp ){
59339     assert( p->aOp );
59340     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
59341     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
59342   }
59343 }
59344 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
59345   va_list ap;
59346   if( p ){
59347     va_start(ap, zFormat);
59348     vdbeVComment(p, zFormat, ap);
59349     va_end(ap);
59350   }
59351 }
59352 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
59353   va_list ap;
59354   if( p ){
59355     sqlite3VdbeAddOp0(p, OP_Noop);
59356     va_start(ap, zFormat);
59357     vdbeVComment(p, zFormat, ap);
59358     va_end(ap);
59359   }
59360 }
59361 #endif  /* NDEBUG */
59362
59363 /*
59364 ** Return the opcode for a given address.  If the address is -1, then
59365 ** return the most recently inserted opcode.
59366 **
59367 ** If a memory allocation error has occurred prior to the calling of this
59368 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
59369 ** is readable but not writable, though it is cast to a writable value.
59370 ** The return of a dummy opcode allows the call to continue functioning
59371 ** after a OOM fault without having to check to see if the return from 
59372 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
59373 ** dummy will never be written to.  This is verified by code inspection and
59374 ** by running with Valgrind.
59375 **
59376 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
59377 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
59378 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
59379 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
59380 ** having to double-check to make sure that the result is non-negative. But
59381 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
59382 ** check the value of p->nOp-1 before continuing.
59383 */
59384 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
59385   /* C89 specifies that the constant "dummy" will be initialized to all
59386   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
59387   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
59388   assert( p->magic==VDBE_MAGIC_INIT );
59389   if( addr<0 ){
59390 #ifdef SQLITE_OMIT_TRACE
59391     if( p->nOp==0 ) return (VdbeOp*)&dummy;
59392 #endif
59393     addr = p->nOp - 1;
59394   }
59395   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
59396   if( p->db->mallocFailed ){
59397     return (VdbeOp*)&dummy;
59398   }else{
59399     return &p->aOp[addr];
59400   }
59401 }
59402
59403 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
59404      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59405 /*
59406 ** Compute a string that describes the P4 parameter for an opcode.
59407 ** Use zTemp for any required temporary buffer space.
59408 */
59409 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
59410   char *zP4 = zTemp;
59411   assert( nTemp>=20 );
59412   switch( pOp->p4type ){
59413     case P4_KEYINFO_STATIC:
59414     case P4_KEYINFO: {
59415       int i, j;
59416       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
59417       assert( pKeyInfo->aSortOrder!=0 );
59418       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
59419       i = sqlite3Strlen30(zTemp);
59420       for(j=0; j<pKeyInfo->nField; j++){
59421         CollSeq *pColl = pKeyInfo->aColl[j];
59422         const char *zColl = pColl ? pColl->zName : "nil";
59423         int n = sqlite3Strlen30(zColl);
59424         if( i+n>nTemp-6 ){
59425           memcpy(&zTemp[i],",...",4);
59426           break;
59427         }
59428         zTemp[i++] = ',';
59429         if( pKeyInfo->aSortOrder[j] ){
59430           zTemp[i++] = '-';
59431         }
59432         memcpy(&zTemp[i], zColl, n+1);
59433         i += n;
59434       }
59435       zTemp[i++] = ')';
59436       zTemp[i] = 0;
59437       assert( i<nTemp );
59438       break;
59439     }
59440     case P4_COLLSEQ: {
59441       CollSeq *pColl = pOp->p4.pColl;
59442       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59443       break;
59444     }
59445     case P4_FUNCDEF: {
59446       FuncDef *pDef = pOp->p4.pFunc;
59447       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59448       break;
59449     }
59450     case P4_INT64: {
59451       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59452       break;
59453     }
59454     case P4_INT32: {
59455       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59456       break;
59457     }
59458     case P4_REAL: {
59459       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59460       break;
59461     }
59462     case P4_MEM: {
59463       Mem *pMem = pOp->p4.pMem;
59464       if( pMem->flags & MEM_Str ){
59465         zP4 = pMem->z;
59466       }else if( pMem->flags & MEM_Int ){
59467         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59468       }else if( pMem->flags & MEM_Real ){
59469         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59470       }else if( pMem->flags & MEM_Null ){
59471         sqlite3_snprintf(nTemp, zTemp, "NULL");
59472       }else{
59473         assert( pMem->flags & MEM_Blob );
59474         zP4 = "(blob)";
59475       }
59476       break;
59477     }
59478 #ifndef SQLITE_OMIT_VIRTUALTABLE
59479     case P4_VTAB: {
59480       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59481       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59482       break;
59483     }
59484 #endif
59485     case P4_INTARRAY: {
59486       sqlite3_snprintf(nTemp, zTemp, "intarray");
59487       break;
59488     }
59489     case P4_SUBPROGRAM: {
59490       sqlite3_snprintf(nTemp, zTemp, "program");
59491       break;
59492     }
59493     case P4_ADVANCE: {
59494       zTemp[0] = 0;
59495       break;
59496     }
59497     default: {
59498       zP4 = pOp->p4.z;
59499       if( zP4==0 ){
59500         zP4 = zTemp;
59501         zTemp[0] = 0;
59502       }
59503     }
59504   }
59505   assert( zP4!=0 );
59506   return zP4;
59507 }
59508 #endif
59509
59510 /*
59511 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59512 **
59513 ** The prepared statements need to know in advance the complete set of
59514 ** attached databases that will be use.  A mask of these databases
59515 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
59516 ** p->btreeMask of databases that will require a lock.
59517 */
59518 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59519   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59520   assert( i<(int)sizeof(p->btreeMask)*8 );
59521   p->btreeMask |= ((yDbMask)1)<<i;
59522   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59523     p->lockMask |= ((yDbMask)1)<<i;
59524   }
59525 }
59526
59527 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59528 /*
59529 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59530 ** this routine obtains the mutex associated with each BtShared structure
59531 ** that may be accessed by the VM passed as an argument. In doing so it also
59532 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59533 ** that the correct busy-handler callback is invoked if required.
59534 **
59535 ** If SQLite is not threadsafe but does support shared-cache mode, then
59536 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59537 ** of all of BtShared structures accessible via the database handle 
59538 ** associated with the VM.
59539 **
59540 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59541 ** function is a no-op.
59542 **
59543 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
59544 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
59545 ** corresponding to btrees that use shared cache.  Then the runtime of
59546 ** this routine is N*N.  But as N is rarely more than 1, this should not
59547 ** be a problem.
59548 */
59549 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59550   int i;
59551   yDbMask mask;
59552   sqlite3 *db;
59553   Db *aDb;
59554   int nDb;
59555   if( p->lockMask==0 ) return;  /* The common case */
59556   db = p->db;
59557   aDb = db->aDb;
59558   nDb = db->nDb;
59559   for(i=0, mask=1; i<nDb; i++, mask += mask){
59560     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59561       sqlite3BtreeEnter(aDb[i].pBt);
59562     }
59563   }
59564 }
59565 #endif
59566
59567 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59568 /*
59569 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59570 */
59571 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59572   int i;
59573   yDbMask mask;
59574   sqlite3 *db;
59575   Db *aDb;
59576   int nDb;
59577   if( p->lockMask==0 ) return;  /* The common case */
59578   db = p->db;
59579   aDb = db->aDb;
59580   nDb = db->nDb;
59581   for(i=0, mask=1; i<nDb; i++, mask += mask){
59582     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59583       sqlite3BtreeLeave(aDb[i].pBt);
59584     }
59585   }
59586 }
59587 #endif
59588
59589 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59590 /*
59591 ** Print a single opcode.  This routine is used for debugging only.
59592 */
59593 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59594   char *zP4;
59595   char zPtr[50];
59596   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59597   if( pOut==0 ) pOut = stdout;
59598   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59599   fprintf(pOut, zFormat1, pc, 
59600       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59601 #ifdef SQLITE_DEBUG
59602       pOp->zComment ? pOp->zComment : ""
59603 #else
59604       ""
59605 #endif
59606   );
59607   fflush(pOut);
59608 }
59609 #endif
59610
59611 /*
59612 ** Release an array of N Mem elements
59613 */
59614 static void releaseMemArray(Mem *p, int N){
59615   if( p && N ){
59616     Mem *pEnd;
59617     sqlite3 *db = p->db;
59618     u8 malloc_failed = db->mallocFailed;
59619     if( db->pnBytesFreed ){
59620       for(pEnd=&p[N]; p<pEnd; p++){
59621         sqlite3DbFree(db, p->zMalloc);
59622       }
59623       return;
59624     }
59625     for(pEnd=&p[N]; p<pEnd; p++){
59626       assert( (&p[1])==pEnd || p[0].db==p[1].db );
59627
59628       /* This block is really an inlined version of sqlite3VdbeMemRelease()
59629       ** that takes advantage of the fact that the memory cell value is 
59630       ** being set to NULL after releasing any dynamic resources.
59631       **
59632       ** The justification for duplicating code is that according to 
59633       ** callgrind, this causes a certain test case to hit the CPU 4.7 
59634       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
59635       ** sqlite3MemRelease() were called from here. With -O2, this jumps
59636       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
59637       ** with no indexes using a single prepared INSERT statement, bind() 
59638       ** and reset(). Inserts are grouped into a transaction.
59639       */
59640       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59641         sqlite3VdbeMemRelease(p);
59642       }else if( p->zMalloc ){
59643         sqlite3DbFree(db, p->zMalloc);
59644         p->zMalloc = 0;
59645       }
59646
59647       p->flags = MEM_Invalid;
59648     }
59649     db->mallocFailed = malloc_failed;
59650   }
59651 }
59652
59653 /*
59654 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59655 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59656 */
59657 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59658   int i;
59659   Mem *aMem = VdbeFrameMem(p);
59660   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59661   for(i=0; i<p->nChildCsr; i++){
59662     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59663   }
59664   releaseMemArray(aMem, p->nChildMem);
59665   sqlite3DbFree(p->v->db, p);
59666 }
59667
59668 #ifndef SQLITE_OMIT_EXPLAIN
59669 /*
59670 ** Give a listing of the program in the virtual machine.
59671 **
59672 ** The interface is the same as sqlite3VdbeExec().  But instead of
59673 ** running the code, it invokes the callback once for each instruction.
59674 ** This feature is used to implement "EXPLAIN".
59675 **
59676 ** When p->explain==1, each instruction is listed.  When
59677 ** p->explain==2, only OP_Explain instructions are listed and these
59678 ** are shown in a different format.  p->explain==2 is used to implement
59679 ** EXPLAIN QUERY PLAN.
59680 **
59681 ** When p->explain==1, first the main program is listed, then each of
59682 ** the trigger subprograms are listed one by one.
59683 */
59684 SQLITE_PRIVATE int sqlite3VdbeList(
59685   Vdbe *p                   /* The VDBE */
59686 ){
59687   int nRow;                            /* Stop when row count reaches this */
59688   int nSub = 0;                        /* Number of sub-vdbes seen so far */
59689   SubProgram **apSub = 0;              /* Array of sub-vdbes */
59690   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
59691   sqlite3 *db = p->db;                 /* The database connection */
59692   int i;                               /* Loop counter */
59693   int rc = SQLITE_OK;                  /* Return code */
59694   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
59695
59696   assert( p->explain );
59697   assert( p->magic==VDBE_MAGIC_RUN );
59698   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59699
59700   /* Even though this opcode does not use dynamic strings for
59701   ** the result, result columns may become dynamic if the user calls
59702   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59703   */
59704   releaseMemArray(pMem, 8);
59705   p->pResultSet = 0;
59706
59707   if( p->rc==SQLITE_NOMEM ){
59708     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59709     ** sqlite3_column_text16() failed.  */
59710     db->mallocFailed = 1;
59711     return SQLITE_ERROR;
59712   }
59713
59714   /* When the number of output rows reaches nRow, that means the
59715   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59716   ** nRow is the sum of the number of rows in the main program, plus
59717   ** the sum of the number of rows in all trigger subprograms encountered
59718   ** so far.  The nRow value will increase as new trigger subprograms are
59719   ** encountered, but p->pc will eventually catch up to nRow.
59720   */
59721   nRow = p->nOp;
59722   if( p->explain==1 ){
59723     /* The first 8 memory cells are used for the result set.  So we will
59724     ** commandeer the 9th cell to use as storage for an array of pointers
59725     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
59726     ** cells.  */
59727     assert( p->nMem>9 );
59728     pSub = &p->aMem[9];
59729     if( pSub->flags&MEM_Blob ){
59730       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
59731       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59732       nSub = pSub->n/sizeof(Vdbe*);
59733       apSub = (SubProgram **)pSub->z;
59734     }
59735     for(i=0; i<nSub; i++){
59736       nRow += apSub[i]->nOp;
59737     }
59738   }
59739
59740   do{
59741     i = p->pc++;
59742   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59743   if( i>=nRow ){
59744     p->rc = SQLITE_OK;
59745     rc = SQLITE_DONE;
59746   }else if( db->u1.isInterrupted ){
59747     p->rc = SQLITE_INTERRUPT;
59748     rc = SQLITE_ERROR;
59749     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59750   }else{
59751     char *z;
59752     Op *pOp;
59753     if( i<p->nOp ){
59754       /* The output line number is small enough that we are still in the
59755       ** main program. */
59756       pOp = &p->aOp[i];
59757     }else{
59758       /* We are currently listing subprograms.  Figure out which one and
59759       ** pick up the appropriate opcode. */
59760       int j;
59761       i -= p->nOp;
59762       for(j=0; i>=apSub[j]->nOp; j++){
59763         i -= apSub[j]->nOp;
59764       }
59765       pOp = &apSub[j]->aOp[i];
59766     }
59767     if( p->explain==1 ){
59768       pMem->flags = MEM_Int;
59769       pMem->type = SQLITE_INTEGER;
59770       pMem->u.i = i;                                /* Program counter */
59771       pMem++;
59772   
59773       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59774       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
59775       assert( pMem->z!=0 );
59776       pMem->n = sqlite3Strlen30(pMem->z);
59777       pMem->type = SQLITE_TEXT;
59778       pMem->enc = SQLITE_UTF8;
59779       pMem++;
59780
59781       /* When an OP_Program opcode is encounter (the only opcode that has
59782       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59783       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59784       ** has not already been seen.
59785       */
59786       if( pOp->p4type==P4_SUBPROGRAM ){
59787         int nByte = (nSub+1)*sizeof(SubProgram*);
59788         int j;
59789         for(j=0; j<nSub; j++){
59790           if( apSub[j]==pOp->p4.pProgram ) break;
59791         }
59792         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
59793           apSub = (SubProgram **)pSub->z;
59794           apSub[nSub++] = pOp->p4.pProgram;
59795           pSub->flags |= MEM_Blob;
59796           pSub->n = nSub*sizeof(SubProgram*);
59797         }
59798       }
59799     }
59800
59801     pMem->flags = MEM_Int;
59802     pMem->u.i = pOp->p1;                          /* P1 */
59803     pMem->type = SQLITE_INTEGER;
59804     pMem++;
59805
59806     pMem->flags = MEM_Int;
59807     pMem->u.i = pOp->p2;                          /* P2 */
59808     pMem->type = SQLITE_INTEGER;
59809     pMem++;
59810
59811     pMem->flags = MEM_Int;
59812     pMem->u.i = pOp->p3;                          /* P3 */
59813     pMem->type = SQLITE_INTEGER;
59814     pMem++;
59815
59816     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
59817       assert( p->db->mallocFailed );
59818       return SQLITE_ERROR;
59819     }
59820     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59821     z = displayP4(pOp, pMem->z, 32);
59822     if( z!=pMem->z ){
59823       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59824     }else{
59825       assert( pMem->z!=0 );
59826       pMem->n = sqlite3Strlen30(pMem->z);
59827       pMem->enc = SQLITE_UTF8;
59828     }
59829     pMem->type = SQLITE_TEXT;
59830     pMem++;
59831
59832     if( p->explain==1 ){
59833       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
59834         assert( p->db->mallocFailed );
59835         return SQLITE_ERROR;
59836       }
59837       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59838       pMem->n = 2;
59839       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
59840       pMem->type = SQLITE_TEXT;
59841       pMem->enc = SQLITE_UTF8;
59842       pMem++;
59843   
59844 #ifdef SQLITE_DEBUG
59845       if( pOp->zComment ){
59846         pMem->flags = MEM_Str|MEM_Term;
59847         pMem->z = pOp->zComment;
59848         pMem->n = sqlite3Strlen30(pMem->z);
59849         pMem->enc = SQLITE_UTF8;
59850         pMem->type = SQLITE_TEXT;
59851       }else
59852 #endif
59853       {
59854         pMem->flags = MEM_Null;                       /* Comment */
59855         pMem->type = SQLITE_NULL;
59856       }
59857     }
59858
59859     p->nResColumn = 8 - 4*(p->explain-1);
59860     p->pResultSet = &p->aMem[1];
59861     p->rc = SQLITE_OK;
59862     rc = SQLITE_ROW;
59863   }
59864   return rc;
59865 }
59866 #endif /* SQLITE_OMIT_EXPLAIN */
59867
59868 #ifdef SQLITE_DEBUG
59869 /*
59870 ** Print the SQL that was used to generate a VDBE program.
59871 */
59872 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
59873   int nOp = p->nOp;
59874   VdbeOp *pOp;
59875   if( nOp<1 ) return;
59876   pOp = &p->aOp[0];
59877   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59878     const char *z = pOp->p4.z;
59879     while( sqlite3Isspace(*z) ) z++;
59880     printf("SQL: [%s]\n", z);
59881   }
59882 }
59883 #endif
59884
59885 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
59886 /*
59887 ** Print an IOTRACE message showing SQL content.
59888 */
59889 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
59890   int nOp = p->nOp;
59891   VdbeOp *pOp;
59892   if( sqlite3IoTrace==0 ) return;
59893   if( nOp<1 ) return;
59894   pOp = &p->aOp[0];
59895   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59896     int i, j;
59897     char z[1000];
59898     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
59899     for(i=0; sqlite3Isspace(z[i]); i++){}
59900     for(j=0; z[i]; i++){
59901       if( sqlite3Isspace(z[i]) ){
59902         if( z[i-1]!=' ' ){
59903           z[j++] = ' ';
59904         }
59905       }else{
59906         z[j++] = z[i];
59907       }
59908     }
59909     z[j] = 0;
59910     sqlite3IoTrace("SQL %s\n", z);
59911   }
59912 }
59913 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
59914
59915 /*
59916 ** Allocate space from a fixed size buffer and return a pointer to
59917 ** that space.  If insufficient space is available, return NULL.
59918 **
59919 ** The pBuf parameter is the initial value of a pointer which will
59920 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
59921 ** NULL, it means that memory space has already been allocated and that
59922 ** this routine should not allocate any new memory.  When pBuf is not
59923 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
59924 ** is NULL.
59925 **
59926 ** nByte is the number of bytes of space needed.
59927 **
59928 ** *ppFrom points to available space and pEnd points to the end of the
59929 ** available space.  When space is allocated, *ppFrom is advanced past
59930 ** the end of the allocated space.
59931 **
59932 ** *pnByte is a counter of the number of bytes of space that have failed
59933 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
59934 ** request, then increment *pnByte by the amount of the request.
59935 */
59936 static void *allocSpace(
59937   void *pBuf,          /* Where return pointer will be stored */
59938   int nByte,           /* Number of bytes to allocate */
59939   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
59940   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
59941   int *pnByte          /* If allocation cannot be made, increment *pnByte */
59942 ){
59943   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
59944   if( pBuf ) return pBuf;
59945   nByte = ROUND8(nByte);
59946   if( &(*ppFrom)[nByte] <= pEnd ){
59947     pBuf = (void*)*ppFrom;
59948     *ppFrom += nByte;
59949   }else{
59950     *pnByte += nByte;
59951   }
59952   return pBuf;
59953 }
59954
59955 /*
59956 ** Rewind the VDBE back to the beginning in preparation for
59957 ** running it.
59958 */
59959 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
59960 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
59961   int i;
59962 #endif
59963   assert( p!=0 );
59964   assert( p->magic==VDBE_MAGIC_INIT );
59965
59966   /* There should be at least one opcode.
59967   */
59968   assert( p->nOp>0 );
59969
59970   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
59971   p->magic = VDBE_MAGIC_RUN;
59972
59973 #ifdef SQLITE_DEBUG
59974   for(i=1; i<p->nMem; i++){
59975     assert( p->aMem[i].db==p->db );
59976   }
59977 #endif
59978   p->pc = -1;
59979   p->rc = SQLITE_OK;
59980   p->errorAction = OE_Abort;
59981   p->magic = VDBE_MAGIC_RUN;
59982   p->nChange = 0;
59983   p->cacheCtr = 1;
59984   p->minWriteFileFormat = 255;
59985   p->iStatement = 0;
59986   p->nFkConstraint = 0;
59987 #ifdef VDBE_PROFILE
59988   for(i=0; i<p->nOp; i++){
59989     p->aOp[i].cnt = 0;
59990     p->aOp[i].cycles = 0;
59991   }
59992 #endif
59993 }
59994
59995 /*
59996 ** Prepare a virtual machine for execution for the first time after
59997 ** creating the virtual machine.  This involves things such
59998 ** as allocating stack space and initializing the program counter.
59999 ** After the VDBE has be prepped, it can be executed by one or more
60000 ** calls to sqlite3VdbeExec().  
60001 **
60002 ** This function may be called exact once on a each virtual machine.
60003 ** After this routine is called the VM has been "packaged" and is ready
60004 ** to run.  After this routine is called, futher calls to 
60005 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
60006 ** the Vdbe from the Parse object that helped generate it so that the
60007 ** the Vdbe becomes an independent entity and the Parse object can be
60008 ** destroyed.
60009 **
60010 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
60011 ** to its initial state after it has been run.
60012 */
60013 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
60014   Vdbe *p,                       /* The VDBE */
60015   Parse *pParse                  /* Parsing context */
60016 ){
60017   sqlite3 *db;                   /* The database connection */
60018   int nVar;                      /* Number of parameters */
60019   int nMem;                      /* Number of VM memory registers */
60020   int nCursor;                   /* Number of cursors required */
60021   int nArg;                      /* Number of arguments in subprograms */
60022   int nOnce;                     /* Number of OP_Once instructions */
60023   int n;                         /* Loop counter */
60024   u8 *zCsr;                      /* Memory available for allocation */
60025   u8 *zEnd;                      /* First byte past allocated memory */
60026   int nByte;                     /* How much extra memory is needed */
60027
60028   assert( p!=0 );
60029   assert( p->nOp>0 );
60030   assert( pParse!=0 );
60031   assert( p->magic==VDBE_MAGIC_INIT );
60032   db = p->db;
60033   assert( db->mallocFailed==0 );
60034   nVar = pParse->nVar;
60035   nMem = pParse->nMem;
60036   nCursor = pParse->nTab;
60037   nArg = pParse->nMaxArg;
60038   nOnce = pParse->nOnce;
60039   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
60040   
60041   /* For each cursor required, also allocate a memory cell. Memory
60042   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
60043   ** the vdbe program. Instead they are used to allocate space for
60044   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
60045   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
60046   ** stores the blob of memory associated with cursor 1, etc.
60047   **
60048   ** See also: allocateCursor().
60049   */
60050   nMem += nCursor;
60051
60052   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
60053   ** an array to marshal SQL function arguments in.
60054   */
60055   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
60056   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
60057
60058   resolveP2Values(p, &nArg);
60059   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
60060   if( pParse->explain && nMem<10 ){
60061     nMem = 10;
60062   }
60063   memset(zCsr, 0, zEnd-zCsr);
60064   zCsr += (zCsr - (u8*)0)&7;
60065   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
60066   p->expired = 0;
60067
60068   /* Memory for registers, parameters, cursor, etc, is allocated in two
60069   ** passes.  On the first pass, we try to reuse unused space at the 
60070   ** end of the opcode array.  If we are unable to satisfy all memory
60071   ** requirements by reusing the opcode array tail, then the second
60072   ** pass will fill in the rest using a fresh allocation.  
60073   **
60074   ** This two-pass approach that reuses as much memory as possible from
60075   ** the leftover space at the end of the opcode array can significantly
60076   ** reduce the amount of memory held by a prepared statement.
60077   */
60078   do {
60079     nByte = 0;
60080     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
60081     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
60082     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
60083     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
60084     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
60085                           &zCsr, zEnd, &nByte);
60086     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
60087     if( nByte ){
60088       p->pFree = sqlite3DbMallocZero(db, nByte);
60089     }
60090     zCsr = p->pFree;
60091     zEnd = &zCsr[nByte];
60092   }while( nByte && !db->mallocFailed );
60093
60094   p->nCursor = (u16)nCursor;
60095   p->nOnceFlag = nOnce;
60096   if( p->aVar ){
60097     p->nVar = (ynVar)nVar;
60098     for(n=0; n<nVar; n++){
60099       p->aVar[n].flags = MEM_Null;
60100       p->aVar[n].db = db;
60101     }
60102   }
60103   if( p->azVar ){
60104     p->nzVar = pParse->nzVar;
60105     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
60106     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
60107   }
60108   if( p->aMem ){
60109     p->aMem--;                      /* aMem[] goes from 1..nMem */
60110     p->nMem = nMem;                 /*       not from 0..nMem-1 */
60111     for(n=1; n<=nMem; n++){
60112       p->aMem[n].flags = MEM_Invalid;
60113       p->aMem[n].db = db;
60114     }
60115   }
60116   p->explain = pParse->explain;
60117   sqlite3VdbeRewind(p);
60118 }
60119
60120 /*
60121 ** Close a VDBE cursor and release all the resources that cursor 
60122 ** happens to hold.
60123 */
60124 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
60125   if( pCx==0 ){
60126     return;
60127   }
60128   sqlite3VdbeSorterClose(p->db, pCx);
60129   if( pCx->pBt ){
60130     sqlite3BtreeClose(pCx->pBt);
60131     /* The pCx->pCursor will be close automatically, if it exists, by
60132     ** the call above. */
60133   }else if( pCx->pCursor ){
60134     sqlite3BtreeCloseCursor(pCx->pCursor);
60135   }
60136 #ifndef SQLITE_OMIT_VIRTUALTABLE
60137   if( pCx->pVtabCursor ){
60138     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
60139     const sqlite3_module *pModule = pCx->pModule;
60140     p->inVtabMethod = 1;
60141     pModule->xClose(pVtabCursor);
60142     p->inVtabMethod = 0;
60143   }
60144 #endif
60145 }
60146
60147 /*
60148 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
60149 ** is used, for example, when a trigger sub-program is halted to restore
60150 ** control to the main program.
60151 */
60152 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
60153   Vdbe *v = pFrame->v;
60154   v->aOnceFlag = pFrame->aOnceFlag;
60155   v->nOnceFlag = pFrame->nOnceFlag;
60156   v->aOp = pFrame->aOp;
60157   v->nOp = pFrame->nOp;
60158   v->aMem = pFrame->aMem;
60159   v->nMem = pFrame->nMem;
60160   v->apCsr = pFrame->apCsr;
60161   v->nCursor = pFrame->nCursor;
60162   v->db->lastRowid = pFrame->lastRowid;
60163   v->nChange = pFrame->nChange;
60164   return pFrame->pc;
60165 }
60166
60167 /*
60168 ** Close all cursors.
60169 **
60170 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
60171 ** cell array. This is necessary as the memory cell array may contain
60172 ** pointers to VdbeFrame objects, which may in turn contain pointers to
60173 ** open cursors.
60174 */
60175 static void closeAllCursors(Vdbe *p){
60176   if( p->pFrame ){
60177     VdbeFrame *pFrame;
60178     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
60179     sqlite3VdbeFrameRestore(pFrame);
60180   }
60181   p->pFrame = 0;
60182   p->nFrame = 0;
60183
60184   if( p->apCsr ){
60185     int i;
60186     for(i=0; i<p->nCursor; i++){
60187       VdbeCursor *pC = p->apCsr[i];
60188       if( pC ){
60189         sqlite3VdbeFreeCursor(p, pC);
60190         p->apCsr[i] = 0;
60191       }
60192     }
60193   }
60194   if( p->aMem ){
60195     releaseMemArray(&p->aMem[1], p->nMem);
60196   }
60197   while( p->pDelFrame ){
60198     VdbeFrame *pDel = p->pDelFrame;
60199     p->pDelFrame = pDel->pParent;
60200     sqlite3VdbeFrameDelete(pDel);
60201   }
60202 }
60203
60204 /*
60205 ** Clean up the VM after execution.
60206 **
60207 ** This routine will automatically close any cursors, lists, and/or
60208 ** sorters that were left open.  It also deletes the values of
60209 ** variables in the aVar[] array.
60210 */
60211 static void Cleanup(Vdbe *p){
60212   sqlite3 *db = p->db;
60213
60214 #ifdef SQLITE_DEBUG
60215   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
60216   ** Vdbe.aMem[] arrays have already been cleaned up.  */
60217   int i;
60218   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
60219   if( p->aMem ){
60220     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
60221   }
60222 #endif
60223
60224   sqlite3DbFree(db, p->zErrMsg);
60225   p->zErrMsg = 0;
60226   p->pResultSet = 0;
60227 }
60228
60229 /*
60230 ** Set the number of result columns that will be returned by this SQL
60231 ** statement. This is now set at compile time, rather than during
60232 ** execution of the vdbe program so that sqlite3_column_count() can
60233 ** be called on an SQL statement before sqlite3_step().
60234 */
60235 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
60236   Mem *pColName;
60237   int n;
60238   sqlite3 *db = p->db;
60239
60240   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60241   sqlite3DbFree(db, p->aColName);
60242   n = nResColumn*COLNAME_N;
60243   p->nResColumn = (u16)nResColumn;
60244   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
60245   if( p->aColName==0 ) return;
60246   while( n-- > 0 ){
60247     pColName->flags = MEM_Null;
60248     pColName->db = p->db;
60249     pColName++;
60250   }
60251 }
60252
60253 /*
60254 ** Set the name of the idx'th column to be returned by the SQL statement.
60255 ** zName must be a pointer to a nul terminated string.
60256 **
60257 ** This call must be made after a call to sqlite3VdbeSetNumCols().
60258 **
60259 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
60260 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
60261 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
60262 */
60263 SQLITE_PRIVATE int sqlite3VdbeSetColName(
60264   Vdbe *p,                         /* Vdbe being configured */
60265   int idx,                         /* Index of column zName applies to */
60266   int var,                         /* One of the COLNAME_* constants */
60267   const char *zName,               /* Pointer to buffer containing name */
60268   void (*xDel)(void*)              /* Memory management strategy for zName */
60269 ){
60270   int rc;
60271   Mem *pColName;
60272   assert( idx<p->nResColumn );
60273   assert( var<COLNAME_N );
60274   if( p->db->mallocFailed ){
60275     assert( !zName || xDel!=SQLITE_DYNAMIC );
60276     return SQLITE_NOMEM;
60277   }
60278   assert( p->aColName!=0 );
60279   pColName = &(p->aColName[idx+var*p->nResColumn]);
60280   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
60281   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
60282   return rc;
60283 }
60284
60285 /*
60286 ** A read or write transaction may or may not be active on database handle
60287 ** db. If a transaction is active, commit it. If there is a
60288 ** write-transaction spanning more than one database file, this routine
60289 ** takes care of the master journal trickery.
60290 */
60291 static int vdbeCommit(sqlite3 *db, Vdbe *p){
60292   int i;
60293   int nTrans = 0;  /* Number of databases with an active write-transaction */
60294   int rc = SQLITE_OK;
60295   int needXcommit = 0;
60296
60297 #ifdef SQLITE_OMIT_VIRTUALTABLE
60298   /* With this option, sqlite3VtabSync() is defined to be simply 
60299   ** SQLITE_OK so p is not used. 
60300   */
60301   UNUSED_PARAMETER(p);
60302 #endif
60303
60304   /* Before doing anything else, call the xSync() callback for any
60305   ** virtual module tables written in this transaction. This has to
60306   ** be done before determining whether a master journal file is 
60307   ** required, as an xSync() callback may add an attached database
60308   ** to the transaction.
60309   */
60310   rc = sqlite3VtabSync(db, &p->zErrMsg);
60311
60312   /* This loop determines (a) if the commit hook should be invoked and
60313   ** (b) how many database files have open write transactions, not 
60314   ** including the temp database. (b) is important because if more than 
60315   ** one database file has an open write transaction, a master journal
60316   ** file is required for an atomic commit.
60317   */ 
60318   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
60319     Btree *pBt = db->aDb[i].pBt;
60320     if( sqlite3BtreeIsInTrans(pBt) ){
60321       needXcommit = 1;
60322       if( i!=1 ) nTrans++;
60323       sqlite3BtreeEnter(pBt);
60324       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
60325       sqlite3BtreeLeave(pBt);
60326     }
60327   }
60328   if( rc!=SQLITE_OK ){
60329     return rc;
60330   }
60331
60332   /* If there are any write-transactions at all, invoke the commit hook */
60333   if( needXcommit && db->xCommitCallback ){
60334     rc = db->xCommitCallback(db->pCommitArg);
60335     if( rc ){
60336       return SQLITE_CONSTRAINT;
60337     }
60338   }
60339
60340   /* The simple case - no more than one database file (not counting the
60341   ** TEMP database) has a transaction active.   There is no need for the
60342   ** master-journal.
60343   **
60344   ** If the return value of sqlite3BtreeGetFilename() is a zero length
60345   ** string, it means the main database is :memory: or a temp file.  In 
60346   ** that case we do not support atomic multi-file commits, so use the 
60347   ** simple case then too.
60348   */
60349   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
60350    || nTrans<=1
60351   ){
60352     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60353       Btree *pBt = db->aDb[i].pBt;
60354       if( pBt ){
60355         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
60356       }
60357     }
60358
60359     /* Do the commit only if all databases successfully complete phase 1. 
60360     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
60361     ** IO error while deleting or truncating a journal file. It is unlikely,
60362     ** but could happen. In this case abandon processing and return the error.
60363     */
60364     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60365       Btree *pBt = db->aDb[i].pBt;
60366       if( pBt ){
60367         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
60368       }
60369     }
60370     if( rc==SQLITE_OK ){
60371       sqlite3VtabCommit(db);
60372     }
60373   }
60374
60375   /* The complex case - There is a multi-file write-transaction active.
60376   ** This requires a master journal file to ensure the transaction is
60377   ** committed atomicly.
60378   */
60379 #ifndef SQLITE_OMIT_DISKIO
60380   else{
60381     sqlite3_vfs *pVfs = db->pVfs;
60382     int needSync = 0;
60383     char *zMaster = 0;   /* File-name for the master journal */
60384     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
60385     sqlite3_file *pMaster = 0;
60386     i64 offset = 0;
60387     int res;
60388     int retryCount = 0;
60389     int nMainFile;
60390
60391     /* Select a master journal file name */
60392     nMainFile = sqlite3Strlen30(zMainFile);
60393     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
60394     if( zMaster==0 ) return SQLITE_NOMEM;
60395     do {
60396       u32 iRandom;
60397       if( retryCount ){
60398         if( retryCount>100 ){
60399           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
60400           sqlite3OsDelete(pVfs, zMaster, 0);
60401           break;
60402         }else if( retryCount==1 ){
60403           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
60404         }
60405       }
60406       retryCount++;
60407       sqlite3_randomness(sizeof(iRandom), &iRandom);
60408       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
60409                                (iRandom>>8)&0xffffff, iRandom&0xff);
60410       /* The antipenultimate character of the master journal name must
60411       ** be "9" to avoid name collisions when using 8+3 filenames. */
60412       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
60413       sqlite3FileSuffix3(zMainFile, zMaster);
60414       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
60415     }while( rc==SQLITE_OK && res );
60416     if( rc==SQLITE_OK ){
60417       /* Open the master journal. */
60418       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
60419           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
60420           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
60421       );
60422     }
60423     if( rc!=SQLITE_OK ){
60424       sqlite3DbFree(db, zMaster);
60425       return rc;
60426     }
60427  
60428     /* Write the name of each database file in the transaction into the new
60429     ** master journal file. If an error occurs at this point close
60430     ** and delete the master journal file. All the individual journal files
60431     ** still have 'null' as the master journal pointer, so they will roll
60432     ** back independently if a failure occurs.
60433     */
60434     for(i=0; i<db->nDb; i++){
60435       Btree *pBt = db->aDb[i].pBt;
60436       if( sqlite3BtreeIsInTrans(pBt) ){
60437         char const *zFile = sqlite3BtreeGetJournalname(pBt);
60438         if( zFile==0 ){
60439           continue;  /* Ignore TEMP and :memory: databases */
60440         }
60441         assert( zFile[0]!=0 );
60442         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60443           needSync = 1;
60444         }
60445         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60446         offset += sqlite3Strlen30(zFile)+1;
60447         if( rc!=SQLITE_OK ){
60448           sqlite3OsCloseFree(pMaster);
60449           sqlite3OsDelete(pVfs, zMaster, 0);
60450           sqlite3DbFree(db, zMaster);
60451           return rc;
60452         }
60453       }
60454     }
60455
60456     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60457     ** flag is set this is not required.
60458     */
60459     if( needSync 
60460      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60461      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60462     ){
60463       sqlite3OsCloseFree(pMaster);
60464       sqlite3OsDelete(pVfs, zMaster, 0);
60465       sqlite3DbFree(db, zMaster);
60466       return rc;
60467     }
60468
60469     /* Sync all the db files involved in the transaction. The same call
60470     ** sets the master journal pointer in each individual journal. If
60471     ** an error occurs here, do not delete the master journal file.
60472     **
60473     ** If the error occurs during the first call to
60474     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60475     ** master journal file will be orphaned. But we cannot delete it,
60476     ** in case the master journal file name was written into the journal
60477     ** file before the failure occurred.
60478     */
60479     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
60480       Btree *pBt = db->aDb[i].pBt;
60481       if( pBt ){
60482         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60483       }
60484     }
60485     sqlite3OsCloseFree(pMaster);
60486     assert( rc!=SQLITE_BUSY );
60487     if( rc!=SQLITE_OK ){
60488       sqlite3DbFree(db, zMaster);
60489       return rc;
60490     }
60491
60492     /* Delete the master journal file. This commits the transaction. After
60493     ** doing this the directory is synced again before any individual
60494     ** transaction files are deleted.
60495     */
60496     rc = sqlite3OsDelete(pVfs, zMaster, 1);
60497     sqlite3DbFree(db, zMaster);
60498     zMaster = 0;
60499     if( rc ){
60500       return rc;
60501     }
60502
60503     /* All files and directories have already been synced, so the following
60504     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60505     ** deleting or truncating journals. If something goes wrong while
60506     ** this is happening we don't really care. The integrity of the
60507     ** transaction is already guaranteed, but some stray 'cold' journals
60508     ** may be lying around. Returning an error code won't help matters.
60509     */
60510     disable_simulated_io_errors();
60511     sqlite3BeginBenignMalloc();
60512     for(i=0; i<db->nDb; i++){ 
60513       Btree *pBt = db->aDb[i].pBt;
60514       if( pBt ){
60515         sqlite3BtreeCommitPhaseTwo(pBt, 1);
60516       }
60517     }
60518     sqlite3EndBenignMalloc();
60519     enable_simulated_io_errors();
60520
60521     sqlite3VtabCommit(db);
60522   }
60523 #endif
60524
60525   return rc;
60526 }
60527
60528 /* 
60529 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60530 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60531 ** currently active. An assertion fails if the two counts do not match.
60532 ** This is an internal self-check only - it is not an essential processing
60533 ** step.
60534 **
60535 ** This is a no-op if NDEBUG is defined.
60536 */
60537 #ifndef NDEBUG
60538 static void checkActiveVdbeCnt(sqlite3 *db){
60539   Vdbe *p;
60540   int cnt = 0;
60541   int nWrite = 0;
60542   p = db->pVdbe;
60543   while( p ){
60544     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60545       cnt++;
60546       if( p->readOnly==0 ) nWrite++;
60547     }
60548     p = p->pNext;
60549   }
60550   assert( cnt==db->activeVdbeCnt );
60551   assert( nWrite==db->writeVdbeCnt );
60552 }
60553 #else
60554 #define checkActiveVdbeCnt(x)
60555 #endif
60556
60557 /*
60558 ** If the Vdbe passed as the first argument opened a statement-transaction,
60559 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60560 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60561 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
60562 ** statement transaction is commtted.
60563 **
60564 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
60565 ** Otherwise SQLITE_OK.
60566 */
60567 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60568   sqlite3 *const db = p->db;
60569   int rc = SQLITE_OK;
60570
60571   /* If p->iStatement is greater than zero, then this Vdbe opened a 
60572   ** statement transaction that should be closed here. The only exception
60573   ** is that an IO error may have occured, causing an emergency rollback.
60574   ** In this case (db->nStatement==0), and there is nothing to do.
60575   */
60576   if( db->nStatement && p->iStatement ){
60577     int i;
60578     const int iSavepoint = p->iStatement-1;
60579
60580     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60581     assert( db->nStatement>0 );
60582     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60583
60584     for(i=0; i<db->nDb; i++){ 
60585       int rc2 = SQLITE_OK;
60586       Btree *pBt = db->aDb[i].pBt;
60587       if( pBt ){
60588         if( eOp==SAVEPOINT_ROLLBACK ){
60589           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60590         }
60591         if( rc2==SQLITE_OK ){
60592           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60593         }
60594         if( rc==SQLITE_OK ){
60595           rc = rc2;
60596         }
60597       }
60598     }
60599     db->nStatement--;
60600     p->iStatement = 0;
60601
60602     if( rc==SQLITE_OK ){
60603       if( eOp==SAVEPOINT_ROLLBACK ){
60604         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60605       }
60606       if( rc==SQLITE_OK ){
60607         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60608       }
60609     }
60610
60611     /* If the statement transaction is being rolled back, also restore the 
60612     ** database handles deferred constraint counter to the value it had when 
60613     ** the statement transaction was opened.  */
60614     if( eOp==SAVEPOINT_ROLLBACK ){
60615       db->nDeferredCons = p->nStmtDefCons;
60616     }
60617   }
60618   return rc;
60619 }
60620
60621 /*
60622 ** This function is called when a transaction opened by the database 
60623 ** handle associated with the VM passed as an argument is about to be 
60624 ** committed. If there are outstanding deferred foreign key constraint
60625 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60626 **
60627 ** If there are outstanding FK violations and this function returns 
60628 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
60629 ** an error message to it. Then return SQLITE_ERROR.
60630 */
60631 #ifndef SQLITE_OMIT_FOREIGN_KEY
60632 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60633   sqlite3 *db = p->db;
60634   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60635     p->rc = SQLITE_CONSTRAINT;
60636     p->errorAction = OE_Abort;
60637     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60638     return SQLITE_ERROR;
60639   }
60640   return SQLITE_OK;
60641 }
60642 #endif
60643
60644 /*
60645 ** This routine is called the when a VDBE tries to halt.  If the VDBE
60646 ** has made changes and is in autocommit mode, then commit those
60647 ** changes.  If a rollback is needed, then do the rollback.
60648 **
60649 ** This routine is the only way to move the state of a VM from
60650 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
60651 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60652 **
60653 ** Return an error code.  If the commit could not complete because of
60654 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
60655 ** means the close did not happen and needs to be repeated.
60656 */
60657 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60658   int rc;                         /* Used to store transient return codes */
60659   sqlite3 *db = p->db;
60660
60661   /* This function contains the logic that determines if a statement or
60662   ** transaction will be committed or rolled back as a result of the
60663   ** execution of this virtual machine. 
60664   **
60665   ** If any of the following errors occur:
60666   **
60667   **     SQLITE_NOMEM
60668   **     SQLITE_IOERR
60669   **     SQLITE_FULL
60670   **     SQLITE_INTERRUPT
60671   **
60672   ** Then the internal cache might have been left in an inconsistent
60673   ** state.  We need to rollback the statement transaction, if there is
60674   ** one, or the complete transaction if there is no statement transaction.
60675   */
60676
60677   if( p->db->mallocFailed ){
60678     p->rc = SQLITE_NOMEM;
60679   }
60680   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
60681   closeAllCursors(p);
60682   if( p->magic!=VDBE_MAGIC_RUN ){
60683     return SQLITE_OK;
60684   }
60685   checkActiveVdbeCnt(db);
60686
60687   /* No commit or rollback needed if the program never started */
60688   if( p->pc>=0 ){
60689     int mrc;   /* Primary error code from p->rc */
60690     int eStatementOp = 0;
60691     int isSpecialError;            /* Set to true if a 'special' error */
60692
60693     /* Lock all btrees used by the statement */
60694     sqlite3VdbeEnter(p);
60695
60696     /* Check for one of the special errors */
60697     mrc = p->rc & 0xff;
60698     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
60699     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60700                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60701     if( isSpecialError ){
60702       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
60703       ** no rollback is necessary. Otherwise, at least a savepoint 
60704       ** transaction must be rolled back to restore the database to a 
60705       ** consistent state.
60706       **
60707       ** Even if the statement is read-only, it is important to perform
60708       ** a statement or transaction rollback operation. If the error 
60709       ** occured while writing to the journal, sub-journal or database
60710       ** file as part of an effort to free up cache space (see function
60711       ** pagerStress() in pager.c), the rollback is required to restore 
60712       ** the pager to a consistent state.
60713       */
60714       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60715         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60716           eStatementOp = SAVEPOINT_ROLLBACK;
60717         }else{
60718           /* We are forced to roll back the active transaction. Before doing
60719           ** so, abort any other statements this handle currently has active.
60720           */
60721           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60722           sqlite3CloseSavepoints(db);
60723           db->autoCommit = 1;
60724         }
60725       }
60726     }
60727
60728     /* Check for immediate foreign key violations. */
60729     if( p->rc==SQLITE_OK ){
60730       sqlite3VdbeCheckFk(p, 0);
60731     }
60732   
60733     /* If the auto-commit flag is set and this is the only active writer 
60734     ** VM, then we do either a commit or rollback of the current transaction. 
60735     **
60736     ** Note: This block also runs if one of the special errors handled 
60737     ** above has occurred. 
60738     */
60739     if( !sqlite3VtabInSync(db) 
60740      && db->autoCommit 
60741      && db->writeVdbeCnt==(p->readOnly==0) 
60742     ){
60743       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60744         rc = sqlite3VdbeCheckFk(p, 1);
60745         if( rc!=SQLITE_OK ){
60746           if( NEVER(p->readOnly) ){
60747             sqlite3VdbeLeave(p);
60748             return SQLITE_ERROR;
60749           }
60750           rc = SQLITE_CONSTRAINT;
60751         }else{ 
60752           /* The auto-commit flag is true, the vdbe program was successful 
60753           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60754           ** key constraints to hold up the transaction. This means a commit 
60755           ** is required. */
60756           rc = vdbeCommit(db, p);
60757         }
60758         if( rc==SQLITE_BUSY && p->readOnly ){
60759           sqlite3VdbeLeave(p);
60760           return SQLITE_BUSY;
60761         }else if( rc!=SQLITE_OK ){
60762           p->rc = rc;
60763           sqlite3RollbackAll(db, SQLITE_OK);
60764         }else{
60765           db->nDeferredCons = 0;
60766           sqlite3CommitInternalChanges(db);
60767         }
60768       }else{
60769         sqlite3RollbackAll(db, SQLITE_OK);
60770       }
60771       db->nStatement = 0;
60772     }else if( eStatementOp==0 ){
60773       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60774         eStatementOp = SAVEPOINT_RELEASE;
60775       }else if( p->errorAction==OE_Abort ){
60776         eStatementOp = SAVEPOINT_ROLLBACK;
60777       }else{
60778         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60779         sqlite3CloseSavepoints(db);
60780         db->autoCommit = 1;
60781       }
60782     }
60783   
60784     /* If eStatementOp is non-zero, then a statement transaction needs to
60785     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60786     ** do so. If this operation returns an error, and the current statement
60787     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60788     ** current statement error code.
60789     */
60790     if( eStatementOp ){
60791       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60792       if( rc ){
60793         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
60794           p->rc = rc;
60795           sqlite3DbFree(db, p->zErrMsg);
60796           p->zErrMsg = 0;
60797         }
60798         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60799         sqlite3CloseSavepoints(db);
60800         db->autoCommit = 1;
60801       }
60802     }
60803   
60804     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60805     ** has been rolled back, update the database connection change-counter. 
60806     */
60807     if( p->changeCntOn ){
60808       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60809         sqlite3VdbeSetChanges(db, p->nChange);
60810       }else{
60811         sqlite3VdbeSetChanges(db, 0);
60812       }
60813       p->nChange = 0;
60814     }
60815
60816     /* Release the locks */
60817     sqlite3VdbeLeave(p);
60818   }
60819
60820   /* We have successfully halted and closed the VM.  Record this fact. */
60821   if( p->pc>=0 ){
60822     db->activeVdbeCnt--;
60823     if( !p->readOnly ){
60824       db->writeVdbeCnt--;
60825     }
60826     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
60827   }
60828   p->magic = VDBE_MAGIC_HALT;
60829   checkActiveVdbeCnt(db);
60830   if( p->db->mallocFailed ){
60831     p->rc = SQLITE_NOMEM;
60832   }
60833
60834   /* If the auto-commit flag is set to true, then any locks that were held
60835   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
60836   ** to invoke any required unlock-notify callbacks.
60837   */
60838   if( db->autoCommit ){
60839     sqlite3ConnectionUnlocked(db);
60840   }
60841
60842   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
60843   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
60844 }
60845
60846
60847 /*
60848 ** Each VDBE holds the result of the most recent sqlite3_step() call
60849 ** in p->rc.  This routine sets that result back to SQLITE_OK.
60850 */
60851 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
60852   p->rc = SQLITE_OK;
60853 }
60854
60855 /*
60856 ** Copy the error code and error message belonging to the VDBE passed
60857 ** as the first argument to its database handle (so that they will be 
60858 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
60859 **
60860 ** This function does not clear the VDBE error code or message, just
60861 ** copies them to the database handle.
60862 */
60863 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
60864   sqlite3 *db = p->db;
60865   int rc = p->rc;
60866   if( p->zErrMsg ){
60867     u8 mallocFailed = db->mallocFailed;
60868     sqlite3BeginBenignMalloc();
60869     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60870     sqlite3EndBenignMalloc();
60871     db->mallocFailed = mallocFailed;
60872     db->errCode = rc;
60873   }else{
60874     sqlite3Error(db, rc, 0);
60875   }
60876   return rc;
60877 }
60878
60879 #ifdef SQLITE_ENABLE_SQLLOG
60880 /*
60881 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
60882 ** invoke it.
60883 */
60884 static void vdbeInvokeSqllog(Vdbe *v){
60885   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
60886     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
60887     assert( v->db->init.busy==0 );
60888     if( zExpanded ){
60889       sqlite3GlobalConfig.xSqllog(
60890           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
60891       );
60892       sqlite3DbFree(v->db, zExpanded);
60893     }
60894   }
60895 }
60896 #else
60897 # define vdbeInvokeSqllog(x)
60898 #endif
60899
60900 /*
60901 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
60902 ** Write any error messages into *pzErrMsg.  Return the result code.
60903 **
60904 ** After this routine is run, the VDBE should be ready to be executed
60905 ** again.
60906 **
60907 ** To look at it another way, this routine resets the state of the
60908 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
60909 ** VDBE_MAGIC_INIT.
60910 */
60911 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
60912   sqlite3 *db;
60913   db = p->db;
60914
60915   /* If the VM did not run to completion or if it encountered an
60916   ** error, then it might not have been halted properly.  So halt
60917   ** it now.
60918   */
60919   sqlite3VdbeHalt(p);
60920
60921   /* If the VDBE has be run even partially, then transfer the error code
60922   ** and error message from the VDBE into the main database structure.  But
60923   ** if the VDBE has just been set to run but has not actually executed any
60924   ** instructions yet, leave the main database error information unchanged.
60925   */
60926   if( p->pc>=0 ){
60927     vdbeInvokeSqllog(p);
60928     sqlite3VdbeTransferError(p);
60929     sqlite3DbFree(db, p->zErrMsg);
60930     p->zErrMsg = 0;
60931     if( p->runOnlyOnce ) p->expired = 1;
60932   }else if( p->rc && p->expired ){
60933     /* The expired flag was set on the VDBE before the first call
60934     ** to sqlite3_step(). For consistency (since sqlite3_step() was
60935     ** called), set the database error in this case as well.
60936     */
60937     sqlite3Error(db, p->rc, 0);
60938     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60939     sqlite3DbFree(db, p->zErrMsg);
60940     p->zErrMsg = 0;
60941   }
60942
60943   /* Reclaim all memory used by the VDBE
60944   */
60945   Cleanup(p);
60946
60947   /* Save profiling information from this VDBE run.
60948   */
60949 #ifdef VDBE_PROFILE
60950   {
60951     FILE *out = fopen("vdbe_profile.out", "a");
60952     if( out ){
60953       int i;
60954       fprintf(out, "---- ");
60955       for(i=0; i<p->nOp; i++){
60956         fprintf(out, "%02x", p->aOp[i].opcode);
60957       }
60958       fprintf(out, "\n");
60959       for(i=0; i<p->nOp; i++){
60960         fprintf(out, "%6d %10lld %8lld ",
60961            p->aOp[i].cnt,
60962            p->aOp[i].cycles,
60963            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
60964         );
60965         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
60966       }
60967       fclose(out);
60968     }
60969   }
60970 #endif
60971   p->magic = VDBE_MAGIC_INIT;
60972   return p->rc & db->errMask;
60973 }
60974  
60975 /*
60976 ** Clean up and delete a VDBE after execution.  Return an integer which is
60977 ** the result code.  Write any error message text into *pzErrMsg.
60978 */
60979 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
60980   int rc = SQLITE_OK;
60981   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
60982     rc = sqlite3VdbeReset(p);
60983     assert( (rc & p->db->errMask)==rc );
60984   }
60985   sqlite3VdbeDelete(p);
60986   return rc;
60987 }
60988
60989 /*
60990 ** Call the destructor for each auxdata entry in pVdbeFunc for which
60991 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
60992 ** are always destroyed.  To destroy all auxdata entries, call this
60993 ** routine with mask==0.
60994 */
60995 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
60996   int i;
60997   for(i=0; i<pVdbeFunc->nAux; i++){
60998     struct AuxData *pAux = &pVdbeFunc->apAux[i];
60999     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
61000       if( pAux->xDelete ){
61001         pAux->xDelete(pAux->pAux);
61002       }
61003       pAux->pAux = 0;
61004     }
61005   }
61006 }
61007
61008 /*
61009 ** Free all memory associated with the Vdbe passed as the second argument,
61010 ** except for object itself, which is preserved.
61011 **
61012 ** The difference between this function and sqlite3VdbeDelete() is that
61013 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
61014 ** the database connection and frees the object itself.
61015 */
61016 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
61017   SubProgram *pSub, *pNext;
61018   int i;
61019   assert( p->db==0 || p->db==db );
61020   releaseMemArray(p->aVar, p->nVar);
61021   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61022   for(pSub=p->pProgram; pSub; pSub=pNext){
61023     pNext = pSub->pNext;
61024     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
61025     sqlite3DbFree(db, pSub);
61026   }
61027   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
61028   vdbeFreeOpArray(db, p->aOp, p->nOp);
61029   sqlite3DbFree(db, p->aLabel);
61030   sqlite3DbFree(db, p->aColName);
61031   sqlite3DbFree(db, p->zSql);
61032   sqlite3DbFree(db, p->pFree);
61033 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
61034   sqlite3_free(p->zExplain);
61035   sqlite3DbFree(db, p->pExplain);
61036 #endif
61037 }
61038
61039 /*
61040 ** Delete an entire VDBE.
61041 */
61042 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
61043   sqlite3 *db;
61044
61045   if( NEVER(p==0) ) return;
61046   db = p->db;
61047   assert( sqlite3_mutex_held(db->mutex) );
61048   sqlite3VdbeClearObject(db, p);
61049   if( p->pPrev ){
61050     p->pPrev->pNext = p->pNext;
61051   }else{
61052     assert( db->pVdbe==p );
61053     db->pVdbe = p->pNext;
61054   }
61055   if( p->pNext ){
61056     p->pNext->pPrev = p->pPrev;
61057   }
61058   p->magic = VDBE_MAGIC_DEAD;
61059   p->db = 0;
61060   sqlite3DbFree(db, p);
61061 }
61062
61063 /*
61064 ** Make sure the cursor p is ready to read or write the row to which it
61065 ** was last positioned.  Return an error code if an OOM fault or I/O error
61066 ** prevents us from positioning the cursor to its correct position.
61067 **
61068 ** If a MoveTo operation is pending on the given cursor, then do that
61069 ** MoveTo now.  If no move is pending, check to see if the row has been
61070 ** deleted out from under the cursor and if it has, mark the row as
61071 ** a NULL row.
61072 **
61073 ** If the cursor is already pointing to the correct row and that row has
61074 ** not been deleted out from under the cursor, then this routine is a no-op.
61075 */
61076 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
61077   if( p->deferredMoveto ){
61078     int res, rc;
61079 #ifdef SQLITE_TEST
61080     extern int sqlite3_search_count;
61081 #endif
61082     assert( p->isTable );
61083     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
61084     if( rc ) return rc;
61085     p->lastRowid = p->movetoTarget;
61086     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
61087     p->rowidIsValid = 1;
61088 #ifdef SQLITE_TEST
61089     sqlite3_search_count++;
61090 #endif
61091     p->deferredMoveto = 0;
61092     p->cacheStatus = CACHE_STALE;
61093   }else if( ALWAYS(p->pCursor) ){
61094     int hasMoved;
61095     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
61096     if( rc ) return rc;
61097     if( hasMoved ){
61098       p->cacheStatus = CACHE_STALE;
61099       p->nullRow = 1;
61100     }
61101   }
61102   return SQLITE_OK;
61103 }
61104
61105 /*
61106 ** The following functions:
61107 **
61108 ** sqlite3VdbeSerialType()
61109 ** sqlite3VdbeSerialTypeLen()
61110 ** sqlite3VdbeSerialLen()
61111 ** sqlite3VdbeSerialPut()
61112 ** sqlite3VdbeSerialGet()
61113 **
61114 ** encapsulate the code that serializes values for storage in SQLite
61115 ** data and index records. Each serialized value consists of a
61116 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
61117 ** integer, stored as a varint.
61118 **
61119 ** In an SQLite index record, the serial type is stored directly before
61120 ** the blob of data that it corresponds to. In a table record, all serial
61121 ** types are stored at the start of the record, and the blobs of data at
61122 ** the end. Hence these functions allow the caller to handle the
61123 ** serial-type and data blob seperately.
61124 **
61125 ** The following table describes the various storage classes for data:
61126 **
61127 **   serial type        bytes of data      type
61128 **   --------------     ---------------    ---------------
61129 **      0                     0            NULL
61130 **      1                     1            signed integer
61131 **      2                     2            signed integer
61132 **      3                     3            signed integer
61133 **      4                     4            signed integer
61134 **      5                     6            signed integer
61135 **      6                     8            signed integer
61136 **      7                     8            IEEE float
61137 **      8                     0            Integer constant 0
61138 **      9                     0            Integer constant 1
61139 **     10,11                               reserved for expansion
61140 **    N>=12 and even       (N-12)/2        BLOB
61141 **    N>=13 and odd        (N-13)/2        text
61142 **
61143 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
61144 ** of SQLite will not understand those serial types.
61145 */
61146
61147 /*
61148 ** Return the serial-type for the value stored in pMem.
61149 */
61150 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
61151   int flags = pMem->flags;
61152   int n;
61153
61154   if( flags&MEM_Null ){
61155     return 0;
61156   }
61157   if( flags&MEM_Int ){
61158     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
61159 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
61160     i64 i = pMem->u.i;
61161     u64 u;
61162     if( i<0 ){
61163       if( i<(-MAX_6BYTE) ) return 6;
61164       /* Previous test prevents:  u = -(-9223372036854775808) */
61165       u = -i;
61166     }else{
61167       u = i;
61168     }
61169     if( u<=127 ){
61170       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
61171     }
61172     if( u<=32767 ) return 2;
61173     if( u<=8388607 ) return 3;
61174     if( u<=2147483647 ) return 4;
61175     if( u<=MAX_6BYTE ) return 5;
61176     return 6;
61177   }
61178   if( flags&MEM_Real ){
61179     return 7;
61180   }
61181   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
61182   n = pMem->n;
61183   if( flags & MEM_Zero ){
61184     n += pMem->u.nZero;
61185   }
61186   assert( n>=0 );
61187   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
61188 }
61189
61190 /*
61191 ** Return the length of the data corresponding to the supplied serial-type.
61192 */
61193 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
61194   if( serial_type>=12 ){
61195     return (serial_type-12)/2;
61196   }else{
61197     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
61198     return aSize[serial_type];
61199   }
61200 }
61201
61202 /*
61203 ** If we are on an architecture with mixed-endian floating 
61204 ** points (ex: ARM7) then swap the lower 4 bytes with the 
61205 ** upper 4 bytes.  Return the result.
61206 **
61207 ** For most architectures, this is a no-op.
61208 **
61209 ** (later):  It is reported to me that the mixed-endian problem
61210 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
61211 ** that early versions of GCC stored the two words of a 64-bit
61212 ** float in the wrong order.  And that error has been propagated
61213 ** ever since.  The blame is not necessarily with GCC, though.
61214 ** GCC might have just copying the problem from a prior compiler.
61215 ** I am also told that newer versions of GCC that follow a different
61216 ** ABI get the byte order right.
61217 **
61218 ** Developers using SQLite on an ARM7 should compile and run their
61219 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
61220 ** enabled, some asserts below will ensure that the byte order of
61221 ** floating point values is correct.
61222 **
61223 ** (2007-08-30)  Frank van Vugt has studied this problem closely
61224 ** and has send his findings to the SQLite developers.  Frank
61225 ** writes that some Linux kernels offer floating point hardware
61226 ** emulation that uses only 32-bit mantissas instead of a full 
61227 ** 48-bits as required by the IEEE standard.  (This is the
61228 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
61229 ** byte swapping becomes very complicated.  To avoid problems,
61230 ** the necessary byte swapping is carried out using a 64-bit integer
61231 ** rather than a 64-bit float.  Frank assures us that the code here
61232 ** works for him.  We, the developers, have no way to independently
61233 ** verify this, but Frank seems to know what he is talking about
61234 ** so we trust him.
61235 */
61236 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
61237 static u64 floatSwap(u64 in){
61238   union {
61239     u64 r;
61240     u32 i[2];
61241   } u;
61242   u32 t;
61243
61244   u.r = in;
61245   t = u.i[0];
61246   u.i[0] = u.i[1];
61247   u.i[1] = t;
61248   return u.r;
61249 }
61250 # define swapMixedEndianFloat(X)  X = floatSwap(X)
61251 #else
61252 # define swapMixedEndianFloat(X)
61253 #endif
61254
61255 /*
61256 ** Write the serialized data blob for the value stored in pMem into 
61257 ** buf. It is assumed that the caller has allocated sufficient space.
61258 ** Return the number of bytes written.
61259 **
61260 ** nBuf is the amount of space left in buf[].  nBuf must always be
61261 ** large enough to hold the entire field.  Except, if the field is
61262 ** a blob with a zero-filled tail, then buf[] might be just the right
61263 ** size to hold everything except for the zero-filled tail.  If buf[]
61264 ** is only big enough to hold the non-zero prefix, then only write that
61265 ** prefix into buf[].  But if buf[] is large enough to hold both the
61266 ** prefix and the tail then write the prefix and set the tail to all
61267 ** zeros.
61268 **
61269 ** Return the number of bytes actually written into buf[].  The number
61270 ** of bytes in the zero-filled tail is included in the return value only
61271 ** if those bytes were zeroed in buf[].
61272 */ 
61273 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
61274   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
61275   u32 len;
61276
61277   /* Integer and Real */
61278   if( serial_type<=7 && serial_type>0 ){
61279     u64 v;
61280     u32 i;
61281     if( serial_type==7 ){
61282       assert( sizeof(v)==sizeof(pMem->r) );
61283       memcpy(&v, &pMem->r, sizeof(v));
61284       swapMixedEndianFloat(v);
61285     }else{
61286       v = pMem->u.i;
61287     }
61288     len = i = sqlite3VdbeSerialTypeLen(serial_type);
61289     assert( len<=(u32)nBuf );
61290     while( i-- ){
61291       buf[i] = (u8)(v&0xFF);
61292       v >>= 8;
61293     }
61294     return len;
61295   }
61296
61297   /* String or blob */
61298   if( serial_type>=12 ){
61299     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
61300              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
61301     assert( pMem->n<=nBuf );
61302     len = pMem->n;
61303     memcpy(buf, pMem->z, len);
61304     if( pMem->flags & MEM_Zero ){
61305       len += pMem->u.nZero;
61306       assert( nBuf>=0 );
61307       if( len > (u32)nBuf ){
61308         len = (u32)nBuf;
61309       }
61310       memset(&buf[pMem->n], 0, len-pMem->n);
61311     }
61312     return len;
61313   }
61314
61315   /* NULL or constants 0 or 1 */
61316   return 0;
61317 }
61318
61319 /*
61320 ** Deserialize the data blob pointed to by buf as serial type serial_type
61321 ** and store the result in pMem.  Return the number of bytes read.
61322 */ 
61323 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
61324   const unsigned char *buf,     /* Buffer to deserialize from */
61325   u32 serial_type,              /* Serial type to deserialize */
61326   Mem *pMem                     /* Memory cell to write value into */
61327 ){
61328   switch( serial_type ){
61329     case 10:   /* Reserved for future use */
61330     case 11:   /* Reserved for future use */
61331     case 0: {  /* NULL */
61332       pMem->flags = MEM_Null;
61333       break;
61334     }
61335     case 1: { /* 1-byte signed integer */
61336       pMem->u.i = (signed char)buf[0];
61337       pMem->flags = MEM_Int;
61338       return 1;
61339     }
61340     case 2: { /* 2-byte signed integer */
61341       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
61342       pMem->flags = MEM_Int;
61343       return 2;
61344     }
61345     case 3: { /* 3-byte signed integer */
61346       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
61347       pMem->flags = MEM_Int;
61348       return 3;
61349     }
61350     case 4: { /* 4-byte signed integer */
61351       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61352       pMem->flags = MEM_Int;
61353       return 4;
61354     }
61355     case 5: { /* 6-byte signed integer */
61356       u64 x = (((signed char)buf[0])<<8) | buf[1];
61357       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
61358       x = (x<<32) | y;
61359       pMem->u.i = *(i64*)&x;
61360       pMem->flags = MEM_Int;
61361       return 6;
61362     }
61363     case 6:   /* 8-byte signed integer */
61364     case 7: { /* IEEE floating point */
61365       u64 x;
61366       u32 y;
61367 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
61368       /* Verify that integers and floating point values use the same
61369       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
61370       ** defined that 64-bit floating point values really are mixed
61371       ** endian.
61372       */
61373       static const u64 t1 = ((u64)0x3ff00000)<<32;
61374       static const double r1 = 1.0;
61375       u64 t2 = t1;
61376       swapMixedEndianFloat(t2);
61377       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
61378 #endif
61379
61380       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61381       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
61382       x = (x<<32) | y;
61383       if( serial_type==6 ){
61384         pMem->u.i = *(i64*)&x;
61385         pMem->flags = MEM_Int;
61386       }else{
61387         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
61388         swapMixedEndianFloat(x);
61389         memcpy(&pMem->r, &x, sizeof(x));
61390         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
61391       }
61392       return 8;
61393     }
61394     case 8:    /* Integer 0 */
61395     case 9: {  /* Integer 1 */
61396       pMem->u.i = serial_type-8;
61397       pMem->flags = MEM_Int;
61398       return 0;
61399     }
61400     default: {
61401       u32 len = (serial_type-12)/2;
61402       pMem->z = (char *)buf;
61403       pMem->n = len;
61404       pMem->xDel = 0;
61405       if( serial_type&0x01 ){
61406         pMem->flags = MEM_Str | MEM_Ephem;
61407       }else{
61408         pMem->flags = MEM_Blob | MEM_Ephem;
61409       }
61410       return len;
61411     }
61412   }
61413   return 0;
61414 }
61415
61416 /*
61417 ** This routine is used to allocate sufficient space for an UnpackedRecord
61418 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
61419 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
61420 **
61421 ** The space is either allocated using sqlite3DbMallocRaw() or from within
61422 ** the unaligned buffer passed via the second and third arguments (presumably
61423 ** stack space). If the former, then *ppFree is set to a pointer that should
61424 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
61425 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
61426 ** before returning.
61427 **
61428 ** If an OOM error occurs, NULL is returned.
61429 */
61430 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
61431   KeyInfo *pKeyInfo,              /* Description of the record */
61432   char *pSpace,                   /* Unaligned space available */
61433   int szSpace,                    /* Size of pSpace[] in bytes */
61434   char **ppFree                   /* OUT: Caller should free this pointer */
61435 ){
61436   UnpackedRecord *p;              /* Unpacked record to return */
61437   int nOff;                       /* Increment pSpace by nOff to align it */
61438   int nByte;                      /* Number of bytes required for *p */
61439
61440   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
61441   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
61442   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
61443   */
61444   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
61445   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
61446   if( nByte>szSpace+nOff ){
61447     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
61448     *ppFree = (char *)p;
61449     if( !p ) return 0;
61450   }else{
61451     p = (UnpackedRecord*)&pSpace[nOff];
61452     *ppFree = 0;
61453   }
61454
61455   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61456   assert( pKeyInfo->aSortOrder!=0 );
61457   p->pKeyInfo = pKeyInfo;
61458   p->nField = pKeyInfo->nField + 1;
61459   return p;
61460 }
61461
61462 /*
61463 ** Given the nKey-byte encoding of a record in pKey[], populate the 
61464 ** UnpackedRecord structure indicated by the fourth argument with the
61465 ** contents of the decoded record.
61466 */ 
61467 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61468   KeyInfo *pKeyInfo,     /* Information about the record format */
61469   int nKey,              /* Size of the binary record */
61470   const void *pKey,      /* The binary record */
61471   UnpackedRecord *p      /* Populate this structure before returning. */
61472 ){
61473   const unsigned char *aKey = (const unsigned char *)pKey;
61474   int d; 
61475   u32 idx;                        /* Offset in aKey[] to read from */
61476   u16 u;                          /* Unsigned loop counter */
61477   u32 szHdr;
61478   Mem *pMem = p->aMem;
61479
61480   p->flags = 0;
61481   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61482   idx = getVarint32(aKey, szHdr);
61483   d = szHdr;
61484   u = 0;
61485   while( idx<szHdr && u<p->nField && d<=nKey ){
61486     u32 serial_type;
61487
61488     idx += getVarint32(&aKey[idx], serial_type);
61489     pMem->enc = pKeyInfo->enc;
61490     pMem->db = pKeyInfo->db;
61491     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61492     pMem->zMalloc = 0;
61493     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61494     pMem++;
61495     u++;
61496   }
61497   assert( u<=pKeyInfo->nField + 1 );
61498   p->nField = u;
61499 }
61500
61501 /*
61502 ** This function compares the two table rows or index records
61503 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
61504 ** or positive integer if key1 is less than, equal to or 
61505 ** greater than key2.  The {nKey1, pKey1} key must be a blob
61506 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
61507 ** key must be a parsed key such as obtained from
61508 ** sqlite3VdbeParseRecord.
61509 **
61510 ** Key1 and Key2 do not have to contain the same number of fields.
61511 ** The key with fewer fields is usually compares less than the 
61512 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
61513 ** and the common prefixes are equal, then key1 is less than key2.
61514 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61515 ** equal, then the keys are considered to be equal and
61516 ** the parts beyond the common prefix are ignored.
61517 */
61518 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61519   int nKey1, const void *pKey1, /* Left key */
61520   UnpackedRecord *pPKey2        /* Right key */
61521 ){
61522   int d1;            /* Offset into aKey[] of next data element */
61523   u32 idx1;          /* Offset into aKey[] of next header element */
61524   u32 szHdr1;        /* Number of bytes in header */
61525   int i = 0;
61526   int nField;
61527   int rc = 0;
61528   const unsigned char *aKey1 = (const unsigned char *)pKey1;
61529   KeyInfo *pKeyInfo;
61530   Mem mem1;
61531
61532   pKeyInfo = pPKey2->pKeyInfo;
61533   mem1.enc = pKeyInfo->enc;
61534   mem1.db = pKeyInfo->db;
61535   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
61536   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61537
61538   /* Compilers may complain that mem1.u.i is potentially uninitialized.
61539   ** We could initialize it, as shown here, to silence those complaints.
61540   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
61541   ** the unnecessary initialization has a measurable negative performance
61542   ** impact, since this routine is a very high runner.  And so, we choose
61543   ** to ignore the compiler warnings and leave this variable uninitialized.
61544   */
61545   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
61546   
61547   idx1 = getVarint32(aKey1, szHdr1);
61548   d1 = szHdr1;
61549   nField = pKeyInfo->nField;
61550   assert( pKeyInfo->aSortOrder!=0 );
61551   while( idx1<szHdr1 && i<pPKey2->nField ){
61552     u32 serial_type1;
61553
61554     /* Read the serial types for the next element in each key. */
61555     idx1 += getVarint32( aKey1+idx1, serial_type1 );
61556     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61557
61558     /* Extract the values to be compared.
61559     */
61560     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61561
61562     /* Do the comparison
61563     */
61564     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61565                            i<nField ? pKeyInfo->aColl[i] : 0);
61566     if( rc!=0 ){
61567       assert( mem1.zMalloc==0 );  /* See comment below */
61568
61569       /* Invert the result if we are using DESC sort order. */
61570       if( i<nField && pKeyInfo->aSortOrder[i] ){
61571         rc = -rc;
61572       }
61573     
61574       /* If the PREFIX_SEARCH flag is set and all fields except the final
61575       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
61576       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61577       ** This is used by the OP_IsUnique opcode.
61578       */
61579       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61580         assert( idx1==szHdr1 && rc );
61581         assert( mem1.flags & MEM_Int );
61582         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61583         pPKey2->rowid = mem1.u.i;
61584       }
61585     
61586       return rc;
61587     }
61588     i++;
61589   }
61590
61591   /* No memory allocation is ever used on mem1.  Prove this using
61592   ** the following assert().  If the assert() fails, it indicates a
61593   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61594   */
61595   assert( mem1.zMalloc==0 );
61596
61597   /* rc==0 here means that one of the keys ran out of fields and
61598   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61599   ** flag is set, then break the tie by treating key2 as larger.
61600   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61601   ** are considered to be equal.  Otherwise, the longer key is the 
61602   ** larger.  As it happens, the pPKey2 will always be the longer
61603   ** if there is a difference.
61604   */
61605   assert( rc==0 );
61606   if( pPKey2->flags & UNPACKED_INCRKEY ){
61607     rc = -1;
61608   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61609     /* Leave rc==0 */
61610   }else if( idx1<szHdr1 ){
61611     rc = 1;
61612   }
61613   return rc;
61614 }
61615  
61616
61617 /*
61618 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61619 ** Read the rowid (the last field in the record) and store it in *rowid.
61620 ** Return SQLITE_OK if everything works, or an error code otherwise.
61621 **
61622 ** pCur might be pointing to text obtained from a corrupt database file.
61623 ** So the content cannot be trusted.  Do appropriate checks on the content.
61624 */
61625 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61626   i64 nCellKey = 0;
61627   int rc;
61628   u32 szHdr;        /* Size of the header */
61629   u32 typeRowid;    /* Serial type of the rowid */
61630   u32 lenRowid;     /* Size of the rowid */
61631   Mem m, v;
61632
61633   UNUSED_PARAMETER(db);
61634
61635   /* Get the size of the index entry.  Only indices entries of less
61636   ** than 2GiB are support - anything large must be database corruption.
61637   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61638   ** this code can safely assume that nCellKey is 32-bits  
61639   */
61640   assert( sqlite3BtreeCursorIsValid(pCur) );
61641   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61642   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
61643   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61644
61645   /* Read in the complete content of the index entry */
61646   memset(&m, 0, sizeof(m));
61647   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61648   if( rc ){
61649     return rc;
61650   }
61651
61652   /* The index entry must begin with a header size */
61653   (void)getVarint32((u8*)m.z, szHdr);
61654   testcase( szHdr==3 );
61655   testcase( szHdr==m.n );
61656   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61657     goto idx_rowid_corruption;
61658   }
61659
61660   /* The last field of the index should be an integer - the ROWID.
61661   ** Verify that the last entry really is an integer. */
61662   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61663   testcase( typeRowid==1 );
61664   testcase( typeRowid==2 );
61665   testcase( typeRowid==3 );
61666   testcase( typeRowid==4 );
61667   testcase( typeRowid==5 );
61668   testcase( typeRowid==6 );
61669   testcase( typeRowid==8 );
61670   testcase( typeRowid==9 );
61671   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61672     goto idx_rowid_corruption;
61673   }
61674   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61675   testcase( (u32)m.n==szHdr+lenRowid );
61676   if( unlikely((u32)m.n<szHdr+lenRowid) ){
61677     goto idx_rowid_corruption;
61678   }
61679
61680   /* Fetch the integer off the end of the index record */
61681   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61682   *rowid = v.u.i;
61683   sqlite3VdbeMemRelease(&m);
61684   return SQLITE_OK;
61685
61686   /* Jump here if database corruption is detected after m has been
61687   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
61688 idx_rowid_corruption:
61689   testcase( m.zMalloc!=0 );
61690   sqlite3VdbeMemRelease(&m);
61691   return SQLITE_CORRUPT_BKPT;
61692 }
61693
61694 /*
61695 ** Compare the key of the index entry that cursor pC is pointing to against
61696 ** the key string in pUnpacked.  Write into *pRes a number
61697 ** that is negative, zero, or positive if pC is less than, equal to,
61698 ** or greater than pUnpacked.  Return SQLITE_OK on success.
61699 **
61700 ** pUnpacked is either created without a rowid or is truncated so that it
61701 ** omits the rowid at the end.  The rowid at the end of the index entry
61702 ** is ignored as well.  Hence, this routine only compares the prefixes 
61703 ** of the keys prior to the final rowid, not the entire key.
61704 */
61705 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61706   VdbeCursor *pC,             /* The cursor to compare against */
61707   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
61708   int *res                    /* Write the comparison result here */
61709 ){
61710   i64 nCellKey = 0;
61711   int rc;
61712   BtCursor *pCur = pC->pCursor;
61713   Mem m;
61714
61715   assert( sqlite3BtreeCursorIsValid(pCur) );
61716   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61717   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
61718   /* nCellKey will always be between 0 and 0xffffffff because of the say
61719   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61720   if( nCellKey<=0 || nCellKey>0x7fffffff ){
61721     *res = 0;
61722     return SQLITE_CORRUPT_BKPT;
61723   }
61724   memset(&m, 0, sizeof(m));
61725   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61726   if( rc ){
61727     return rc;
61728   }
61729   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
61730   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61731   sqlite3VdbeMemRelease(&m);
61732   return SQLITE_OK;
61733 }
61734
61735 /*
61736 ** This routine sets the value to be returned by subsequent calls to
61737 ** sqlite3_changes() on the database handle 'db'. 
61738 */
61739 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61740   assert( sqlite3_mutex_held(db->mutex) );
61741   db->nChange = nChange;
61742   db->nTotalChange += nChange;
61743 }
61744
61745 /*
61746 ** Set a flag in the vdbe to update the change counter when it is finalised
61747 ** or reset.
61748 */
61749 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61750   v->changeCntOn = 1;
61751 }
61752
61753 /*
61754 ** Mark every prepared statement associated with a database connection
61755 ** as expired.
61756 **
61757 ** An expired statement means that recompilation of the statement is
61758 ** recommend.  Statements expire when things happen that make their
61759 ** programs obsolete.  Removing user-defined functions or collating
61760 ** sequences, or changing an authorization function are the types of
61761 ** things that make prepared statements obsolete.
61762 */
61763 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61764   Vdbe *p;
61765   for(p = db->pVdbe; p; p=p->pNext){
61766     p->expired = 1;
61767   }
61768 }
61769
61770 /*
61771 ** Return the database associated with the Vdbe.
61772 */
61773 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61774   return v->db;
61775 }
61776
61777 /*
61778 ** Return a pointer to an sqlite3_value structure containing the value bound
61779 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
61780 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61781 ** constants) to the value before returning it.
61782 **
61783 ** The returned value must be freed by the caller using sqlite3ValueFree().
61784 */
61785 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61786   assert( iVar>0 );
61787   if( v ){
61788     Mem *pMem = &v->aVar[iVar-1];
61789     if( 0==(pMem->flags & MEM_Null) ){
61790       sqlite3_value *pRet = sqlite3ValueNew(v->db);
61791       if( pRet ){
61792         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61793         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61794         sqlite3VdbeMemStoreType((Mem *)pRet);
61795       }
61796       return pRet;
61797     }
61798   }
61799   return 0;
61800 }
61801
61802 /*
61803 ** Configure SQL variable iVar so that binding a new value to it signals
61804 ** to sqlite3_reoptimize() that re-preparing the statement may result
61805 ** in a better query plan.
61806 */
61807 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61808   assert( iVar>0 );
61809   if( iVar>32 ){
61810     v->expmask = 0xffffffff;
61811   }else{
61812     v->expmask |= ((u32)1 << (iVar-1));
61813   }
61814 }
61815
61816 /************** End of vdbeaux.c *********************************************/
61817 /************** Begin file vdbeapi.c *****************************************/
61818 /*
61819 ** 2004 May 26
61820 **
61821 ** The author disclaims copyright to this source code.  In place of
61822 ** a legal notice, here is a blessing:
61823 **
61824 **    May you do good and not evil.
61825 **    May you find forgiveness for yourself and forgive others.
61826 **    May you share freely, never taking more than you give.
61827 **
61828 *************************************************************************
61829 **
61830 ** This file contains code use to implement APIs that are part of the
61831 ** VDBE.
61832 */
61833
61834 #ifndef SQLITE_OMIT_DEPRECATED
61835 /*
61836 ** Return TRUE (non-zero) of the statement supplied as an argument needs
61837 ** to be recompiled.  A statement needs to be recompiled whenever the
61838 ** execution environment changes in a way that would alter the program
61839 ** that sqlite3_prepare() generates.  For example, if new functions or
61840 ** collating sequences are registered or if an authorizer function is
61841 ** added or changed.
61842 */
61843 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
61844   Vdbe *p = (Vdbe*)pStmt;
61845   return p==0 || p->expired;
61846 }
61847 #endif
61848
61849 /*
61850 ** Check on a Vdbe to make sure it has not been finalized.  Log
61851 ** an error and return true if it has been finalized (or is otherwise
61852 ** invalid).  Return false if it is ok.
61853 */
61854 static int vdbeSafety(Vdbe *p){
61855   if( p->db==0 ){
61856     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
61857     return 1;
61858   }else{
61859     return 0;
61860   }
61861 }
61862 static int vdbeSafetyNotNull(Vdbe *p){
61863   if( p==0 ){
61864     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
61865     return 1;
61866   }else{
61867     return vdbeSafety(p);
61868   }
61869 }
61870
61871 /*
61872 ** The following routine destroys a virtual machine that is created by
61873 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
61874 ** success/failure code that describes the result of executing the virtual
61875 ** machine.
61876 **
61877 ** This routine sets the error code and string returned by
61878 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61879 */
61880 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
61881   int rc;
61882   if( pStmt==0 ){
61883     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
61884     ** pointer is a harmless no-op. */
61885     rc = SQLITE_OK;
61886   }else{
61887     Vdbe *v = (Vdbe*)pStmt;
61888     sqlite3 *db = v->db;
61889     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
61890     sqlite3_mutex_enter(db->mutex);
61891     rc = sqlite3VdbeFinalize(v);
61892     rc = sqlite3ApiExit(db, rc);
61893     sqlite3LeaveMutexAndCloseZombie(db);
61894   }
61895   return rc;
61896 }
61897
61898 /*
61899 ** Terminate the current execution of an SQL statement and reset it
61900 ** back to its starting state so that it can be reused. A success code from
61901 ** the prior execution is returned.
61902 **
61903 ** This routine sets the error code and string returned by
61904 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61905 */
61906 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
61907   int rc;
61908   if( pStmt==0 ){
61909     rc = SQLITE_OK;
61910   }else{
61911     Vdbe *v = (Vdbe*)pStmt;
61912     sqlite3_mutex_enter(v->db->mutex);
61913     rc = sqlite3VdbeReset(v);
61914     sqlite3VdbeRewind(v);
61915     assert( (rc & (v->db->errMask))==rc );
61916     rc = sqlite3ApiExit(v->db, rc);
61917     sqlite3_mutex_leave(v->db->mutex);
61918   }
61919   return rc;
61920 }
61921
61922 /*
61923 ** Set all the parameters in the compiled SQL statement to NULL.
61924 */
61925 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
61926   int i;
61927   int rc = SQLITE_OK;
61928   Vdbe *p = (Vdbe*)pStmt;
61929 #if SQLITE_THREADSAFE
61930   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
61931 #endif
61932   sqlite3_mutex_enter(mutex);
61933   for(i=0; i<p->nVar; i++){
61934     sqlite3VdbeMemRelease(&p->aVar[i]);
61935     p->aVar[i].flags = MEM_Null;
61936   }
61937   if( p->isPrepareV2 && p->expmask ){
61938     p->expired = 1;
61939   }
61940   sqlite3_mutex_leave(mutex);
61941   return rc;
61942 }
61943
61944
61945 /**************************** sqlite3_value_  *******************************
61946 ** The following routines extract information from a Mem or sqlite3_value
61947 ** structure.
61948 */
61949 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
61950   Mem *p = (Mem*)pVal;
61951   if( p->flags & (MEM_Blob|MEM_Str) ){
61952     sqlite3VdbeMemExpandBlob(p);
61953     p->flags &= ~MEM_Str;
61954     p->flags |= MEM_Blob;
61955     return p->n ? p->z : 0;
61956   }else{
61957     return sqlite3_value_text(pVal);
61958   }
61959 }
61960 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
61961   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
61962 }
61963 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
61964   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
61965 }
61966 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
61967   return sqlite3VdbeRealValue((Mem*)pVal);
61968 }
61969 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
61970   return (int)sqlite3VdbeIntValue((Mem*)pVal);
61971 }
61972 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
61973   return sqlite3VdbeIntValue((Mem*)pVal);
61974 }
61975 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
61976   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
61977 }
61978 #ifndef SQLITE_OMIT_UTF16
61979 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
61980   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
61981 }
61982 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
61983   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
61984 }
61985 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
61986   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
61987 }
61988 #endif /* SQLITE_OMIT_UTF16 */
61989 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
61990   return pVal->type;
61991 }
61992
61993 /**************************** sqlite3_result_  *******************************
61994 ** The following routines are used by user-defined functions to specify
61995 ** the function result.
61996 **
61997 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
61998 ** result as a string or blob but if the string or blob is too large, it
61999 ** then sets the error code to SQLITE_TOOBIG
62000 */
62001 static void setResultStrOrError(
62002   sqlite3_context *pCtx,  /* Function context */
62003   const char *z,          /* String pointer */
62004   int n,                  /* Bytes in string, or negative */
62005   u8 enc,                 /* Encoding of z.  0 for BLOBs */
62006   void (*xDel)(void*)     /* Destructor function */
62007 ){
62008   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
62009     sqlite3_result_error_toobig(pCtx);
62010   }
62011 }
62012 SQLITE_API void sqlite3_result_blob(
62013   sqlite3_context *pCtx, 
62014   const void *z, 
62015   int n, 
62016   void (*xDel)(void *)
62017 ){
62018   assert( n>=0 );
62019   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62020   setResultStrOrError(pCtx, z, n, 0, xDel);
62021 }
62022 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
62023   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62024   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
62025 }
62026 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
62027   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62028   pCtx->isError = SQLITE_ERROR;
62029   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
62030 }
62031 #ifndef SQLITE_OMIT_UTF16
62032 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
62033   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62034   pCtx->isError = SQLITE_ERROR;
62035   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
62036 }
62037 #endif
62038 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
62039   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62040   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
62041 }
62042 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
62043   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62044   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
62045 }
62046 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
62047   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62048   sqlite3VdbeMemSetNull(&pCtx->s);
62049 }
62050 SQLITE_API void sqlite3_result_text(
62051   sqlite3_context *pCtx, 
62052   const char *z, 
62053   int n,
62054   void (*xDel)(void *)
62055 ){
62056   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62057   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
62058 }
62059 #ifndef SQLITE_OMIT_UTF16
62060 SQLITE_API void sqlite3_result_text16(
62061   sqlite3_context *pCtx, 
62062   const void *z, 
62063   int n, 
62064   void (*xDel)(void *)
62065 ){
62066   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62067   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
62068 }
62069 SQLITE_API void sqlite3_result_text16be(
62070   sqlite3_context *pCtx, 
62071   const void *z, 
62072   int n, 
62073   void (*xDel)(void *)
62074 ){
62075   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62076   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
62077 }
62078 SQLITE_API void sqlite3_result_text16le(
62079   sqlite3_context *pCtx, 
62080   const void *z, 
62081   int n, 
62082   void (*xDel)(void *)
62083 ){
62084   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62085   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
62086 }
62087 #endif /* SQLITE_OMIT_UTF16 */
62088 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
62089   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62090   sqlite3VdbeMemCopy(&pCtx->s, pValue);
62091 }
62092 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
62093   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62094   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
62095 }
62096 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
62097   pCtx->isError = errCode;
62098   if( pCtx->s.flags & MEM_Null ){
62099     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
62100                          SQLITE_UTF8, SQLITE_STATIC);
62101   }
62102 }
62103
62104 /* Force an SQLITE_TOOBIG error. */
62105 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
62106   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62107   pCtx->isError = SQLITE_TOOBIG;
62108   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
62109                        SQLITE_UTF8, SQLITE_STATIC);
62110 }
62111
62112 /* An SQLITE_NOMEM error. */
62113 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
62114   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62115   sqlite3VdbeMemSetNull(&pCtx->s);
62116   pCtx->isError = SQLITE_NOMEM;
62117   pCtx->s.db->mallocFailed = 1;
62118 }
62119
62120 /*
62121 ** This function is called after a transaction has been committed. It 
62122 ** invokes callbacks registered with sqlite3_wal_hook() as required.
62123 */
62124 static int doWalCallbacks(sqlite3 *db){
62125   int rc = SQLITE_OK;
62126 #ifndef SQLITE_OMIT_WAL
62127   int i;
62128   for(i=0; i<db->nDb; i++){
62129     Btree *pBt = db->aDb[i].pBt;
62130     if( pBt ){
62131       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
62132       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
62133         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
62134       }
62135     }
62136   }
62137 #endif
62138   return rc;
62139 }
62140
62141 /*
62142 ** Execute the statement pStmt, either until a row of data is ready, the
62143 ** statement is completely executed or an error occurs.
62144 **
62145 ** This routine implements the bulk of the logic behind the sqlite_step()
62146 ** API.  The only thing omitted is the automatic recompile if a 
62147 ** schema change has occurred.  That detail is handled by the
62148 ** outer sqlite3_step() wrapper procedure.
62149 */
62150 static int sqlite3Step(Vdbe *p){
62151   sqlite3 *db;
62152   int rc;
62153
62154   assert(p);
62155   if( p->magic!=VDBE_MAGIC_RUN ){
62156     /* We used to require that sqlite3_reset() be called before retrying
62157     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
62158     ** with version 3.7.0, we changed this so that sqlite3_reset() would
62159     ** be called automatically instead of throwing the SQLITE_MISUSE error.
62160     ** This "automatic-reset" change is not technically an incompatibility, 
62161     ** since any application that receives an SQLITE_MISUSE is broken by
62162     ** definition.
62163     **
62164     ** Nevertheless, some published applications that were originally written
62165     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
62166     ** returns, and those were broken by the automatic-reset change.  As a
62167     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
62168     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
62169     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
62170     ** or SQLITE_BUSY error.
62171     */
62172 #ifdef SQLITE_OMIT_AUTORESET
62173     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
62174       sqlite3_reset((sqlite3_stmt*)p);
62175     }else{
62176       return SQLITE_MISUSE_BKPT;
62177     }
62178 #else
62179     sqlite3_reset((sqlite3_stmt*)p);
62180 #endif
62181   }
62182
62183   /* Check that malloc() has not failed. If it has, return early. */
62184   db = p->db;
62185   if( db->mallocFailed ){
62186     p->rc = SQLITE_NOMEM;
62187     return SQLITE_NOMEM;
62188   }
62189
62190   if( p->pc<=0 && p->expired ){
62191     p->rc = SQLITE_SCHEMA;
62192     rc = SQLITE_ERROR;
62193     goto end_of_step;
62194   }
62195   if( p->pc<0 ){
62196     /* If there are no other statements currently running, then
62197     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
62198     ** from interrupting a statement that has not yet started.
62199     */
62200     if( db->activeVdbeCnt==0 ){
62201       db->u1.isInterrupted = 0;
62202     }
62203
62204     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
62205
62206 #ifndef SQLITE_OMIT_TRACE
62207     if( db->xProfile && !db->init.busy ){
62208       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
62209     }
62210 #endif
62211
62212     db->activeVdbeCnt++;
62213     if( p->readOnly==0 ) db->writeVdbeCnt++;
62214     p->pc = 0;
62215   }
62216 #ifndef SQLITE_OMIT_EXPLAIN
62217   if( p->explain ){
62218     rc = sqlite3VdbeList(p);
62219   }else
62220 #endif /* SQLITE_OMIT_EXPLAIN */
62221   {
62222     db->vdbeExecCnt++;
62223     rc = sqlite3VdbeExec(p);
62224     db->vdbeExecCnt--;
62225   }
62226
62227 #ifndef SQLITE_OMIT_TRACE
62228   /* Invoke the profile callback if there is one
62229   */
62230   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
62231     sqlite3_int64 iNow;
62232     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
62233     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
62234   }
62235 #endif
62236
62237   if( rc==SQLITE_DONE ){
62238     assert( p->rc==SQLITE_OK );
62239     p->rc = doWalCallbacks(db);
62240     if( p->rc!=SQLITE_OK ){
62241       rc = SQLITE_ERROR;
62242     }
62243   }
62244
62245   db->errCode = rc;
62246   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
62247     p->rc = SQLITE_NOMEM;
62248   }
62249 end_of_step:
62250   /* At this point local variable rc holds the value that should be 
62251   ** returned if this statement was compiled using the legacy 
62252   ** sqlite3_prepare() interface. According to the docs, this can only
62253   ** be one of the values in the first assert() below. Variable p->rc 
62254   ** contains the value that would be returned if sqlite3_finalize() 
62255   ** were called on statement p.
62256   */
62257   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
62258        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
62259   );
62260   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
62261   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
62262     /* If this statement was prepared using sqlite3_prepare_v2(), and an
62263     ** error has occured, then return the error code in p->rc to the
62264     ** caller. Set the error code in the database handle to the same value.
62265     */ 
62266     rc = sqlite3VdbeTransferError(p);
62267   }
62268   return (rc&db->errMask);
62269 }
62270
62271 /*
62272 ** The maximum number of times that a statement will try to reparse
62273 ** itself before giving up and returning SQLITE_SCHEMA.
62274 */
62275 #ifndef SQLITE_MAX_SCHEMA_RETRY
62276 # define SQLITE_MAX_SCHEMA_RETRY 5
62277 #endif
62278
62279 /*
62280 ** This is the top-level implementation of sqlite3_step().  Call
62281 ** sqlite3Step() to do most of the work.  If a schema error occurs,
62282 ** call sqlite3Reprepare() and try again.
62283 */
62284 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
62285   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
62286   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
62287   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
62288   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
62289   sqlite3 *db;             /* The database connection */
62290
62291   if( vdbeSafetyNotNull(v) ){
62292     return SQLITE_MISUSE_BKPT;
62293   }
62294   db = v->db;
62295   sqlite3_mutex_enter(db->mutex);
62296   v->doingRerun = 0;
62297   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
62298          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
62299          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
62300     sqlite3_reset(pStmt);
62301     v->doingRerun = 1;
62302     assert( v->expired==0 );
62303   }
62304   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
62305     /* This case occurs after failing to recompile an sql statement. 
62306     ** The error message from the SQL compiler has already been loaded 
62307     ** into the database handle. This block copies the error message 
62308     ** from the database handle into the statement and sets the statement
62309     ** program counter to 0 to ensure that when the statement is 
62310     ** finalized or reset the parser error message is available via
62311     ** sqlite3_errmsg() and sqlite3_errcode().
62312     */
62313     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
62314     sqlite3DbFree(db, v->zErrMsg);
62315     if( !db->mallocFailed ){
62316       v->zErrMsg = sqlite3DbStrDup(db, zErr);
62317       v->rc = rc2;
62318     } else {
62319       v->zErrMsg = 0;
62320       v->rc = rc = SQLITE_NOMEM;
62321     }
62322   }
62323   rc = sqlite3ApiExit(db, rc);
62324   sqlite3_mutex_leave(db->mutex);
62325   return rc;
62326 }
62327
62328 /*
62329 ** Extract the user data from a sqlite3_context structure and return a
62330 ** pointer to it.
62331 */
62332 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
62333   assert( p && p->pFunc );
62334   return p->pFunc->pUserData;
62335 }
62336
62337 /*
62338 ** Extract the user data from a sqlite3_context structure and return a
62339 ** pointer to it.
62340 **
62341 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
62342 ** returns a copy of the pointer to the database connection (the 1st
62343 ** parameter) of the sqlite3_create_function() and
62344 ** sqlite3_create_function16() routines that originally registered the
62345 ** application defined function.
62346 */
62347 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
62348   assert( p && p->pFunc );
62349   return p->s.db;
62350 }
62351
62352 /*
62353 ** The following is the implementation of an SQL function that always
62354 ** fails with an error message stating that the function is used in the
62355 ** wrong context.  The sqlite3_overload_function() API might construct
62356 ** SQL function that use this routine so that the functions will exist
62357 ** for name resolution but are actually overloaded by the xFindFunction
62358 ** method of virtual tables.
62359 */
62360 SQLITE_PRIVATE void sqlite3InvalidFunction(
62361   sqlite3_context *context,  /* The function calling context */
62362   int NotUsed,               /* Number of arguments to the function */
62363   sqlite3_value **NotUsed2   /* Value of each argument */
62364 ){
62365   const char *zName = context->pFunc->zName;
62366   char *zErr;
62367   UNUSED_PARAMETER2(NotUsed, NotUsed2);
62368   zErr = sqlite3_mprintf(
62369       "unable to use function %s in the requested context", zName);
62370   sqlite3_result_error(context, zErr, -1);
62371   sqlite3_free(zErr);
62372 }
62373
62374 /*
62375 ** Allocate or return the aggregate context for a user function.  A new
62376 ** context is allocated on the first call.  Subsequent calls return the
62377 ** same context that was returned on prior calls.
62378 */
62379 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
62380   Mem *pMem;
62381   assert( p && p->pFunc && p->pFunc->xStep );
62382   assert( sqlite3_mutex_held(p->s.db->mutex) );
62383   pMem = p->pMem;
62384   testcase( nByte<0 );
62385   if( (pMem->flags & MEM_Agg)==0 ){
62386     if( nByte<=0 ){
62387       sqlite3VdbeMemReleaseExternal(pMem);
62388       pMem->flags = MEM_Null;
62389       pMem->z = 0;
62390     }else{
62391       sqlite3VdbeMemGrow(pMem, nByte, 0);
62392       pMem->flags = MEM_Agg;
62393       pMem->u.pDef = p->pFunc;
62394       if( pMem->z ){
62395         memset(pMem->z, 0, nByte);
62396       }
62397     }
62398   }
62399   return (void*)pMem->z;
62400 }
62401
62402 /*
62403 ** Return the auxilary data pointer, if any, for the iArg'th argument to
62404 ** the user-function defined by pCtx.
62405 */
62406 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
62407   VdbeFunc *pVdbeFunc;
62408
62409   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62410   pVdbeFunc = pCtx->pVdbeFunc;
62411   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
62412     return 0;
62413   }
62414   return pVdbeFunc->apAux[iArg].pAux;
62415 }
62416
62417 /*
62418 ** Set the auxilary data pointer and delete function, for the iArg'th
62419 ** argument to the user-function defined by pCtx. Any previous value is
62420 ** deleted by calling the delete function specified when it was set.
62421 */
62422 SQLITE_API void sqlite3_set_auxdata(
62423   sqlite3_context *pCtx, 
62424   int iArg, 
62425   void *pAux, 
62426   void (*xDelete)(void*)
62427 ){
62428   struct AuxData *pAuxData;
62429   VdbeFunc *pVdbeFunc;
62430   if( iArg<0 ) goto failed;
62431
62432   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62433   pVdbeFunc = pCtx->pVdbeFunc;
62434   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
62435     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
62436     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
62437     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
62438     if( !pVdbeFunc ){
62439       goto failed;
62440     }
62441     pCtx->pVdbeFunc = pVdbeFunc;
62442     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
62443     pVdbeFunc->nAux = iArg+1;
62444     pVdbeFunc->pFunc = pCtx->pFunc;
62445   }
62446
62447   pAuxData = &pVdbeFunc->apAux[iArg];
62448   if( pAuxData->pAux && pAuxData->xDelete ){
62449     pAuxData->xDelete(pAuxData->pAux);
62450   }
62451   pAuxData->pAux = pAux;
62452   pAuxData->xDelete = xDelete;
62453   return;
62454
62455 failed:
62456   if( xDelete ){
62457     xDelete(pAux);
62458   }
62459 }
62460
62461 #ifndef SQLITE_OMIT_DEPRECATED
62462 /*
62463 ** Return the number of times the Step function of a aggregate has been 
62464 ** called.
62465 **
62466 ** This function is deprecated.  Do not use it for new code.  It is
62467 ** provide only to avoid breaking legacy code.  New aggregate function
62468 ** implementations should keep their own counts within their aggregate
62469 ** context.
62470 */
62471 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62472   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62473   return p->pMem->n;
62474 }
62475 #endif
62476
62477 /*
62478 ** Return the number of columns in the result set for the statement pStmt.
62479 */
62480 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62481   Vdbe *pVm = (Vdbe *)pStmt;
62482   return pVm ? pVm->nResColumn : 0;
62483 }
62484
62485 /*
62486 ** Return the number of values available from the current row of the
62487 ** currently executing statement pStmt.
62488 */
62489 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62490   Vdbe *pVm = (Vdbe *)pStmt;
62491   if( pVm==0 || pVm->pResultSet==0 ) return 0;
62492   return pVm->nResColumn;
62493 }
62494
62495
62496 /*
62497 ** Check to see if column iCol of the given statement is valid.  If
62498 ** it is, return a pointer to the Mem for the value of that column.
62499 ** If iCol is not valid, return a pointer to a Mem which has a value
62500 ** of NULL.
62501 */
62502 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62503   Vdbe *pVm;
62504   Mem *pOut;
62505
62506   pVm = (Vdbe *)pStmt;
62507   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62508     sqlite3_mutex_enter(pVm->db->mutex);
62509     pOut = &pVm->pResultSet[i];
62510   }else{
62511     /* If the value passed as the second argument is out of range, return
62512     ** a pointer to the following static Mem object which contains the
62513     ** value SQL NULL. Even though the Mem structure contains an element
62514     ** of type i64, on certain architectures (x86) with certain compiler
62515     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62516     ** instead of an 8-byte one. This all works fine, except that when
62517     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62518     ** that a Mem structure is located on an 8-byte boundary. To prevent
62519     ** these assert()s from failing, when building with SQLITE_DEBUG defined
62520     ** using gcc, we force nullMem to be 8-byte aligned using the magical
62521     ** __attribute__((aligned(8))) macro.  */
62522     static const Mem nullMem 
62523 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62524       __attribute__((aligned(8))) 
62525 #endif
62526       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62527 #ifdef SQLITE_DEBUG
62528          0, 0,  /* pScopyFrom, pFiller */
62529 #endif
62530          0, 0 };
62531
62532     if( pVm && ALWAYS(pVm->db) ){
62533       sqlite3_mutex_enter(pVm->db->mutex);
62534       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62535     }
62536     pOut = (Mem*)&nullMem;
62537   }
62538   return pOut;
62539 }
62540
62541 /*
62542 ** This function is called after invoking an sqlite3_value_XXX function on a 
62543 ** column value (i.e. a value returned by evaluating an SQL expression in the
62544 ** select list of a SELECT statement) that may cause a malloc() failure. If 
62545 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62546 ** code of statement pStmt set to SQLITE_NOMEM.
62547 **
62548 ** Specifically, this is called from within:
62549 **
62550 **     sqlite3_column_int()
62551 **     sqlite3_column_int64()
62552 **     sqlite3_column_text()
62553 **     sqlite3_column_text16()
62554 **     sqlite3_column_real()
62555 **     sqlite3_column_bytes()
62556 **     sqlite3_column_bytes16()
62557 **     sqiite3_column_blob()
62558 */
62559 static void columnMallocFailure(sqlite3_stmt *pStmt)
62560 {
62561   /* If malloc() failed during an encoding conversion within an
62562   ** sqlite3_column_XXX API, then set the return code of the statement to
62563   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62564   ** and _finalize() will return NOMEM.
62565   */
62566   Vdbe *p = (Vdbe *)pStmt;
62567   if( p ){
62568     p->rc = sqlite3ApiExit(p->db, p->rc);
62569     sqlite3_mutex_leave(p->db->mutex);
62570   }
62571 }
62572
62573 /**************************** sqlite3_column_  *******************************
62574 ** The following routines are used to access elements of the current row
62575 ** in the result set.
62576 */
62577 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62578   const void *val;
62579   val = sqlite3_value_blob( columnMem(pStmt,i) );
62580   /* Even though there is no encoding conversion, value_blob() might
62581   ** need to call malloc() to expand the result of a zeroblob() 
62582   ** expression. 
62583   */
62584   columnMallocFailure(pStmt);
62585   return val;
62586 }
62587 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62588   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62589   columnMallocFailure(pStmt);
62590   return val;
62591 }
62592 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62593   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62594   columnMallocFailure(pStmt);
62595   return val;
62596 }
62597 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62598   double val = sqlite3_value_double( columnMem(pStmt,i) );
62599   columnMallocFailure(pStmt);
62600   return val;
62601 }
62602 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62603   int val = sqlite3_value_int( columnMem(pStmt,i) );
62604   columnMallocFailure(pStmt);
62605   return val;
62606 }
62607 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62608   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62609   columnMallocFailure(pStmt);
62610   return val;
62611 }
62612 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62613   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62614   columnMallocFailure(pStmt);
62615   return val;
62616 }
62617 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62618   Mem *pOut = columnMem(pStmt, i);
62619   if( pOut->flags&MEM_Static ){
62620     pOut->flags &= ~MEM_Static;
62621     pOut->flags |= MEM_Ephem;
62622   }
62623   columnMallocFailure(pStmt);
62624   return (sqlite3_value *)pOut;
62625 }
62626 #ifndef SQLITE_OMIT_UTF16
62627 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62628   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62629   columnMallocFailure(pStmt);
62630   return val;
62631 }
62632 #endif /* SQLITE_OMIT_UTF16 */
62633 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62634   int iType = sqlite3_value_type( columnMem(pStmt,i) );
62635   columnMallocFailure(pStmt);
62636   return iType;
62637 }
62638
62639 /* The following function is experimental and subject to change or
62640 ** removal */
62641 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62642 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62643 **}
62644 */
62645
62646 /*
62647 ** Convert the N-th element of pStmt->pColName[] into a string using
62648 ** xFunc() then return that string.  If N is out of range, return 0.
62649 **
62650 ** There are up to 5 names for each column.  useType determines which
62651 ** name is returned.  Here are the names:
62652 **
62653 **    0      The column name as it should be displayed for output
62654 **    1      The datatype name for the column
62655 **    2      The name of the database that the column derives from
62656 **    3      The name of the table that the column derives from
62657 **    4      The name of the table column that the result column derives from
62658 **
62659 ** If the result is not a simple column reference (if it is an expression
62660 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62661 */
62662 static const void *columnName(
62663   sqlite3_stmt *pStmt,
62664   int N,
62665   const void *(*xFunc)(Mem*),
62666   int useType
62667 ){
62668   const void *ret = 0;
62669   Vdbe *p = (Vdbe *)pStmt;
62670   int n;
62671   sqlite3 *db = p->db;
62672   
62673   assert( db!=0 );
62674   n = sqlite3_column_count(pStmt);
62675   if( N<n && N>=0 ){
62676     N += useType*n;
62677     sqlite3_mutex_enter(db->mutex);
62678     assert( db->mallocFailed==0 );
62679     ret = xFunc(&p->aColName[N]);
62680      /* A malloc may have failed inside of the xFunc() call. If this
62681     ** is the case, clear the mallocFailed flag and return NULL.
62682     */
62683     if( db->mallocFailed ){
62684       db->mallocFailed = 0;
62685       ret = 0;
62686     }
62687     sqlite3_mutex_leave(db->mutex);
62688   }
62689   return ret;
62690 }
62691
62692 /*
62693 ** Return the name of the Nth column of the result set returned by SQL
62694 ** statement pStmt.
62695 */
62696 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62697   return columnName(
62698       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62699 }
62700 #ifndef SQLITE_OMIT_UTF16
62701 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62702   return columnName(
62703       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62704 }
62705 #endif
62706
62707 /*
62708 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
62709 ** not define OMIT_DECLTYPE.
62710 */
62711 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62712 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62713          and SQLITE_ENABLE_COLUMN_METADATA"
62714 #endif
62715
62716 #ifndef SQLITE_OMIT_DECLTYPE
62717 /*
62718 ** Return the column declaration type (if applicable) of the 'i'th column
62719 ** of the result set of SQL statement pStmt.
62720 */
62721 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62722   return columnName(
62723       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62724 }
62725 #ifndef SQLITE_OMIT_UTF16
62726 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62727   return columnName(
62728       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62729 }
62730 #endif /* SQLITE_OMIT_UTF16 */
62731 #endif /* SQLITE_OMIT_DECLTYPE */
62732
62733 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62734 /*
62735 ** Return the name of the database from which a result column derives.
62736 ** NULL is returned if the result column is an expression or constant or
62737 ** anything else which is not an unabiguous reference to a database column.
62738 */
62739 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62740   return columnName(
62741       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62742 }
62743 #ifndef SQLITE_OMIT_UTF16
62744 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62745   return columnName(
62746       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62747 }
62748 #endif /* SQLITE_OMIT_UTF16 */
62749
62750 /*
62751 ** Return the name of the table from which a result column derives.
62752 ** NULL is returned if the result column is an expression or constant or
62753 ** anything else which is not an unabiguous reference to a database column.
62754 */
62755 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62756   return columnName(
62757       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62758 }
62759 #ifndef SQLITE_OMIT_UTF16
62760 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62761   return columnName(
62762       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62763 }
62764 #endif /* SQLITE_OMIT_UTF16 */
62765
62766 /*
62767 ** Return the name of the table column from which a result column derives.
62768 ** NULL is returned if the result column is an expression or constant or
62769 ** anything else which is not an unabiguous reference to a database column.
62770 */
62771 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62772   return columnName(
62773       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62774 }
62775 #ifndef SQLITE_OMIT_UTF16
62776 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62777   return columnName(
62778       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62779 }
62780 #endif /* SQLITE_OMIT_UTF16 */
62781 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62782
62783
62784 /******************************* sqlite3_bind_  ***************************
62785 ** 
62786 ** Routines used to attach values to wildcards in a compiled SQL statement.
62787 */
62788 /*
62789 ** Unbind the value bound to variable i in virtual machine p. This is the 
62790 ** the same as binding a NULL value to the column. If the "i" parameter is
62791 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62792 **
62793 ** A successful evaluation of this routine acquires the mutex on p.
62794 ** the mutex is released if any kind of error occurs.
62795 **
62796 ** The error code stored in database p->db is overwritten with the return
62797 ** value in any case.
62798 */
62799 static int vdbeUnbind(Vdbe *p, int i){
62800   Mem *pVar;
62801   if( vdbeSafetyNotNull(p) ){
62802     return SQLITE_MISUSE_BKPT;
62803   }
62804   sqlite3_mutex_enter(p->db->mutex);
62805   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62806     sqlite3Error(p->db, SQLITE_MISUSE, 0);
62807     sqlite3_mutex_leave(p->db->mutex);
62808     sqlite3_log(SQLITE_MISUSE, 
62809         "bind on a busy prepared statement: [%s]", p->zSql);
62810     return SQLITE_MISUSE_BKPT;
62811   }
62812   if( i<1 || i>p->nVar ){
62813     sqlite3Error(p->db, SQLITE_RANGE, 0);
62814     sqlite3_mutex_leave(p->db->mutex);
62815     return SQLITE_RANGE;
62816   }
62817   i--;
62818   pVar = &p->aVar[i];
62819   sqlite3VdbeMemRelease(pVar);
62820   pVar->flags = MEM_Null;
62821   sqlite3Error(p->db, SQLITE_OK, 0);
62822
62823   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
62824   ** binding a new value to this variable invalidates the current query plan.
62825   **
62826   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
62827   ** parameter in the WHERE clause might influence the choice of query plan
62828   ** for a statement, then the statement will be automatically recompiled,
62829   ** as if there had been a schema change, on the first sqlite3_step() call
62830   ** following any change to the bindings of that parameter.
62831   */
62832   if( p->isPrepareV2 &&
62833      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
62834   ){
62835     p->expired = 1;
62836   }
62837   return SQLITE_OK;
62838 }
62839
62840 /*
62841 ** Bind a text or BLOB value.
62842 */
62843 static int bindText(
62844   sqlite3_stmt *pStmt,   /* The statement to bind against */
62845   int i,                 /* Index of the parameter to bind */
62846   const void *zData,     /* Pointer to the data to be bound */
62847   int nData,             /* Number of bytes of data to be bound */
62848   void (*xDel)(void*),   /* Destructor for the data */
62849   u8 encoding            /* Encoding for the data */
62850 ){
62851   Vdbe *p = (Vdbe *)pStmt;
62852   Mem *pVar;
62853   int rc;
62854
62855   rc = vdbeUnbind(p, i);
62856   if( rc==SQLITE_OK ){
62857     if( zData!=0 ){
62858       pVar = &p->aVar[i-1];
62859       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
62860       if( rc==SQLITE_OK && encoding!=0 ){
62861         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
62862       }
62863       sqlite3Error(p->db, rc, 0);
62864       rc = sqlite3ApiExit(p->db, rc);
62865     }
62866     sqlite3_mutex_leave(p->db->mutex);
62867   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
62868     xDel((void*)zData);
62869   }
62870   return rc;
62871 }
62872
62873
62874 /*
62875 ** Bind a blob value to an SQL statement variable.
62876 */
62877 SQLITE_API int sqlite3_bind_blob(
62878   sqlite3_stmt *pStmt, 
62879   int i, 
62880   const void *zData, 
62881   int nData, 
62882   void (*xDel)(void*)
62883 ){
62884   return bindText(pStmt, i, zData, nData, xDel, 0);
62885 }
62886 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
62887   int rc;
62888   Vdbe *p = (Vdbe *)pStmt;
62889   rc = vdbeUnbind(p, i);
62890   if( rc==SQLITE_OK ){
62891     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
62892     sqlite3_mutex_leave(p->db->mutex);
62893   }
62894   return rc;
62895 }
62896 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
62897   return sqlite3_bind_int64(p, i, (i64)iValue);
62898 }
62899 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
62900   int rc;
62901   Vdbe *p = (Vdbe *)pStmt;
62902   rc = vdbeUnbind(p, i);
62903   if( rc==SQLITE_OK ){
62904     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
62905     sqlite3_mutex_leave(p->db->mutex);
62906   }
62907   return rc;
62908 }
62909 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
62910   int rc;
62911   Vdbe *p = (Vdbe*)pStmt;
62912   rc = vdbeUnbind(p, i);
62913   if( rc==SQLITE_OK ){
62914     sqlite3_mutex_leave(p->db->mutex);
62915   }
62916   return rc;
62917 }
62918 SQLITE_API int sqlite3_bind_text( 
62919   sqlite3_stmt *pStmt, 
62920   int i, 
62921   const char *zData, 
62922   int nData, 
62923   void (*xDel)(void*)
62924 ){
62925   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
62926 }
62927 #ifndef SQLITE_OMIT_UTF16
62928 SQLITE_API int sqlite3_bind_text16(
62929   sqlite3_stmt *pStmt, 
62930   int i, 
62931   const void *zData, 
62932   int nData, 
62933   void (*xDel)(void*)
62934 ){
62935   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
62936 }
62937 #endif /* SQLITE_OMIT_UTF16 */
62938 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
62939   int rc;
62940   switch( pValue->type ){
62941     case SQLITE_INTEGER: {
62942       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
62943       break;
62944     }
62945     case SQLITE_FLOAT: {
62946       rc = sqlite3_bind_double(pStmt, i, pValue->r);
62947       break;
62948     }
62949     case SQLITE_BLOB: {
62950       if( pValue->flags & MEM_Zero ){
62951         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
62952       }else{
62953         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
62954       }
62955       break;
62956     }
62957     case SQLITE_TEXT: {
62958       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
62959                               pValue->enc);
62960       break;
62961     }
62962     default: {
62963       rc = sqlite3_bind_null(pStmt, i);
62964       break;
62965     }
62966   }
62967   return rc;
62968 }
62969 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
62970   int rc;
62971   Vdbe *p = (Vdbe *)pStmt;
62972   rc = vdbeUnbind(p, i);
62973   if( rc==SQLITE_OK ){
62974     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
62975     sqlite3_mutex_leave(p->db->mutex);
62976   }
62977   return rc;
62978 }
62979
62980 /*
62981 ** Return the number of wildcards that can be potentially bound to.
62982 ** This routine is added to support DBD::SQLite.  
62983 */
62984 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
62985   Vdbe *p = (Vdbe*)pStmt;
62986   return p ? p->nVar : 0;
62987 }
62988
62989 /*
62990 ** Return the name of a wildcard parameter.  Return NULL if the index
62991 ** is out of range or if the wildcard is unnamed.
62992 **
62993 ** The result is always UTF-8.
62994 */
62995 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
62996   Vdbe *p = (Vdbe*)pStmt;
62997   if( p==0 || i<1 || i>p->nzVar ){
62998     return 0;
62999   }
63000   return p->azVar[i-1];
63001 }
63002
63003 /*
63004 ** Given a wildcard parameter name, return the index of the variable
63005 ** with that name.  If there is no variable with the given name,
63006 ** return 0.
63007 */
63008 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
63009   int i;
63010   if( p==0 ){
63011     return 0;
63012   }
63013   if( zName ){
63014     for(i=0; i<p->nzVar; i++){
63015       const char *z = p->azVar[i];
63016       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
63017         return i+1;
63018       }
63019     }
63020   }
63021   return 0;
63022 }
63023 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
63024   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
63025 }
63026
63027 /*
63028 ** Transfer all bindings from the first statement over to the second.
63029 */
63030 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63031   Vdbe *pFrom = (Vdbe*)pFromStmt;
63032   Vdbe *pTo = (Vdbe*)pToStmt;
63033   int i;
63034   assert( pTo->db==pFrom->db );
63035   assert( pTo->nVar==pFrom->nVar );
63036   sqlite3_mutex_enter(pTo->db->mutex);
63037   for(i=0; i<pFrom->nVar; i++){
63038     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
63039   }
63040   sqlite3_mutex_leave(pTo->db->mutex);
63041   return SQLITE_OK;
63042 }
63043
63044 #ifndef SQLITE_OMIT_DEPRECATED
63045 /*
63046 ** Deprecated external interface.  Internal/core SQLite code
63047 ** should call sqlite3TransferBindings.
63048 **
63049 ** Is is misuse to call this routine with statements from different
63050 ** database connections.  But as this is a deprecated interface, we
63051 ** will not bother to check for that condition.
63052 **
63053 ** If the two statements contain a different number of bindings, then
63054 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
63055 ** SQLITE_OK is returned.
63056 */
63057 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63058   Vdbe *pFrom = (Vdbe*)pFromStmt;
63059   Vdbe *pTo = (Vdbe*)pToStmt;
63060   if( pFrom->nVar!=pTo->nVar ){
63061     return SQLITE_ERROR;
63062   }
63063   if( pTo->isPrepareV2 && pTo->expmask ){
63064     pTo->expired = 1;
63065   }
63066   if( pFrom->isPrepareV2 && pFrom->expmask ){
63067     pFrom->expired = 1;
63068   }
63069   return sqlite3TransferBindings(pFromStmt, pToStmt);
63070 }
63071 #endif
63072
63073 /*
63074 ** Return the sqlite3* database handle to which the prepared statement given
63075 ** in the argument belongs.  This is the same database handle that was
63076 ** the first argument to the sqlite3_prepare() that was used to create
63077 ** the statement in the first place.
63078 */
63079 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
63080   return pStmt ? ((Vdbe*)pStmt)->db : 0;
63081 }
63082
63083 /*
63084 ** Return true if the prepared statement is guaranteed to not modify the
63085 ** database.
63086 */
63087 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
63088   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
63089 }
63090
63091 /*
63092 ** Return true if the prepared statement is in need of being reset.
63093 */
63094 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
63095   Vdbe *v = (Vdbe*)pStmt;
63096   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
63097 }
63098
63099 /*
63100 ** Return a pointer to the next prepared statement after pStmt associated
63101 ** with database connection pDb.  If pStmt is NULL, return the first
63102 ** prepared statement for the database connection.  Return NULL if there
63103 ** are no more.
63104 */
63105 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
63106   sqlite3_stmt *pNext;
63107   sqlite3_mutex_enter(pDb->mutex);
63108   if( pStmt==0 ){
63109     pNext = (sqlite3_stmt*)pDb->pVdbe;
63110   }else{
63111     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
63112   }
63113   sqlite3_mutex_leave(pDb->mutex);
63114   return pNext;
63115 }
63116
63117 /*
63118 ** Return the value of a status counter for a prepared statement
63119 */
63120 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
63121   Vdbe *pVdbe = (Vdbe*)pStmt;
63122   int v = pVdbe->aCounter[op-1];
63123   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
63124   return v;
63125 }
63126
63127 /************** End of vdbeapi.c *********************************************/
63128 /************** Begin file vdbetrace.c ***************************************/
63129 /*
63130 ** 2009 November 25
63131 **
63132 ** The author disclaims copyright to this source code.  In place of
63133 ** a legal notice, here is a blessing:
63134 **
63135 **    May you do good and not evil.
63136 **    May you find forgiveness for yourself and forgive others.
63137 **    May you share freely, never taking more than you give.
63138 **
63139 *************************************************************************
63140 **
63141 ** This file contains code used to insert the values of host parameters
63142 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
63143 **
63144 ** The Vdbe parse-tree explainer is also found here.
63145 */
63146
63147 #ifndef SQLITE_OMIT_TRACE
63148
63149 /*
63150 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
63151 ** bytes in this text up to but excluding the first character in
63152 ** a host parameter.  If the text contains no host parameters, return
63153 ** the total number of bytes in the text.
63154 */
63155 static int findNextHostParameter(const char *zSql, int *pnToken){
63156   int tokenType;
63157   int nTotal = 0;
63158   int n;
63159
63160   *pnToken = 0;
63161   while( zSql[0] ){
63162     n = sqlite3GetToken((u8*)zSql, &tokenType);
63163     assert( n>0 && tokenType!=TK_ILLEGAL );
63164     if( tokenType==TK_VARIABLE ){
63165       *pnToken = n;
63166       break;
63167     }
63168     nTotal += n;
63169     zSql += n;
63170   }
63171   return nTotal;
63172 }
63173
63174 /*
63175 ** This function returns a pointer to a nul-terminated string in memory
63176 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
63177 ** string contains a copy of zRawSql but with host parameters expanded to 
63178 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
63179 ** then the returned string holds a copy of zRawSql with "-- " prepended
63180 ** to each line of text.
63181 **
63182 ** The calling function is responsible for making sure the memory returned
63183 ** is eventually freed.
63184 **
63185 ** ALGORITHM:  Scan the input string looking for host parameters in any of
63186 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
63187 ** string literals, quoted identifier names, and comments.  For text forms,
63188 ** the host parameter index is found by scanning the perpared
63189 ** statement for the corresponding OP_Variable opcode.  Once the host
63190 ** parameter index is known, locate the value in p->aVar[].  Then render
63191 ** the value as a literal in place of the host parameter name.
63192 */
63193 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
63194   Vdbe *p,                 /* The prepared statement being evaluated */
63195   const char *zRawSql      /* Raw text of the SQL statement */
63196 ){
63197   sqlite3 *db;             /* The database connection */
63198   int idx = 0;             /* Index of a host parameter */
63199   int nextIndex = 1;       /* Index of next ? host parameter */
63200   int n;                   /* Length of a token prefix */
63201   int nToken;              /* Length of the parameter token */
63202   int i;                   /* Loop counter */
63203   Mem *pVar;               /* Value of a host parameter */
63204   StrAccum out;            /* Accumulate the output here */
63205   char zBase[100];         /* Initial working space */
63206
63207   db = p->db;
63208   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
63209                       db->aLimit[SQLITE_LIMIT_LENGTH]);
63210   out.db = db;
63211   if( db->vdbeExecCnt>1 ){
63212     while( *zRawSql ){
63213       const char *zStart = zRawSql;
63214       while( *(zRawSql++)!='\n' && *zRawSql );
63215       sqlite3StrAccumAppend(&out, "-- ", 3);
63216       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
63217     }
63218   }else{
63219     while( zRawSql[0] ){
63220       n = findNextHostParameter(zRawSql, &nToken);
63221       assert( n>0 );
63222       sqlite3StrAccumAppend(&out, zRawSql, n);
63223       zRawSql += n;
63224       assert( zRawSql[0] || nToken==0 );
63225       if( nToken==0 ) break;
63226       if( zRawSql[0]=='?' ){
63227         if( nToken>1 ){
63228           assert( sqlite3Isdigit(zRawSql[1]) );
63229           sqlite3GetInt32(&zRawSql[1], &idx);
63230         }else{
63231           idx = nextIndex;
63232         }
63233       }else{
63234         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
63235         testcase( zRawSql[0]==':' );
63236         testcase( zRawSql[0]=='$' );
63237         testcase( zRawSql[0]=='@' );
63238         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
63239         assert( idx>0 );
63240       }
63241       zRawSql += nToken;
63242       nextIndex = idx + 1;
63243       assert( idx>0 && idx<=p->nVar );
63244       pVar = &p->aVar[idx-1];
63245       if( pVar->flags & MEM_Null ){
63246         sqlite3StrAccumAppend(&out, "NULL", 4);
63247       }else if( pVar->flags & MEM_Int ){
63248         sqlite3XPrintf(&out, "%lld", pVar->u.i);
63249       }else if( pVar->flags & MEM_Real ){
63250         sqlite3XPrintf(&out, "%!.15g", pVar->r);
63251       }else if( pVar->flags & MEM_Str ){
63252 #ifndef SQLITE_OMIT_UTF16
63253         u8 enc = ENC(db);
63254         if( enc!=SQLITE_UTF8 ){
63255           Mem utf8;
63256           memset(&utf8, 0, sizeof(utf8));
63257           utf8.db = db;
63258           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
63259           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
63260           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
63261           sqlite3VdbeMemRelease(&utf8);
63262         }else
63263 #endif
63264         {
63265           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
63266         }
63267       }else if( pVar->flags & MEM_Zero ){
63268         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
63269       }else{
63270         assert( pVar->flags & MEM_Blob );
63271         sqlite3StrAccumAppend(&out, "x'", 2);
63272         for(i=0; i<pVar->n; i++){
63273           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
63274         }
63275         sqlite3StrAccumAppend(&out, "'", 1);
63276       }
63277     }
63278   }
63279   return sqlite3StrAccumFinish(&out);
63280 }
63281
63282 #endif /* #ifndef SQLITE_OMIT_TRACE */
63283
63284 /*****************************************************************************
63285 ** The following code implements the data-structure explaining logic
63286 ** for the Vdbe.
63287 */
63288
63289 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
63290
63291 /*
63292 ** Allocate a new Explain object
63293 */
63294 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
63295   if( pVdbe ){
63296     Explain *p;
63297     sqlite3BeginBenignMalloc();
63298     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
63299     if( p ){
63300       p->pVdbe = pVdbe;
63301       sqlite3_free(pVdbe->pExplain);
63302       pVdbe->pExplain = p;
63303       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
63304                           SQLITE_MAX_LENGTH);
63305       p->str.useMalloc = 2;
63306     }else{
63307       sqlite3EndBenignMalloc();
63308     }
63309   }
63310 }
63311
63312 /*
63313 ** Return true if the Explain ends with a new-line.
63314 */
63315 static int endsWithNL(Explain *p){
63316   return p && p->str.zText && p->str.nChar
63317            && p->str.zText[p->str.nChar-1]=='\n';
63318 }
63319     
63320 /*
63321 ** Append text to the indentation
63322 */
63323 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
63324   Explain *p;
63325   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63326     va_list ap;
63327     if( p->nIndent && endsWithNL(p) ){
63328       int n = p->nIndent;
63329       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
63330       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
63331     }   
63332     va_start(ap, zFormat);
63333     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
63334     va_end(ap);
63335   }
63336 }
63337
63338 /*
63339 ** Append a '\n' if there is not already one.
63340 */
63341 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
63342   Explain *p;
63343   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
63344     sqlite3StrAccumAppend(&p->str, "\n", 1);
63345   }
63346 }
63347
63348 /*
63349 ** Push a new indentation level.  Subsequent lines will be indented
63350 ** so that they begin at the current cursor position.
63351 */
63352 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
63353   Explain *p;
63354   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63355     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
63356       const char *z = p->str.zText;
63357       int i = p->str.nChar-1;
63358       int x;
63359       while( i>=0 && z[i]!='\n' ){ i--; }
63360       x = (p->str.nChar - 1) - i;
63361       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
63362         x = p->aIndent[p->nIndent-1];
63363       }
63364       p->aIndent[p->nIndent] = x;
63365     }
63366     p->nIndent++;
63367   }
63368 }
63369
63370 /*
63371 ** Pop the indentation stack by one level.
63372 */
63373 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
63374   if( p && p->pExplain ) p->pExplain->nIndent--;
63375 }
63376
63377 /*
63378 ** Free the indentation structure
63379 */
63380 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
63381   if( pVdbe && pVdbe->pExplain ){
63382     sqlite3_free(pVdbe->zExplain);
63383     sqlite3ExplainNL(pVdbe);
63384     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
63385     sqlite3_free(pVdbe->pExplain);
63386     pVdbe->pExplain = 0;
63387     sqlite3EndBenignMalloc();
63388   }
63389 }
63390
63391 /*
63392 ** Return the explanation of a virtual machine.
63393 */
63394 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
63395   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
63396 }
63397 #endif /* defined(SQLITE_DEBUG) */
63398
63399 /************** End of vdbetrace.c *******************************************/
63400 /************** Begin file vdbe.c ********************************************/
63401 /*
63402 ** 2001 September 15
63403 **
63404 ** The author disclaims copyright to this source code.  In place of
63405 ** a legal notice, here is a blessing:
63406 **
63407 **    May you do good and not evil.
63408 **    May you find forgiveness for yourself and forgive others.
63409 **    May you share freely, never taking more than you give.
63410 **
63411 *************************************************************************
63412 ** The code in this file implements execution method of the 
63413 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
63414 ** handles housekeeping details such as creating and deleting
63415 ** VDBE instances.  This file is solely interested in executing
63416 ** the VDBE program.
63417 **
63418 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
63419 ** to a VDBE.
63420 **
63421 ** The SQL parser generates a program which is then executed by
63422 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
63423 ** similar in form to assembly language.  The program consists of
63424 ** a linear sequence of operations.  Each operation has an opcode 
63425 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
63426 ** is a null-terminated string.  Operand P5 is an unsigned character.
63427 ** Few opcodes use all 5 operands.
63428 **
63429 ** Computation results are stored on a set of registers numbered beginning
63430 ** with 1 and going up to Vdbe.nMem.  Each register can store
63431 ** either an integer, a null-terminated string, a floating point
63432 ** number, or the SQL "NULL" value.  An implicit conversion from one
63433 ** type to the other occurs as necessary.
63434 ** 
63435 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
63436 ** function which does the work of interpreting a VDBE program.
63437 ** But other routines are also provided to help in building up
63438 ** a program instruction by instruction.
63439 **
63440 ** Various scripts scan this source file in order to generate HTML
63441 ** documentation, headers files, or other derived files.  The formatting
63442 ** of the code in this file is, therefore, important.  See other comments
63443 ** in this file for details.  If in doubt, do not deviate from existing
63444 ** commenting and indentation practices when changing or adding code.
63445 */
63446
63447 /*
63448 ** Invoke this macro on memory cells just prior to changing the
63449 ** value of the cell.  This macro verifies that shallow copies are
63450 ** not misused.
63451 */
63452 #ifdef SQLITE_DEBUG
63453 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
63454 #else
63455 # define memAboutToChange(P,M)
63456 #endif
63457
63458 /*
63459 ** The following global variable is incremented every time a cursor
63460 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
63461 ** procedures use this information to make sure that indices are
63462 ** working correctly.  This variable has no function other than to
63463 ** help verify the correct operation of the library.
63464 */
63465 #ifdef SQLITE_TEST
63466 SQLITE_API int sqlite3_search_count = 0;
63467 #endif
63468
63469 /*
63470 ** When this global variable is positive, it gets decremented once before
63471 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
63472 ** field of the sqlite3 structure is set in order to simulate an interrupt.
63473 **
63474 ** This facility is used for testing purposes only.  It does not function
63475 ** in an ordinary build.
63476 */
63477 #ifdef SQLITE_TEST
63478 SQLITE_API int sqlite3_interrupt_count = 0;
63479 #endif
63480
63481 /*
63482 ** The next global variable is incremented each type the OP_Sort opcode
63483 ** is executed.  The test procedures use this information to make sure that
63484 ** sorting is occurring or not occurring at appropriate times.   This variable
63485 ** has no function other than to help verify the correct operation of the
63486 ** library.
63487 */
63488 #ifdef SQLITE_TEST
63489 SQLITE_API int sqlite3_sort_count = 0;
63490 #endif
63491
63492 /*
63493 ** The next global variable records the size of the largest MEM_Blob
63494 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
63495 ** use this information to make sure that the zero-blob functionality
63496 ** is working correctly.   This variable has no function other than to
63497 ** help verify the correct operation of the library.
63498 */
63499 #ifdef SQLITE_TEST
63500 SQLITE_API int sqlite3_max_blobsize = 0;
63501 static void updateMaxBlobsize(Mem *p){
63502   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
63503     sqlite3_max_blobsize = p->n;
63504   }
63505 }
63506 #endif
63507
63508 /*
63509 ** The next global variable is incremented each type the OP_Found opcode
63510 ** is executed. This is used to test whether or not the foreign key
63511 ** operation implemented using OP_FkIsZero is working. This variable
63512 ** has no function other than to help verify the correct operation of the
63513 ** library.
63514 */
63515 #ifdef SQLITE_TEST
63516 SQLITE_API int sqlite3_found_count = 0;
63517 #endif
63518
63519 /*
63520 ** Test a register to see if it exceeds the current maximum blob size.
63521 ** If it does, record the new maximum blob size.
63522 */
63523 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63524 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
63525 #else
63526 # define UPDATE_MAX_BLOBSIZE(P)
63527 #endif
63528
63529 /*
63530 ** Convert the given register into a string if it isn't one
63531 ** already. Return non-zero if a malloc() fails.
63532 */
63533 #define Stringify(P, enc) \
63534    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63535      { goto no_mem; }
63536
63537 /*
63538 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63539 ** a pointer to a dynamically allocated string where some other entity
63540 ** is responsible for deallocating that string.  Because the register
63541 ** does not control the string, it might be deleted without the register
63542 ** knowing it.
63543 **
63544 ** This routine converts an ephemeral string into a dynamically allocated
63545 ** string that the register itself controls.  In other words, it
63546 ** converts an MEM_Ephem string into an MEM_Dyn string.
63547 */
63548 #define Deephemeralize(P) \
63549    if( ((P)->flags&MEM_Ephem)!=0 \
63550        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63551
63552 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63553 #ifdef SQLITE_OMIT_MERGE_SORT
63554 # define isSorter(x) 0
63555 #else
63556 # define isSorter(x) ((x)->pSorter!=0)
63557 #endif
63558
63559 /*
63560 ** Argument pMem points at a register that will be passed to a
63561 ** user-defined function or returned to the user as the result of a query.
63562 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
63563 ** routines.
63564 */
63565 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63566   int flags = pMem->flags;
63567   if( flags & MEM_Null ){
63568     pMem->type = SQLITE_NULL;
63569   }
63570   else if( flags & MEM_Int ){
63571     pMem->type = SQLITE_INTEGER;
63572   }
63573   else if( flags & MEM_Real ){
63574     pMem->type = SQLITE_FLOAT;
63575   }
63576   else if( flags & MEM_Str ){
63577     pMem->type = SQLITE_TEXT;
63578   }else{
63579     pMem->type = SQLITE_BLOB;
63580   }
63581 }
63582
63583 /*
63584 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
63585 ** if we run out of memory.
63586 */
63587 static VdbeCursor *allocateCursor(
63588   Vdbe *p,              /* The virtual machine */
63589   int iCur,             /* Index of the new VdbeCursor */
63590   int nField,           /* Number of fields in the table or index */
63591   int iDb,              /* Database the cursor belongs to, or -1 */
63592   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
63593 ){
63594   /* Find the memory cell that will be used to store the blob of memory
63595   ** required for this VdbeCursor structure. It is convenient to use a 
63596   ** vdbe memory cell to manage the memory allocation required for a
63597   ** VdbeCursor structure for the following reasons:
63598   **
63599   **   * Sometimes cursor numbers are used for a couple of different
63600   **     purposes in a vdbe program. The different uses might require
63601   **     different sized allocations. Memory cells provide growable
63602   **     allocations.
63603   **
63604   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63605   **     be freed lazily via the sqlite3_release_memory() API. This
63606   **     minimizes the number of malloc calls made by the system.
63607   **
63608   ** Memory cells for cursors are allocated at the top of the address
63609   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63610   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63611   */
63612   Mem *pMem = &p->aMem[p->nMem-iCur];
63613
63614   int nByte;
63615   VdbeCursor *pCx = 0;
63616   nByte = 
63617       ROUND8(sizeof(VdbeCursor)) + 
63618       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
63619       2*nField*sizeof(u32);
63620
63621   assert( iCur<p->nCursor );
63622   if( p->apCsr[iCur] ){
63623     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63624     p->apCsr[iCur] = 0;
63625   }
63626   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63627     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63628     memset(pCx, 0, sizeof(VdbeCursor));
63629     pCx->iDb = iDb;
63630     pCx->nField = nField;
63631     if( nField ){
63632       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63633     }
63634     if( isBtreeCursor ){
63635       pCx->pCursor = (BtCursor*)
63636           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63637       sqlite3BtreeCursorZero(pCx->pCursor);
63638     }
63639   }
63640   return pCx;
63641 }
63642
63643 /*
63644 ** Try to convert a value into a numeric representation if we can
63645 ** do so without loss of information.  In other words, if the string
63646 ** looks like a number, convert it into a number.  If it does not
63647 ** look like a number, leave it alone.
63648 */
63649 static void applyNumericAffinity(Mem *pRec){
63650   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63651     double rValue;
63652     i64 iValue;
63653     u8 enc = pRec->enc;
63654     if( (pRec->flags&MEM_Str)==0 ) return;
63655     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63656     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63657       pRec->u.i = iValue;
63658       pRec->flags |= MEM_Int;
63659     }else{
63660       pRec->r = rValue;
63661       pRec->flags |= MEM_Real;
63662     }
63663   }
63664 }
63665
63666 /*
63667 ** Processing is determine by the affinity parameter:
63668 **
63669 ** SQLITE_AFF_INTEGER:
63670 ** SQLITE_AFF_REAL:
63671 ** SQLITE_AFF_NUMERIC:
63672 **    Try to convert pRec to an integer representation or a 
63673 **    floating-point representation if an integer representation
63674 **    is not possible.  Note that the integer representation is
63675 **    always preferred, even if the affinity is REAL, because
63676 **    an integer representation is more space efficient on disk.
63677 **
63678 ** SQLITE_AFF_TEXT:
63679 **    Convert pRec to a text representation.
63680 **
63681 ** SQLITE_AFF_NONE:
63682 **    No-op.  pRec is unchanged.
63683 */
63684 static void applyAffinity(
63685   Mem *pRec,          /* The value to apply affinity to */
63686   char affinity,      /* The affinity to be applied */
63687   u8 enc              /* Use this text encoding */
63688 ){
63689   if( affinity==SQLITE_AFF_TEXT ){
63690     /* Only attempt the conversion to TEXT if there is an integer or real
63691     ** representation (blob and NULL do not get converted) but no string
63692     ** representation.
63693     */
63694     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63695       sqlite3VdbeMemStringify(pRec, enc);
63696     }
63697     pRec->flags &= ~(MEM_Real|MEM_Int);
63698   }else if( affinity!=SQLITE_AFF_NONE ){
63699     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63700              || affinity==SQLITE_AFF_NUMERIC );
63701     applyNumericAffinity(pRec);
63702     if( pRec->flags & MEM_Real ){
63703       sqlite3VdbeIntegerAffinity(pRec);
63704     }
63705   }
63706 }
63707
63708 /*
63709 ** Try to convert the type of a function argument or a result column
63710 ** into a numeric representation.  Use either INTEGER or REAL whichever
63711 ** is appropriate.  But only do the conversion if it is possible without
63712 ** loss of information and return the revised type of the argument.
63713 */
63714 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63715   Mem *pMem = (Mem*)pVal;
63716   if( pMem->type==SQLITE_TEXT ){
63717     applyNumericAffinity(pMem);
63718     sqlite3VdbeMemStoreType(pMem);
63719   }
63720   return pMem->type;
63721 }
63722
63723 /*
63724 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
63725 ** not the internal Mem* type.
63726 */
63727 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63728   sqlite3_value *pVal, 
63729   u8 affinity, 
63730   u8 enc
63731 ){
63732   applyAffinity((Mem *)pVal, affinity, enc);
63733 }
63734
63735 #ifdef SQLITE_DEBUG
63736 /*
63737 ** Write a nice string representation of the contents of cell pMem
63738 ** into buffer zBuf, length nBuf.
63739 */
63740 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63741   char *zCsr = zBuf;
63742   int f = pMem->flags;
63743
63744   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63745
63746   if( f&MEM_Blob ){
63747     int i;
63748     char c;
63749     if( f & MEM_Dyn ){
63750       c = 'z';
63751       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63752     }else if( f & MEM_Static ){
63753       c = 't';
63754       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63755     }else if( f & MEM_Ephem ){
63756       c = 'e';
63757       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63758     }else{
63759       c = 's';
63760     }
63761
63762     sqlite3_snprintf(100, zCsr, "%c", c);
63763     zCsr += sqlite3Strlen30(zCsr);
63764     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63765     zCsr += sqlite3Strlen30(zCsr);
63766     for(i=0; i<16 && i<pMem->n; i++){
63767       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63768       zCsr += sqlite3Strlen30(zCsr);
63769     }
63770     for(i=0; i<16 && i<pMem->n; i++){
63771       char z = pMem->z[i];
63772       if( z<32 || z>126 ) *zCsr++ = '.';
63773       else *zCsr++ = z;
63774     }
63775
63776     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63777     zCsr += sqlite3Strlen30(zCsr);
63778     if( f & MEM_Zero ){
63779       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63780       zCsr += sqlite3Strlen30(zCsr);
63781     }
63782     *zCsr = '\0';
63783   }else if( f & MEM_Str ){
63784     int j, k;
63785     zBuf[0] = ' ';
63786     if( f & MEM_Dyn ){
63787       zBuf[1] = 'z';
63788       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63789     }else if( f & MEM_Static ){
63790       zBuf[1] = 't';
63791       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63792     }else if( f & MEM_Ephem ){
63793       zBuf[1] = 'e';
63794       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63795     }else{
63796       zBuf[1] = 's';
63797     }
63798     k = 2;
63799     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63800     k += sqlite3Strlen30(&zBuf[k]);
63801     zBuf[k++] = '[';
63802     for(j=0; j<15 && j<pMem->n; j++){
63803       u8 c = pMem->z[j];
63804       if( c>=0x20 && c<0x7f ){
63805         zBuf[k++] = c;
63806       }else{
63807         zBuf[k++] = '.';
63808       }
63809     }
63810     zBuf[k++] = ']';
63811     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63812     k += sqlite3Strlen30(&zBuf[k]);
63813     zBuf[k++] = 0;
63814   }
63815 }
63816 #endif
63817
63818 #ifdef SQLITE_DEBUG
63819 /*
63820 ** Print the value of a register for tracing purposes:
63821 */
63822 static void memTracePrint(FILE *out, Mem *p){
63823   if( p->flags & MEM_Invalid ){
63824     fprintf(out, " undefined");
63825   }else if( p->flags & MEM_Null ){
63826     fprintf(out, " NULL");
63827   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63828     fprintf(out, " si:%lld", p->u.i);
63829   }else if( p->flags & MEM_Int ){
63830     fprintf(out, " i:%lld", p->u.i);
63831 #ifndef SQLITE_OMIT_FLOATING_POINT
63832   }else if( p->flags & MEM_Real ){
63833     fprintf(out, " r:%g", p->r);
63834 #endif
63835   }else if( p->flags & MEM_RowSet ){
63836     fprintf(out, " (rowset)");
63837   }else{
63838     char zBuf[200];
63839     sqlite3VdbeMemPrettyPrint(p, zBuf);
63840     fprintf(out, " ");
63841     fprintf(out, "%s", zBuf);
63842   }
63843 }
63844 static void registerTrace(FILE *out, int iReg, Mem *p){
63845   fprintf(out, "REG[%d] = ", iReg);
63846   memTracePrint(out, p);
63847   fprintf(out, "\n");
63848 }
63849 #endif
63850
63851 #ifdef SQLITE_DEBUG
63852 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
63853 #else
63854 #  define REGISTER_TRACE(R,M)
63855 #endif
63856
63857
63858 #ifdef VDBE_PROFILE
63859
63860 /* 
63861 ** hwtime.h contains inline assembler code for implementing 
63862 ** high-performance timing routines.
63863 */
63864 /************** Include hwtime.h in the middle of vdbe.c *********************/
63865 /************** Begin file hwtime.h ******************************************/
63866 /*
63867 ** 2008 May 27
63868 **
63869 ** The author disclaims copyright to this source code.  In place of
63870 ** a legal notice, here is a blessing:
63871 **
63872 **    May you do good and not evil.
63873 **    May you find forgiveness for yourself and forgive others.
63874 **    May you share freely, never taking more than you give.
63875 **
63876 ******************************************************************************
63877 **
63878 ** This file contains inline asm code for retrieving "high-performance"
63879 ** counters for x86 class CPUs.
63880 */
63881 #ifndef _HWTIME_H_
63882 #define _HWTIME_H_
63883
63884 /*
63885 ** The following routine only works on pentium-class (or newer) processors.
63886 ** It uses the RDTSC opcode to read the cycle count value out of the
63887 ** processor and returns that value.  This can be used for high-res
63888 ** profiling.
63889 */
63890 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
63891       (defined(i386) || defined(__i386__) || defined(_M_IX86))
63892
63893   #if defined(__GNUC__)
63894
63895   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63896      unsigned int lo, hi;
63897      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
63898      return (sqlite_uint64)hi << 32 | lo;
63899   }
63900
63901   #elif defined(_MSC_VER)
63902
63903   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
63904      __asm {
63905         rdtsc
63906         ret       ; return value at EDX:EAX
63907      }
63908   }
63909
63910   #endif
63911
63912 #elif (defined(__GNUC__) && defined(__x86_64__))
63913
63914   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63915       unsigned long val;
63916       __asm__ __volatile__ ("rdtsc" : "=A" (val));
63917       return val;
63918   }
63919  
63920 #elif (defined(__GNUC__) && defined(__ppc__))
63921
63922   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63923       unsigned long long retval;
63924       unsigned long junk;
63925       __asm__ __volatile__ ("\n\
63926           1:      mftbu   %1\n\
63927                   mftb    %L0\n\
63928                   mftbu   %0\n\
63929                   cmpw    %0,%1\n\
63930                   bne     1b"
63931                   : "=r" (retval), "=r" (junk));
63932       return retval;
63933   }
63934
63935 #else
63936
63937   #error Need implementation of sqlite3Hwtime() for your platform.
63938
63939   /*
63940   ** To compile without implementing sqlite3Hwtime() for your platform,
63941   ** you can remove the above #error and use the following
63942   ** stub function.  You will lose timing support for many
63943   ** of the debugging and testing utilities, but it should at
63944   ** least compile and run.
63945   */
63946 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
63947
63948 #endif
63949
63950 #endif /* !defined(_HWTIME_H_) */
63951
63952 /************** End of hwtime.h **********************************************/
63953 /************** Continuing where we left off in vdbe.c ***********************/
63954
63955 #endif
63956
63957 /*
63958 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
63959 ** sqlite3_interrupt() routine has been called.  If it has been, then
63960 ** processing of the VDBE program is interrupted.
63961 **
63962 ** This macro added to every instruction that does a jump in order to
63963 ** implement a loop.  This test used to be on every single instruction,
63964 ** but that meant we more testing than we needed.  By only testing the
63965 ** flag on jump instructions, we get a (small) speed improvement.
63966 */
63967 #define CHECK_FOR_INTERRUPT \
63968    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
63969
63970
63971 #ifndef NDEBUG
63972 /*
63973 ** This function is only called from within an assert() expression. It
63974 ** checks that the sqlite3.nTransaction variable is correctly set to
63975 ** the number of non-transaction savepoints currently in the 
63976 ** linked list starting at sqlite3.pSavepoint.
63977 ** 
63978 ** Usage:
63979 **
63980 **     assert( checkSavepointCount(db) );
63981 */
63982 static int checkSavepointCount(sqlite3 *db){
63983   int n = 0;
63984   Savepoint *p;
63985   for(p=db->pSavepoint; p; p=p->pNext) n++;
63986   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
63987   return 1;
63988 }
63989 #endif
63990
63991 /*
63992 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
63993 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
63994 ** in memory obtained from sqlite3DbMalloc).
63995 */
63996 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
63997   sqlite3 *db = p->db;
63998   sqlite3DbFree(db, p->zErrMsg);
63999   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64000   sqlite3_free(pVtab->zErrMsg);
64001   pVtab->zErrMsg = 0;
64002 }
64003
64004
64005 /*
64006 ** Execute as much of a VDBE program as we can then return.
64007 **
64008 ** sqlite3VdbeMakeReady() must be called before this routine in order to
64009 ** close the program with a final OP_Halt and to set up the callbacks
64010 ** and the error message pointer.
64011 **
64012 ** Whenever a row or result data is available, this routine will either
64013 ** invoke the result callback (if there is one) or return with
64014 ** SQLITE_ROW.
64015 **
64016 ** If an attempt is made to open a locked database, then this routine
64017 ** will either invoke the busy callback (if there is one) or it will
64018 ** return SQLITE_BUSY.
64019 **
64020 ** If an error occurs, an error message is written to memory obtained
64021 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
64022 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
64023 **
64024 ** If the callback ever returns non-zero, then the program exits
64025 ** immediately.  There will be no error message but the p->rc field is
64026 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
64027 **
64028 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
64029 ** routine to return SQLITE_ERROR.
64030 **
64031 ** Other fatal errors return SQLITE_ERROR.
64032 **
64033 ** After this routine has finished, sqlite3VdbeFinalize() should be
64034 ** used to clean up the mess that was left behind.
64035 */
64036 SQLITE_PRIVATE int sqlite3VdbeExec(
64037   Vdbe *p                    /* The VDBE */
64038 ){
64039   int pc=0;                  /* The program counter */
64040   Op *aOp = p->aOp;          /* Copy of p->aOp */
64041   Op *pOp;                   /* Current operation */
64042   int rc = SQLITE_OK;        /* Value to return */
64043   sqlite3 *db = p->db;       /* The database */
64044   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64045   u8 encoding = ENC(db);     /* The database encoding */
64046 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64047   int checkProgress;         /* True if progress callbacks are enabled */
64048   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64049 #endif
64050   Mem *aMem = p->aMem;       /* Copy of p->aMem */
64051   Mem *pIn1 = 0;             /* 1st input operand */
64052   Mem *pIn2 = 0;             /* 2nd input operand */
64053   Mem *pIn3 = 0;             /* 3rd input operand */
64054   Mem *pOut = 0;             /* Output operand */
64055   int iCompare = 0;          /* Result of last OP_Compare operation */
64056   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64057   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64058 #ifdef VDBE_PROFILE
64059   u64 start;                 /* CPU clock count at start of opcode */
64060   int origPc;                /* Program counter at start of opcode */
64061 #endif
64062   /********************************************************************
64063   ** Automatically generated code
64064   **
64065   ** The following union is automatically generated by the
64066   ** vdbe-compress.tcl script.  The purpose of this union is to
64067   ** reduce the amount of stack space required by this function.
64068   ** See comments in the vdbe-compress.tcl script for details.
64069   */
64070   union vdbeExecUnion {
64071     struct OP_Yield_stack_vars {
64072       int pcDest;
64073     } aa;
64074     struct OP_Null_stack_vars {
64075       int cnt;
64076       u16 nullFlag;
64077     } ab;
64078     struct OP_Variable_stack_vars {
64079       Mem *pVar;       /* Value being transferred */
64080     } ac;
64081     struct OP_Move_stack_vars {
64082       char *zMalloc;   /* Holding variable for allocated memory */
64083       int n;           /* Number of registers left to copy */
64084       int p1;          /* Register to copy from */
64085       int p2;          /* Register to copy to */
64086     } ad;
64087     struct OP_Copy_stack_vars {
64088       int n;
64089     } ae;
64090     struct OP_ResultRow_stack_vars {
64091       Mem *pMem;
64092       int i;
64093     } af;
64094     struct OP_Concat_stack_vars {
64095       i64 nByte;
64096     } ag;
64097     struct OP_Remainder_stack_vars {
64098       char bIntint;   /* Started out as two integer operands */
64099       int flags;      /* Combined MEM_* flags from both inputs */
64100       i64 iA;         /* Integer value of left operand */
64101       i64 iB;         /* Integer value of right operand */
64102       double rA;      /* Real value of left operand */
64103       double rB;      /* Real value of right operand */
64104     } ah;
64105     struct OP_Function_stack_vars {
64106       int i;
64107       Mem *pArg;
64108       sqlite3_context ctx;
64109       sqlite3_value **apVal;
64110       int n;
64111     } ai;
64112     struct OP_ShiftRight_stack_vars {
64113       i64 iA;
64114       u64 uA;
64115       i64 iB;
64116       u8 op;
64117     } aj;
64118     struct OP_Ge_stack_vars {
64119       int res;            /* Result of the comparison of pIn1 against pIn3 */
64120       char affinity;      /* Affinity to use for comparison */
64121       u16 flags1;         /* Copy of initial value of pIn1->flags */
64122       u16 flags3;         /* Copy of initial value of pIn3->flags */
64123     } ak;
64124     struct OP_Compare_stack_vars {
64125       int n;
64126       int i;
64127       int p1;
64128       int p2;
64129       const KeyInfo *pKeyInfo;
64130       int idx;
64131       CollSeq *pColl;    /* Collating sequence to use on this term */
64132       int bRev;          /* True for DESCENDING sort order */
64133     } al;
64134     struct OP_Or_stack_vars {
64135       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64136       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64137     } am;
64138     struct OP_IfNot_stack_vars {
64139       int c;
64140     } an;
64141     struct OP_Column_stack_vars {
64142       u32 payloadSize;   /* Number of bytes in the record */
64143       i64 payloadSize64; /* Number of bytes in the record */
64144       int p1;            /* P1 value of the opcode */
64145       int p2;            /* column number to retrieve */
64146       VdbeCursor *pC;    /* The VDBE cursor */
64147       char *zRec;        /* Pointer to complete record-data */
64148       BtCursor *pCrsr;   /* The BTree cursor */
64149       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64150       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64151       int nField;        /* number of fields in the record */
64152       int len;           /* The length of the serialized data for the column */
64153       int i;             /* Loop counter */
64154       char *zData;       /* Part of the record being decoded */
64155       Mem *pDest;        /* Where to write the extracted value */
64156       Mem sMem;          /* For storing the record being decoded */
64157       u8 *zIdx;          /* Index into header */
64158       u8 *zEndHdr;       /* Pointer to first byte after the header */
64159       u32 offset;        /* Offset into the data */
64160       u32 szField;       /* Number of bytes in the content of a field */
64161       int szHdr;         /* Size of the header size field at start of record */
64162       int avail;         /* Number of bytes of available data */
64163       u32 t;             /* A type code from the record header */
64164       Mem *pReg;         /* PseudoTable input register */
64165     } ao;
64166     struct OP_Affinity_stack_vars {
64167       const char *zAffinity;   /* The affinity to be applied */
64168       char cAff;               /* A single character of affinity */
64169     } ap;
64170     struct OP_MakeRecord_stack_vars {
64171       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64172       Mem *pRec;             /* The new record */
64173       u64 nData;             /* Number of bytes of data space */
64174       int nHdr;              /* Number of bytes of header space */
64175       i64 nByte;             /* Data space required for this record */
64176       int nZero;             /* Number of zero bytes at the end of the record */
64177       int nVarint;           /* Number of bytes in a varint */
64178       u32 serial_type;       /* Type field */
64179       Mem *pData0;           /* First field to be combined into the record */
64180       Mem *pLast;            /* Last field of the record */
64181       int nField;            /* Number of fields in the record */
64182       char *zAffinity;       /* The affinity string for the record */
64183       int file_format;       /* File format to use for encoding */
64184       int i;                 /* Space used in zNewRecord[] */
64185       int len;               /* Length of a field */
64186     } aq;
64187     struct OP_Count_stack_vars {
64188       i64 nEntry;
64189       BtCursor *pCrsr;
64190     } ar;
64191     struct OP_Savepoint_stack_vars {
64192       int p1;                         /* Value of P1 operand */
64193       char *zName;                    /* Name of savepoint */
64194       int nName;
64195       Savepoint *pNew;
64196       Savepoint *pSavepoint;
64197       Savepoint *pTmp;
64198       int iSavepoint;
64199       int ii;
64200     } as;
64201     struct OP_AutoCommit_stack_vars {
64202       int desiredAutoCommit;
64203       int iRollback;
64204       int turnOnAC;
64205     } at;
64206     struct OP_Transaction_stack_vars {
64207       Btree *pBt;
64208     } au;
64209     struct OP_ReadCookie_stack_vars {
64210       int iMeta;
64211       int iDb;
64212       int iCookie;
64213     } av;
64214     struct OP_SetCookie_stack_vars {
64215       Db *pDb;
64216     } aw;
64217     struct OP_VerifyCookie_stack_vars {
64218       int iMeta;
64219       int iGen;
64220       Btree *pBt;
64221     } ax;
64222     struct OP_OpenWrite_stack_vars {
64223       int nField;
64224       KeyInfo *pKeyInfo;
64225       int p2;
64226       int iDb;
64227       int wrFlag;
64228       Btree *pX;
64229       VdbeCursor *pCur;
64230       Db *pDb;
64231     } ay;
64232     struct OP_OpenEphemeral_stack_vars {
64233       VdbeCursor *pCx;
64234     } az;
64235     struct OP_SorterOpen_stack_vars {
64236       VdbeCursor *pCx;
64237     } ba;
64238     struct OP_OpenPseudo_stack_vars {
64239       VdbeCursor *pCx;
64240     } bb;
64241     struct OP_SeekGt_stack_vars {
64242       int res;
64243       int oc;
64244       VdbeCursor *pC;
64245       UnpackedRecord r;
64246       int nField;
64247       i64 iKey;      /* The rowid we are to seek to */
64248     } bc;
64249     struct OP_Seek_stack_vars {
64250       VdbeCursor *pC;
64251     } bd;
64252     struct OP_Found_stack_vars {
64253       int alreadyExists;
64254       VdbeCursor *pC;
64255       int res;
64256       char *pFree;
64257       UnpackedRecord *pIdxKey;
64258       UnpackedRecord r;
64259       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
64260     } be;
64261     struct OP_IsUnique_stack_vars {
64262       u16 ii;
64263       VdbeCursor *pCx;
64264       BtCursor *pCrsr;
64265       u16 nField;
64266       Mem *aMx;
64267       UnpackedRecord r;                  /* B-Tree index search key */
64268       i64 R;                             /* Rowid stored in register P3 */
64269     } bf;
64270     struct OP_NotExists_stack_vars {
64271       VdbeCursor *pC;
64272       BtCursor *pCrsr;
64273       int res;
64274       u64 iKey;
64275     } bg;
64276     struct OP_NewRowid_stack_vars {
64277       i64 v;                 /* The new rowid */
64278       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
64279       int res;               /* Result of an sqlite3BtreeLast() */
64280       int cnt;               /* Counter to limit the number of searches */
64281       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
64282       VdbeFrame *pFrame;     /* Root frame of VDBE */
64283     } bh;
64284     struct OP_InsertInt_stack_vars {
64285       Mem *pData;       /* MEM cell holding data for the record to be inserted */
64286       Mem *pKey;        /* MEM cell holding key  for the record */
64287       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
64288       VdbeCursor *pC;   /* Cursor to table into which insert is written */
64289       int nZero;        /* Number of zero-bytes to append */
64290       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
64291       const char *zDb;  /* database name - used by the update hook */
64292       const char *zTbl; /* Table name - used by the opdate hook */
64293       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
64294     } bi;
64295     struct OP_Delete_stack_vars {
64296       i64 iKey;
64297       VdbeCursor *pC;
64298     } bj;
64299     struct OP_SorterCompare_stack_vars {
64300       VdbeCursor *pC;
64301       int res;
64302     } bk;
64303     struct OP_SorterData_stack_vars {
64304       VdbeCursor *pC;
64305     } bl;
64306     struct OP_RowData_stack_vars {
64307       VdbeCursor *pC;
64308       BtCursor *pCrsr;
64309       u32 n;
64310       i64 n64;
64311     } bm;
64312     struct OP_Rowid_stack_vars {
64313       VdbeCursor *pC;
64314       i64 v;
64315       sqlite3_vtab *pVtab;
64316       const sqlite3_module *pModule;
64317     } bn;
64318     struct OP_NullRow_stack_vars {
64319       VdbeCursor *pC;
64320     } bo;
64321     struct OP_Last_stack_vars {
64322       VdbeCursor *pC;
64323       BtCursor *pCrsr;
64324       int res;
64325     } bp;
64326     struct OP_Rewind_stack_vars {
64327       VdbeCursor *pC;
64328       BtCursor *pCrsr;
64329       int res;
64330     } bq;
64331     struct OP_Next_stack_vars {
64332       VdbeCursor *pC;
64333       int res;
64334     } br;
64335     struct OP_IdxInsert_stack_vars {
64336       VdbeCursor *pC;
64337       BtCursor *pCrsr;
64338       int nKey;
64339       const char *zKey;
64340     } bs;
64341     struct OP_IdxDelete_stack_vars {
64342       VdbeCursor *pC;
64343       BtCursor *pCrsr;
64344       int res;
64345       UnpackedRecord r;
64346     } bt;
64347     struct OP_IdxRowid_stack_vars {
64348       BtCursor *pCrsr;
64349       VdbeCursor *pC;
64350       i64 rowid;
64351     } bu;
64352     struct OP_IdxGE_stack_vars {
64353       VdbeCursor *pC;
64354       int res;
64355       UnpackedRecord r;
64356     } bv;
64357     struct OP_Destroy_stack_vars {
64358       int iMoved;
64359       int iCnt;
64360       Vdbe *pVdbe;
64361       int iDb;
64362     } bw;
64363     struct OP_Clear_stack_vars {
64364       int nChange;
64365     } bx;
64366     struct OP_CreateTable_stack_vars {
64367       int pgno;
64368       int flags;
64369       Db *pDb;
64370     } by;
64371     struct OP_ParseSchema_stack_vars {
64372       int iDb;
64373       const char *zMaster;
64374       char *zSql;
64375       InitData initData;
64376     } bz;
64377     struct OP_IntegrityCk_stack_vars {
64378       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
64379       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
64380       int j;          /* Loop counter */
64381       int nErr;       /* Number of errors reported */
64382       char *z;        /* Text of the error report */
64383       Mem *pnErr;     /* Register keeping track of errors remaining */
64384     } ca;
64385     struct OP_RowSetRead_stack_vars {
64386       i64 val;
64387     } cb;
64388     struct OP_RowSetTest_stack_vars {
64389       int iSet;
64390       int exists;
64391     } cc;
64392     struct OP_Program_stack_vars {
64393       int nMem;               /* Number of memory registers for sub-program */
64394       int nByte;              /* Bytes of runtime space required for sub-program */
64395       Mem *pRt;               /* Register to allocate runtime space */
64396       Mem *pMem;              /* Used to iterate through memory cells */
64397       Mem *pEnd;              /* Last memory cell in new array */
64398       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64399       SubProgram *pProgram;   /* Sub-program to execute */
64400       void *t;                /* Token identifying trigger */
64401     } cd;
64402     struct OP_Param_stack_vars {
64403       VdbeFrame *pFrame;
64404       Mem *pIn;
64405     } ce;
64406     struct OP_MemMax_stack_vars {
64407       Mem *pIn1;
64408       VdbeFrame *pFrame;
64409     } cf;
64410     struct OP_AggStep_stack_vars {
64411       int n;
64412       int i;
64413       Mem *pMem;
64414       Mem *pRec;
64415       sqlite3_context ctx;
64416       sqlite3_value **apVal;
64417     } cg;
64418     struct OP_AggFinal_stack_vars {
64419       Mem *pMem;
64420     } ch;
64421     struct OP_Checkpoint_stack_vars {
64422       int i;                          /* Loop counter */
64423       int aRes[3];                    /* Results */
64424       Mem *pMem;                      /* Write results here */
64425     } ci;
64426     struct OP_JournalMode_stack_vars {
64427       Btree *pBt;                     /* Btree to change journal mode of */
64428       Pager *pPager;                  /* Pager associated with pBt */
64429       int eNew;                       /* New journal mode */
64430       int eOld;                       /* The old journal mode */
64431 #ifndef SQLITE_OMIT_WAL
64432       const char *zFilename;          /* Name of database file for pPager */
64433 #endif
64434     } cj;
64435     struct OP_IncrVacuum_stack_vars {
64436       Btree *pBt;
64437     } ck;
64438     struct OP_VBegin_stack_vars {
64439       VTable *pVTab;
64440     } cl;
64441     struct OP_VOpen_stack_vars {
64442       VdbeCursor *pCur;
64443       sqlite3_vtab_cursor *pVtabCursor;
64444       sqlite3_vtab *pVtab;
64445       sqlite3_module *pModule;
64446     } cm;
64447     struct OP_VFilter_stack_vars {
64448       int nArg;
64449       int iQuery;
64450       const sqlite3_module *pModule;
64451       Mem *pQuery;
64452       Mem *pArgc;
64453       sqlite3_vtab_cursor *pVtabCursor;
64454       sqlite3_vtab *pVtab;
64455       VdbeCursor *pCur;
64456       int res;
64457       int i;
64458       Mem **apArg;
64459     } cn;
64460     struct OP_VColumn_stack_vars {
64461       sqlite3_vtab *pVtab;
64462       const sqlite3_module *pModule;
64463       Mem *pDest;
64464       sqlite3_context sContext;
64465     } co;
64466     struct OP_VNext_stack_vars {
64467       sqlite3_vtab *pVtab;
64468       const sqlite3_module *pModule;
64469       int res;
64470       VdbeCursor *pCur;
64471     } cp;
64472     struct OP_VRename_stack_vars {
64473       sqlite3_vtab *pVtab;
64474       Mem *pName;
64475     } cq;
64476     struct OP_VUpdate_stack_vars {
64477       sqlite3_vtab *pVtab;
64478       sqlite3_module *pModule;
64479       int nArg;
64480       int i;
64481       sqlite_int64 rowid;
64482       Mem **apArg;
64483       Mem *pX;
64484     } cr;
64485     struct OP_Trace_stack_vars {
64486       char *zTrace;
64487       char *z;
64488     } cs;
64489   } u;
64490   /* End automatically generated code
64491   ********************************************************************/
64492
64493   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
64494   sqlite3VdbeEnter(p);
64495   if( p->rc==SQLITE_NOMEM ){
64496     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64497     ** sqlite3_column_text16() failed.  */
64498     goto no_mem;
64499   }
64500   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
64501   p->rc = SQLITE_OK;
64502   assert( p->explain==0 );
64503   p->pResultSet = 0;
64504   db->busyHandler.nBusy = 0;
64505   CHECK_FOR_INTERRUPT;
64506   sqlite3VdbeIOTraceSql(p);
64507 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64508   checkProgress = db->xProgress!=0;
64509 #endif
64510 #ifdef SQLITE_DEBUG
64511   sqlite3BeginBenignMalloc();
64512   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64513     int i;
64514     printf("VDBE Program Listing:\n");
64515     sqlite3VdbePrintSql(p);
64516     for(i=0; i<p->nOp; i++){
64517       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64518     }
64519   }
64520   sqlite3EndBenignMalloc();
64521 #endif
64522   for(pc=p->pc; rc==SQLITE_OK; pc++){
64523     assert( pc>=0 && pc<p->nOp );
64524     if( db->mallocFailed ) goto no_mem;
64525 #ifdef VDBE_PROFILE
64526     origPc = pc;
64527     start = sqlite3Hwtime();
64528 #endif
64529     pOp = &aOp[pc];
64530
64531     /* Only allow tracing if SQLITE_DEBUG is defined.
64532     */
64533 #ifdef SQLITE_DEBUG
64534     if( p->trace ){
64535       if( pc==0 ){
64536         printf("VDBE Execution Trace:\n");
64537         sqlite3VdbePrintSql(p);
64538       }
64539       sqlite3VdbePrintOp(p->trace, pc, pOp);
64540     }
64541 #endif
64542       
64543
64544     /* Check to see if we need to simulate an interrupt.  This only happens
64545     ** if we have a special test build.
64546     */
64547 #ifdef SQLITE_TEST
64548     if( sqlite3_interrupt_count>0 ){
64549       sqlite3_interrupt_count--;
64550       if( sqlite3_interrupt_count==0 ){
64551         sqlite3_interrupt(db);
64552       }
64553     }
64554 #endif
64555
64556 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64557     /* Call the progress callback if it is configured and the required number
64558     ** of VDBE ops have been executed (either since this invocation of
64559     ** sqlite3VdbeExec() or since last time the progress callback was called).
64560     ** If the progress callback returns non-zero, exit the virtual machine with
64561     ** a return code SQLITE_ABORT.
64562     */
64563     if( checkProgress ){
64564       if( db->nProgressOps==nProgressOps ){
64565         int prc;
64566         prc = db->xProgress(db->pProgressArg);
64567         if( prc!=0 ){
64568           rc = SQLITE_INTERRUPT;
64569           goto vdbe_error_halt;
64570         }
64571         nProgressOps = 0;
64572       }
64573       nProgressOps++;
64574     }
64575 #endif
64576
64577     /* On any opcode with the "out2-prerelease" tag, free any
64578     ** external allocations out of mem[p2] and set mem[p2] to be
64579     ** an undefined integer.  Opcodes will either fill in the integer
64580     ** value or convert mem[p2] to a different type.
64581     */
64582     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64583     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64584       assert( pOp->p2>0 );
64585       assert( pOp->p2<=p->nMem );
64586       pOut = &aMem[pOp->p2];
64587       memAboutToChange(p, pOut);
64588       VdbeMemRelease(pOut);
64589       pOut->flags = MEM_Int;
64590     }
64591
64592     /* Sanity checking on other operands */
64593 #ifdef SQLITE_DEBUG
64594     if( (pOp->opflags & OPFLG_IN1)!=0 ){
64595       assert( pOp->p1>0 );
64596       assert( pOp->p1<=p->nMem );
64597       assert( memIsValid(&aMem[pOp->p1]) );
64598       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64599     }
64600     if( (pOp->opflags & OPFLG_IN2)!=0 ){
64601       assert( pOp->p2>0 );
64602       assert( pOp->p2<=p->nMem );
64603       assert( memIsValid(&aMem[pOp->p2]) );
64604       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64605     }
64606     if( (pOp->opflags & OPFLG_IN3)!=0 ){
64607       assert( pOp->p3>0 );
64608       assert( pOp->p3<=p->nMem );
64609       assert( memIsValid(&aMem[pOp->p3]) );
64610       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64611     }
64612     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64613       assert( pOp->p2>0 );
64614       assert( pOp->p2<=p->nMem );
64615       memAboutToChange(p, &aMem[pOp->p2]);
64616     }
64617     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64618       assert( pOp->p3>0 );
64619       assert( pOp->p3<=p->nMem );
64620       memAboutToChange(p, &aMem[pOp->p3]);
64621     }
64622 #endif
64623   
64624     switch( pOp->opcode ){
64625
64626 /*****************************************************************************
64627 ** What follows is a massive switch statement where each case implements a
64628 ** separate instruction in the virtual machine.  If we follow the usual
64629 ** indentation conventions, each case should be indented by 6 spaces.  But
64630 ** that is a lot of wasted space on the left margin.  So the code within
64631 ** the switch statement will break with convention and be flush-left. Another
64632 ** big comment (similar to this one) will mark the point in the code where
64633 ** we transition back to normal indentation.
64634 **
64635 ** The formatting of each case is important.  The makefile for SQLite
64636 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64637 ** file looking for lines that begin with "case OP_".  The opcodes.h files
64638 ** will be filled with #defines that give unique integer values to each
64639 ** opcode and the opcodes.c file is filled with an array of strings where
64640 ** each string is the symbolic name for the corresponding opcode.  If the
64641 ** case statement is followed by a comment of the form "/# same as ... #/"
64642 ** that comment is used to determine the particular value of the opcode.
64643 **
64644 ** Other keywords in the comment that follows each case are used to
64645 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64646 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
64647 ** the mkopcodeh.awk script for additional information.
64648 **
64649 ** Documentation about VDBE opcodes is generated by scanning this file
64650 ** for lines of that contain "Opcode:".  That line and all subsequent
64651 ** comment lines are used in the generation of the opcode.html documentation
64652 ** file.
64653 **
64654 ** SUMMARY:
64655 **
64656 **     Formatting is important to scripts that scan this file.
64657 **     Do not deviate from the formatting style currently in use.
64658 **
64659 *****************************************************************************/
64660
64661 /* Opcode:  Goto * P2 * * *
64662 **
64663 ** An unconditional jump to address P2.
64664 ** The next instruction executed will be 
64665 ** the one at index P2 from the beginning of
64666 ** the program.
64667 */
64668 case OP_Goto: {             /* jump */
64669   CHECK_FOR_INTERRUPT;
64670   pc = pOp->p2 - 1;
64671   break;
64672 }
64673
64674 /* Opcode:  Gosub P1 P2 * * *
64675 **
64676 ** Write the current address onto register P1
64677 ** and then jump to address P2.
64678 */
64679 case OP_Gosub: {            /* jump */
64680   assert( pOp->p1>0 && pOp->p1<=p->nMem );
64681   pIn1 = &aMem[pOp->p1];
64682   assert( (pIn1->flags & MEM_Dyn)==0 );
64683   memAboutToChange(p, pIn1);
64684   pIn1->flags = MEM_Int;
64685   pIn1->u.i = pc;
64686   REGISTER_TRACE(pOp->p1, pIn1);
64687   pc = pOp->p2 - 1;
64688   break;
64689 }
64690
64691 /* Opcode:  Return P1 * * * *
64692 **
64693 ** Jump to the next instruction after the address in register P1.
64694 */
64695 case OP_Return: {           /* in1 */
64696   pIn1 = &aMem[pOp->p1];
64697   assert( pIn1->flags & MEM_Int );
64698   pc = (int)pIn1->u.i;
64699   break;
64700 }
64701
64702 /* Opcode:  Yield P1 * * * *
64703 **
64704 ** Swap the program counter with the value in register P1.
64705 */
64706 case OP_Yield: {            /* in1 */
64707 #if 0  /* local variables moved into u.aa */
64708   int pcDest;
64709 #endif /* local variables moved into u.aa */
64710   pIn1 = &aMem[pOp->p1];
64711   assert( (pIn1->flags & MEM_Dyn)==0 );
64712   pIn1->flags = MEM_Int;
64713   u.aa.pcDest = (int)pIn1->u.i;
64714   pIn1->u.i = pc;
64715   REGISTER_TRACE(pOp->p1, pIn1);
64716   pc = u.aa.pcDest;
64717   break;
64718 }
64719
64720 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
64721 **
64722 ** Check the value in register P3.  If it is NULL then Halt using
64723 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
64724 ** value in register P3 is not NULL, then this routine is a no-op.
64725 */
64726 case OP_HaltIfNull: {      /* in3 */
64727   pIn3 = &aMem[pOp->p3];
64728   if( (pIn3->flags & MEM_Null)==0 ) break;
64729   /* Fall through into OP_Halt */
64730 }
64731
64732 /* Opcode:  Halt P1 P2 * P4 *
64733 **
64734 ** Exit immediately.  All open cursors, etc are closed
64735 ** automatically.
64736 **
64737 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64738 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
64739 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
64740 ** whether or not to rollback the current transaction.  Do not rollback
64741 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
64742 ** then back out all changes that have occurred during this execution of the
64743 ** VDBE, but do not rollback the transaction. 
64744 **
64745 ** If P4 is not null then it is an error message string.
64746 **
64747 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64748 ** every program.  So a jump past the last instruction of the program
64749 ** is the same as executing Halt.
64750 */
64751 case OP_Halt: {
64752   if( pOp->p1==SQLITE_OK && p->pFrame ){
64753     /* Halt the sub-program. Return control to the parent frame. */
64754     VdbeFrame *pFrame = p->pFrame;
64755     p->pFrame = pFrame->pParent;
64756     p->nFrame--;
64757     sqlite3VdbeSetChanges(db, p->nChange);
64758     pc = sqlite3VdbeFrameRestore(pFrame);
64759     lastRowid = db->lastRowid;
64760     if( pOp->p2==OE_Ignore ){
64761       /* Instruction pc is the OP_Program that invoked the sub-program 
64762       ** currently being halted. If the p2 instruction of this OP_Halt
64763       ** instruction is set to OE_Ignore, then the sub-program is throwing
64764       ** an IGNORE exception. In this case jump to the address specified
64765       ** as the p2 of the calling OP_Program.  */
64766       pc = p->aOp[pc].p2-1;
64767     }
64768     aOp = p->aOp;
64769     aMem = p->aMem;
64770     break;
64771   }
64772
64773   p->rc = pOp->p1;
64774   p->errorAction = (u8)pOp->p2;
64775   p->pc = pc;
64776   if( pOp->p4.z ){
64777     assert( p->rc!=SQLITE_OK );
64778     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64779     testcase( sqlite3GlobalConfig.xLog!=0 );
64780     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64781   }else if( p->rc ){
64782     testcase( sqlite3GlobalConfig.xLog!=0 );
64783     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64784   }
64785   rc = sqlite3VdbeHalt(p);
64786   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64787   if( rc==SQLITE_BUSY ){
64788     p->rc = rc = SQLITE_BUSY;
64789   }else{
64790     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
64791     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64792     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64793   }
64794   goto vdbe_return;
64795 }
64796
64797 /* Opcode: Integer P1 P2 * * *
64798 **
64799 ** The 32-bit integer value P1 is written into register P2.
64800 */
64801 case OP_Integer: {         /* out2-prerelease */
64802   pOut->u.i = pOp->p1;
64803   break;
64804 }
64805
64806 /* Opcode: Int64 * P2 * P4 *
64807 **
64808 ** P4 is a pointer to a 64-bit integer value.
64809 ** Write that value into register P2.
64810 */
64811 case OP_Int64: {           /* out2-prerelease */
64812   assert( pOp->p4.pI64!=0 );
64813   pOut->u.i = *pOp->p4.pI64;
64814   break;
64815 }
64816
64817 #ifndef SQLITE_OMIT_FLOATING_POINT
64818 /* Opcode: Real * P2 * P4 *
64819 **
64820 ** P4 is a pointer to a 64-bit floating point value.
64821 ** Write that value into register P2.
64822 */
64823 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
64824   pOut->flags = MEM_Real;
64825   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64826   pOut->r = *pOp->p4.pReal;
64827   break;
64828 }
64829 #endif
64830
64831 /* Opcode: String8 * P2 * P4 *
64832 **
64833 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
64834 ** into an OP_String before it is executed for the first time.
64835 */
64836 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
64837   assert( pOp->p4.z!=0 );
64838   pOp->opcode = OP_String;
64839   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
64840
64841 #ifndef SQLITE_OMIT_UTF16
64842   if( encoding!=SQLITE_UTF8 ){
64843     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
64844     if( rc==SQLITE_TOOBIG ) goto too_big;
64845     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
64846     assert( pOut->zMalloc==pOut->z );
64847     assert( pOut->flags & MEM_Dyn );
64848     pOut->zMalloc = 0;
64849     pOut->flags |= MEM_Static;
64850     pOut->flags &= ~MEM_Dyn;
64851     if( pOp->p4type==P4_DYNAMIC ){
64852       sqlite3DbFree(db, pOp->p4.z);
64853     }
64854     pOp->p4type = P4_DYNAMIC;
64855     pOp->p4.z = pOut->z;
64856     pOp->p1 = pOut->n;
64857   }
64858 #endif
64859   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64860     goto too_big;
64861   }
64862   /* Fall through to the next case, OP_String */
64863 }
64864   
64865 /* Opcode: String P1 P2 * P4 *
64866 **
64867 ** The string value P4 of length P1 (bytes) is stored in register P2.
64868 */
64869 case OP_String: {          /* out2-prerelease */
64870   assert( pOp->p4.z!=0 );
64871   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64872   pOut->z = pOp->p4.z;
64873   pOut->n = pOp->p1;
64874   pOut->enc = encoding;
64875   UPDATE_MAX_BLOBSIZE(pOut);
64876   break;
64877 }
64878
64879 /* Opcode: Null P1 P2 P3 * *
64880 **
64881 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
64882 ** NULL into register P3 and every register in between P2 and P3.  If P3
64883 ** is less than P2 (typically P3 is zero) then only register P2 is
64884 ** set to NULL.
64885 **
64886 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
64887 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
64888 ** OP_Ne or OP_Eq.
64889 */
64890 case OP_Null: {           /* out2-prerelease */
64891 #if 0  /* local variables moved into u.ab */
64892   int cnt;
64893   u16 nullFlag;
64894 #endif /* local variables moved into u.ab */
64895   u.ab.cnt = pOp->p3-pOp->p2;
64896   assert( pOp->p3<=p->nMem );
64897   pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
64898   while( u.ab.cnt>0 ){
64899     pOut++;
64900     memAboutToChange(p, pOut);
64901     VdbeMemRelease(pOut);
64902     pOut->flags = u.ab.nullFlag;
64903     u.ab.cnt--;
64904   }
64905   break;
64906 }
64907
64908
64909 /* Opcode: Blob P1 P2 * P4
64910 **
64911 ** P4 points to a blob of data P1 bytes long.  Store this
64912 ** blob in register P2.
64913 */
64914 case OP_Blob: {                /* out2-prerelease */
64915   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
64916   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
64917   pOut->enc = encoding;
64918   UPDATE_MAX_BLOBSIZE(pOut);
64919   break;
64920 }
64921
64922 /* Opcode: Variable P1 P2 * P4 *
64923 **
64924 ** Transfer the values of bound parameter P1 into register P2
64925 **
64926 ** If the parameter is named, then its name appears in P4 and P3==1.
64927 ** The P4 value is used by sqlite3_bind_parameter_name().
64928 */
64929 case OP_Variable: {            /* out2-prerelease */
64930 #if 0  /* local variables moved into u.ac */
64931   Mem *pVar;       /* Value being transferred */
64932 #endif /* local variables moved into u.ac */
64933
64934   assert( pOp->p1>0 && pOp->p1<=p->nVar );
64935   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
64936   u.ac.pVar = &p->aVar[pOp->p1 - 1];
64937   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
64938     goto too_big;
64939   }
64940   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
64941   UPDATE_MAX_BLOBSIZE(pOut);
64942   break;
64943 }
64944
64945 /* Opcode: Move P1 P2 P3 * *
64946 **
64947 ** Move the values in register P1..P1+P3 over into
64948 ** registers P2..P2+P3.  Registers P1..P1+P3 are
64949 ** left holding a NULL.  It is an error for register ranges
64950 ** P1..P1+P3 and P2..P2+P3 to overlap.
64951 */
64952 case OP_Move: {
64953 #if 0  /* local variables moved into u.ad */
64954   char *zMalloc;   /* Holding variable for allocated memory */
64955   int n;           /* Number of registers left to copy */
64956   int p1;          /* Register to copy from */
64957   int p2;          /* Register to copy to */
64958 #endif /* local variables moved into u.ad */
64959
64960   u.ad.n = pOp->p3 + 1;
64961   u.ad.p1 = pOp->p1;
64962   u.ad.p2 = pOp->p2;
64963   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
64964   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
64965
64966   pIn1 = &aMem[u.ad.p1];
64967   pOut = &aMem[u.ad.p2];
64968   while( u.ad.n-- ){
64969     assert( pOut<=&aMem[p->nMem] );
64970     assert( pIn1<=&aMem[p->nMem] );
64971     assert( memIsValid(pIn1) );
64972     memAboutToChange(p, pOut);
64973     u.ad.zMalloc = pOut->zMalloc;
64974     pOut->zMalloc = 0;
64975     sqlite3VdbeMemMove(pOut, pIn1);
64976 #ifdef SQLITE_DEBUG
64977     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
64978       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
64979     }
64980 #endif
64981     pIn1->zMalloc = u.ad.zMalloc;
64982     REGISTER_TRACE(u.ad.p2++, pOut);
64983     pIn1++;
64984     pOut++;
64985   }
64986   break;
64987 }
64988
64989 /* Opcode: Copy P1 P2 P3 * *
64990 **
64991 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
64992 **
64993 ** This instruction makes a deep copy of the value.  A duplicate
64994 ** is made of any string or blob constant.  See also OP_SCopy.
64995 */
64996 case OP_Copy: {
64997 #if 0  /* local variables moved into u.ae */
64998   int n;
64999 #endif /* local variables moved into u.ae */
65000
65001   u.ae.n = pOp->p3;
65002   pIn1 = &aMem[pOp->p1];
65003   pOut = &aMem[pOp->p2];
65004   assert( pOut!=pIn1 );
65005   while( 1 ){
65006     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65007     Deephemeralize(pOut);
65008 #ifdef SQLITE_DEBUG
65009     pOut->pScopyFrom = 0;
65010 #endif
65011     REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
65012     if( (u.ae.n--)==0 ) break;
65013     pOut++;
65014     pIn1++;
65015   }
65016   break;
65017 }
65018
65019 /* Opcode: SCopy P1 P2 * * *
65020 **
65021 ** Make a shallow copy of register P1 into register P2.
65022 **
65023 ** This instruction makes a shallow copy of the value.  If the value
65024 ** is a string or blob, then the copy is only a pointer to the
65025 ** original and hence if the original changes so will the copy.
65026 ** Worse, if the original is deallocated, the copy becomes invalid.
65027 ** Thus the program must guarantee that the original will not change
65028 ** during the lifetime of the copy.  Use OP_Copy to make a complete
65029 ** copy.
65030 */
65031 case OP_SCopy: {            /* in1, out2 */
65032   pIn1 = &aMem[pOp->p1];
65033   pOut = &aMem[pOp->p2];
65034   assert( pOut!=pIn1 );
65035   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65036 #ifdef SQLITE_DEBUG
65037   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65038 #endif
65039   REGISTER_TRACE(pOp->p2, pOut);
65040   break;
65041 }
65042
65043 /* Opcode: ResultRow P1 P2 * * *
65044 **
65045 ** The registers P1 through P1+P2-1 contain a single row of
65046 ** results. This opcode causes the sqlite3_step() call to terminate
65047 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
65048 ** structure to provide access to the top P1 values as the result
65049 ** row.
65050 */
65051 case OP_ResultRow: {
65052 #if 0  /* local variables moved into u.af */
65053   Mem *pMem;
65054   int i;
65055 #endif /* local variables moved into u.af */
65056   assert( p->nResColumn==pOp->p2 );
65057   assert( pOp->p1>0 );
65058   assert( pOp->p1+pOp->p2<=p->nMem+1 );
65059
65060   /* If this statement has violated immediate foreign key constraints, do
65061   ** not return the number of rows modified. And do not RELEASE the statement
65062   ** transaction. It needs to be rolled back.  */
65063   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
65064     assert( db->flags&SQLITE_CountRows );
65065     assert( p->usesStmtJournal );
65066     break;
65067   }
65068
65069   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
65070   ** DML statements invoke this opcode to return the number of rows
65071   ** modified to the user. This is the only way that a VM that
65072   ** opens a statement transaction may invoke this opcode.
65073   **
65074   ** In case this is such a statement, close any statement transaction
65075   ** opened by this VM before returning control to the user. This is to
65076   ** ensure that statement-transactions are always nested, not overlapping.
65077   ** If the open statement-transaction is not closed here, then the user
65078   ** may step another VM that opens its own statement transaction. This
65079   ** may lead to overlapping statement transactions.
65080   **
65081   ** The statement transaction is never a top-level transaction.  Hence
65082   ** the RELEASE call below can never fail.
65083   */
65084   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
65085   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65086   if( NEVER(rc!=SQLITE_OK) ){
65087     break;
65088   }
65089
65090   /* Invalidate all ephemeral cursor row caches */
65091   p->cacheCtr = (p->cacheCtr + 2)|1;
65092
65093   /* Make sure the results of the current row are \000 terminated
65094   ** and have an assigned type.  The results are de-ephemeralized as
65095   ** a side effect.
65096   */
65097   u.af.pMem = p->pResultSet = &aMem[pOp->p1];
65098   for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
65099     assert( memIsValid(&u.af.pMem[u.af.i]) );
65100     Deephemeralize(&u.af.pMem[u.af.i]);
65101     assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
65102             || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
65103     sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
65104     sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
65105     REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
65106   }
65107   if( db->mallocFailed ) goto no_mem;
65108
65109   /* Return SQLITE_ROW
65110   */
65111   p->pc = pc + 1;
65112   rc = SQLITE_ROW;
65113   goto vdbe_return;
65114 }
65115
65116 /* Opcode: Concat P1 P2 P3 * *
65117 **
65118 ** Add the text in register P1 onto the end of the text in
65119 ** register P2 and store the result in register P3.
65120 ** If either the P1 or P2 text are NULL then store NULL in P3.
65121 **
65122 **   P3 = P2 || P1
65123 **
65124 ** It is illegal for P1 and P3 to be the same register. Sometimes,
65125 ** if P3 is the same register as P2, the implementation is able
65126 ** to avoid a memcpy().
65127 */
65128 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
65129 #if 0  /* local variables moved into u.ag */
65130   i64 nByte;
65131 #endif /* local variables moved into u.ag */
65132
65133   pIn1 = &aMem[pOp->p1];
65134   pIn2 = &aMem[pOp->p2];
65135   pOut = &aMem[pOp->p3];
65136   assert( pIn1!=pOut );
65137   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65138     sqlite3VdbeMemSetNull(pOut);
65139     break;
65140   }
65141   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
65142   Stringify(pIn1, encoding);
65143   Stringify(pIn2, encoding);
65144   u.ag.nByte = pIn1->n + pIn2->n;
65145   if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65146     goto too_big;
65147   }
65148   MemSetTypeFlag(pOut, MEM_Str);
65149   if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
65150     goto no_mem;
65151   }
65152   if( pOut!=pIn2 ){
65153     memcpy(pOut->z, pIn2->z, pIn2->n);
65154   }
65155   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
65156   pOut->z[u.ag.nByte] = 0;
65157   pOut->z[u.ag.nByte+1] = 0;
65158   pOut->flags |= MEM_Term;
65159   pOut->n = (int)u.ag.nByte;
65160   pOut->enc = encoding;
65161   UPDATE_MAX_BLOBSIZE(pOut);
65162   break;
65163 }
65164
65165 /* Opcode: Add P1 P2 P3 * *
65166 **
65167 ** Add the value in register P1 to the value in register P2
65168 ** and store the result in register P3.
65169 ** If either input is NULL, the result is NULL.
65170 */
65171 /* Opcode: Multiply P1 P2 P3 * *
65172 **
65173 **
65174 ** Multiply the value in register P1 by the value in register P2
65175 ** and store the result in register P3.
65176 ** If either input is NULL, the result is NULL.
65177 */
65178 /* Opcode: Subtract P1 P2 P3 * *
65179 **
65180 ** Subtract the value in register P1 from the value in register P2
65181 ** and store the result in register P3.
65182 ** If either input is NULL, the result is NULL.
65183 */
65184 /* Opcode: Divide P1 P2 P3 * *
65185 **
65186 ** Divide the value in register P1 by the value in register P2
65187 ** and store the result in register P3 (P3=P2/P1). If the value in 
65188 ** register P1 is zero, then the result is NULL. If either input is 
65189 ** NULL, the result is NULL.
65190 */
65191 /* Opcode: Remainder P1 P2 P3 * *
65192 **
65193 ** Compute the remainder after integer division of the value in
65194 ** register P1 by the value in register P2 and store the result in P3. 
65195 ** If the value in register P2 is zero the result is NULL.
65196 ** If either operand is NULL, the result is NULL.
65197 */
65198 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
65199 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
65200 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
65201 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
65202 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
65203 #if 0  /* local variables moved into u.ah */
65204   char bIntint;   /* Started out as two integer operands */
65205   int flags;      /* Combined MEM_* flags from both inputs */
65206   i64 iA;         /* Integer value of left operand */
65207   i64 iB;         /* Integer value of right operand */
65208   double rA;      /* Real value of left operand */
65209   double rB;      /* Real value of right operand */
65210 #endif /* local variables moved into u.ah */
65211
65212   pIn1 = &aMem[pOp->p1];
65213   applyNumericAffinity(pIn1);
65214   pIn2 = &aMem[pOp->p2];
65215   applyNumericAffinity(pIn2);
65216   pOut = &aMem[pOp->p3];
65217   u.ah.flags = pIn1->flags | pIn2->flags;
65218   if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
65219   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
65220     u.ah.iA = pIn1->u.i;
65221     u.ah.iB = pIn2->u.i;
65222     u.ah.bIntint = 1;
65223     switch( pOp->opcode ){
65224       case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65225       case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65226       case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65227       case OP_Divide: {
65228         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65229         if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
65230         u.ah.iB /= u.ah.iA;
65231         break;
65232       }
65233       default: {
65234         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65235         if( u.ah.iA==-1 ) u.ah.iA = 1;
65236         u.ah.iB %= u.ah.iA;
65237         break;
65238       }
65239     }
65240     pOut->u.i = u.ah.iB;
65241     MemSetTypeFlag(pOut, MEM_Int);
65242   }else{
65243     u.ah.bIntint = 0;
65244 fp_math:
65245     u.ah.rA = sqlite3VdbeRealValue(pIn1);
65246     u.ah.rB = sqlite3VdbeRealValue(pIn2);
65247     switch( pOp->opcode ){
65248       case OP_Add:         u.ah.rB += u.ah.rA;       break;
65249       case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
65250       case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
65251       case OP_Divide: {
65252         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65253         if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
65254         u.ah.rB /= u.ah.rA;
65255         break;
65256       }
65257       default: {
65258         u.ah.iA = (i64)u.ah.rA;
65259         u.ah.iB = (i64)u.ah.rB;
65260         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65261         if( u.ah.iA==-1 ) u.ah.iA = 1;
65262         u.ah.rB = (double)(u.ah.iB % u.ah.iA);
65263         break;
65264       }
65265     }
65266 #ifdef SQLITE_OMIT_FLOATING_POINT
65267     pOut->u.i = u.ah.rB;
65268     MemSetTypeFlag(pOut, MEM_Int);
65269 #else
65270     if( sqlite3IsNaN(u.ah.rB) ){
65271       goto arithmetic_result_is_null;
65272     }
65273     pOut->r = u.ah.rB;
65274     MemSetTypeFlag(pOut, MEM_Real);
65275     if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
65276       sqlite3VdbeIntegerAffinity(pOut);
65277     }
65278 #endif
65279   }
65280   break;
65281
65282 arithmetic_result_is_null:
65283   sqlite3VdbeMemSetNull(pOut);
65284   break;
65285 }
65286
65287 /* Opcode: CollSeq P1 * * P4
65288 **
65289 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
65290 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
65291 ** be returned. This is used by the built-in min(), max() and nullif()
65292 ** functions.
65293 **
65294 ** If P1 is not zero, then it is a register that a subsequent min() or
65295 ** max() aggregate will set to 1 if the current row is not the minimum or
65296 ** maximum.  The P1 register is initialized to 0 by this instruction.
65297 **
65298 ** The interface used by the implementation of the aforementioned functions
65299 ** to retrieve the collation sequence set by this opcode is not available
65300 ** publicly, only to user functions defined in func.c.
65301 */
65302 case OP_CollSeq: {
65303   assert( pOp->p4type==P4_COLLSEQ );
65304   if( pOp->p1 ){
65305     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
65306   }
65307   break;
65308 }
65309
65310 /* Opcode: Function P1 P2 P3 P4 P5
65311 **
65312 ** Invoke a user function (P4 is a pointer to a Function structure that
65313 ** defines the function) with P5 arguments taken from register P2 and
65314 ** successors.  The result of the function is stored in register P3.
65315 ** Register P3 must not be one of the function inputs.
65316 **
65317 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
65318 ** function was determined to be constant at compile time. If the first
65319 ** argument was constant then bit 0 of P1 is set. This is used to determine
65320 ** whether meta data associated with a user function argument using the
65321 ** sqlite3_set_auxdata() API may be safely retained until the next
65322 ** invocation of this opcode.
65323 **
65324 ** See also: AggStep and AggFinal
65325 */
65326 case OP_Function: {
65327 #if 0  /* local variables moved into u.ai */
65328   int i;
65329   Mem *pArg;
65330   sqlite3_context ctx;
65331   sqlite3_value **apVal;
65332   int n;
65333 #endif /* local variables moved into u.ai */
65334
65335   u.ai.n = pOp->p5;
65336   u.ai.apVal = p->apArg;
65337   assert( u.ai.apVal || u.ai.n==0 );
65338   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65339   pOut = &aMem[pOp->p3];
65340   memAboutToChange(p, pOut);
65341
65342   assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
65343   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
65344   u.ai.pArg = &aMem[pOp->p2];
65345   for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
65346     assert( memIsValid(u.ai.pArg) );
65347     u.ai.apVal[u.ai.i] = u.ai.pArg;
65348     Deephemeralize(u.ai.pArg);
65349     sqlite3VdbeMemStoreType(u.ai.pArg);
65350     REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
65351   }
65352
65353   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
65354   if( pOp->p4type==P4_FUNCDEF ){
65355     u.ai.ctx.pFunc = pOp->p4.pFunc;
65356     u.ai.ctx.pVdbeFunc = 0;
65357   }else{
65358     u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
65359     u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
65360   }
65361
65362   u.ai.ctx.s.flags = MEM_Null;
65363   u.ai.ctx.s.db = db;
65364   u.ai.ctx.s.xDel = 0;
65365   u.ai.ctx.s.zMalloc = 0;
65366
65367   /* The output cell may already have a buffer allocated. Move
65368   ** the pointer to u.ai.ctx.s so in case the user-function can use
65369   ** the already allocated buffer instead of allocating a new one.
65370   */
65371   sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
65372   MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
65373
65374   u.ai.ctx.isError = 0;
65375   if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65376     assert( pOp>aOp );
65377     assert( pOp[-1].p4type==P4_COLLSEQ );
65378     assert( pOp[-1].opcode==OP_CollSeq );
65379     u.ai.ctx.pColl = pOp[-1].p4.pColl;
65380   }
65381   db->lastRowid = lastRowid;
65382   (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
65383   lastRowid = db->lastRowid;
65384
65385   /* If any auxiliary data functions have been called by this user function,
65386   ** immediately call the destructor for any non-static values.
65387   */
65388   if( u.ai.ctx.pVdbeFunc ){
65389     sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
65390     pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
65391     pOp->p4type = P4_VDBEFUNC;
65392   }
65393
65394   if( db->mallocFailed ){
65395     /* Even though a malloc() has failed, the implementation of the
65396     ** user function may have called an sqlite3_result_XXX() function
65397     ** to return a value. The following call releases any resources
65398     ** associated with such a value.
65399     */
65400     sqlite3VdbeMemRelease(&u.ai.ctx.s);
65401     goto no_mem;
65402   }
65403
65404   /* If the function returned an error, throw an exception */
65405   if( u.ai.ctx.isError ){
65406     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
65407     rc = u.ai.ctx.isError;
65408   }
65409
65410   /* Copy the result of the function into register P3 */
65411   sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
65412   sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
65413   if( sqlite3VdbeMemTooBig(pOut) ){
65414     goto too_big;
65415   }
65416
65417 #if 0
65418   /* The app-defined function has done something that as caused this
65419   ** statement to expire.  (Perhaps the function called sqlite3_exec()
65420   ** with a CREATE TABLE statement.)
65421   */
65422   if( p->expired ) rc = SQLITE_ABORT;
65423 #endif
65424
65425   REGISTER_TRACE(pOp->p3, pOut);
65426   UPDATE_MAX_BLOBSIZE(pOut);
65427   break;
65428 }
65429
65430 /* Opcode: BitAnd P1 P2 P3 * *
65431 **
65432 ** Take the bit-wise AND of the values in register P1 and P2 and
65433 ** store the result in register P3.
65434 ** If either input is NULL, the result is NULL.
65435 */
65436 /* Opcode: BitOr P1 P2 P3 * *
65437 **
65438 ** Take the bit-wise OR of the values in register P1 and P2 and
65439 ** store the result in register P3.
65440 ** If either input is NULL, the result is NULL.
65441 */
65442 /* Opcode: ShiftLeft P1 P2 P3 * *
65443 **
65444 ** Shift the integer value in register P2 to the left by the
65445 ** number of bits specified by the integer in register P1.
65446 ** Store the result in register P3.
65447 ** If either input is NULL, the result is NULL.
65448 */
65449 /* Opcode: ShiftRight P1 P2 P3 * *
65450 **
65451 ** Shift the integer value in register P2 to the right by the
65452 ** number of bits specified by the integer in register P1.
65453 ** Store the result in register P3.
65454 ** If either input is NULL, the result is NULL.
65455 */
65456 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
65457 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
65458 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
65459 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
65460 #if 0  /* local variables moved into u.aj */
65461   i64 iA;
65462   u64 uA;
65463   i64 iB;
65464   u8 op;
65465 #endif /* local variables moved into u.aj */
65466
65467   pIn1 = &aMem[pOp->p1];
65468   pIn2 = &aMem[pOp->p2];
65469   pOut = &aMem[pOp->p3];
65470   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65471     sqlite3VdbeMemSetNull(pOut);
65472     break;
65473   }
65474   u.aj.iA = sqlite3VdbeIntValue(pIn2);
65475   u.aj.iB = sqlite3VdbeIntValue(pIn1);
65476   u.aj.op = pOp->opcode;
65477   if( u.aj.op==OP_BitAnd ){
65478     u.aj.iA &= u.aj.iB;
65479   }else if( u.aj.op==OP_BitOr ){
65480     u.aj.iA |= u.aj.iB;
65481   }else if( u.aj.iB!=0 ){
65482     assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
65483
65484     /* If shifting by a negative amount, shift in the other direction */
65485     if( u.aj.iB<0 ){
65486       assert( OP_ShiftRight==OP_ShiftLeft+1 );
65487       u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
65488       u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
65489     }
65490
65491     if( u.aj.iB>=64 ){
65492       u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
65493     }else{
65494       memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
65495       if( u.aj.op==OP_ShiftLeft ){
65496         u.aj.uA <<= u.aj.iB;
65497       }else{
65498         u.aj.uA >>= u.aj.iB;
65499         /* Sign-extend on a right shift of a negative number */
65500         if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
65501       }
65502       memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
65503     }
65504   }
65505   pOut->u.i = u.aj.iA;
65506   MemSetTypeFlag(pOut, MEM_Int);
65507   break;
65508 }
65509
65510 /* Opcode: AddImm  P1 P2 * * *
65511 ** 
65512 ** Add the constant P2 to the value in register P1.
65513 ** The result is always an integer.
65514 **
65515 ** To force any register to be an integer, just add 0.
65516 */
65517 case OP_AddImm: {            /* in1 */
65518   pIn1 = &aMem[pOp->p1];
65519   memAboutToChange(p, pIn1);
65520   sqlite3VdbeMemIntegerify(pIn1);
65521   pIn1->u.i += pOp->p2;
65522   break;
65523 }
65524
65525 /* Opcode: MustBeInt P1 P2 * * *
65526 ** 
65527 ** Force the value in register P1 to be an integer.  If the value
65528 ** in P1 is not an integer and cannot be converted into an integer
65529 ** without data loss, then jump immediately to P2, or if P2==0
65530 ** raise an SQLITE_MISMATCH exception.
65531 */
65532 case OP_MustBeInt: {            /* jump, in1 */
65533   pIn1 = &aMem[pOp->p1];
65534   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
65535   if( (pIn1->flags & MEM_Int)==0 ){
65536     if( pOp->p2==0 ){
65537       rc = SQLITE_MISMATCH;
65538       goto abort_due_to_error;
65539     }else{
65540       pc = pOp->p2 - 1;
65541     }
65542   }else{
65543     MemSetTypeFlag(pIn1, MEM_Int);
65544   }
65545   break;
65546 }
65547
65548 #ifndef SQLITE_OMIT_FLOATING_POINT
65549 /* Opcode: RealAffinity P1 * * * *
65550 **
65551 ** If register P1 holds an integer convert it to a real value.
65552 **
65553 ** This opcode is used when extracting information from a column that
65554 ** has REAL affinity.  Such column values may still be stored as
65555 ** integers, for space efficiency, but after extraction we want them
65556 ** to have only a real value.
65557 */
65558 case OP_RealAffinity: {                  /* in1 */
65559   pIn1 = &aMem[pOp->p1];
65560   if( pIn1->flags & MEM_Int ){
65561     sqlite3VdbeMemRealify(pIn1);
65562   }
65563   break;
65564 }
65565 #endif
65566
65567 #ifndef SQLITE_OMIT_CAST
65568 /* Opcode: ToText P1 * * * *
65569 **
65570 ** Force the value in register P1 to be text.
65571 ** If the value is numeric, convert it to a string using the
65572 ** equivalent of printf().  Blob values are unchanged and
65573 ** are afterwards simply interpreted as text.
65574 **
65575 ** A NULL value is not changed by this routine.  It remains NULL.
65576 */
65577 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
65578   pIn1 = &aMem[pOp->p1];
65579   memAboutToChange(p, pIn1);
65580   if( pIn1->flags & MEM_Null ) break;
65581   assert( MEM_Str==(MEM_Blob>>3) );
65582   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65583   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65584   rc = ExpandBlob(pIn1);
65585   assert( pIn1->flags & MEM_Str || db->mallocFailed );
65586   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65587   UPDATE_MAX_BLOBSIZE(pIn1);
65588   break;
65589 }
65590
65591 /* Opcode: ToBlob P1 * * * *
65592 **
65593 ** Force the value in register P1 to be a BLOB.
65594 ** If the value is numeric, convert it to a string first.
65595 ** Strings are simply reinterpreted as blobs with no change
65596 ** to the underlying data.
65597 **
65598 ** A NULL value is not changed by this routine.  It remains NULL.
65599 */
65600 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
65601   pIn1 = &aMem[pOp->p1];
65602   if( pIn1->flags & MEM_Null ) break;
65603   if( (pIn1->flags & MEM_Blob)==0 ){
65604     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65605     assert( pIn1->flags & MEM_Str || db->mallocFailed );
65606     MemSetTypeFlag(pIn1, MEM_Blob);
65607   }else{
65608     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65609   }
65610   UPDATE_MAX_BLOBSIZE(pIn1);
65611   break;
65612 }
65613
65614 /* Opcode: ToNumeric P1 * * * *
65615 **
65616 ** Force the value in register P1 to be numeric (either an
65617 ** integer or a floating-point number.)
65618 ** If the value is text or blob, try to convert it to an using the
65619 ** equivalent of atoi() or atof() and store 0 if no such conversion 
65620 ** is possible.
65621 **
65622 ** A NULL value is not changed by this routine.  It remains NULL.
65623 */
65624 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
65625   pIn1 = &aMem[pOp->p1];
65626   sqlite3VdbeMemNumerify(pIn1);
65627   break;
65628 }
65629 #endif /* SQLITE_OMIT_CAST */
65630
65631 /* Opcode: ToInt P1 * * * *
65632 **
65633 ** Force the value in register P1 to be an integer.  If
65634 ** The value is currently a real number, drop its fractional part.
65635 ** If the value is text or blob, try to convert it to an integer using the
65636 ** equivalent of atoi() and store 0 if no such conversion is possible.
65637 **
65638 ** A NULL value is not changed by this routine.  It remains NULL.
65639 */
65640 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
65641   pIn1 = &aMem[pOp->p1];
65642   if( (pIn1->flags & MEM_Null)==0 ){
65643     sqlite3VdbeMemIntegerify(pIn1);
65644   }
65645   break;
65646 }
65647
65648 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65649 /* Opcode: ToReal P1 * * * *
65650 **
65651 ** Force the value in register P1 to be a floating point number.
65652 ** If The value is currently an integer, convert it.
65653 ** If the value is text or blob, try to convert it to an integer using the
65654 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65655 **
65656 ** A NULL value is not changed by this routine.  It remains NULL.
65657 */
65658 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
65659   pIn1 = &aMem[pOp->p1];
65660   memAboutToChange(p, pIn1);
65661   if( (pIn1->flags & MEM_Null)==0 ){
65662     sqlite3VdbeMemRealify(pIn1);
65663   }
65664   break;
65665 }
65666 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65667
65668 /* Opcode: Lt P1 P2 P3 P4 P5
65669 **
65670 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
65671 ** jump to address P2.  
65672 **
65673 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65674 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
65675 ** bit is clear then fall through if either operand is NULL.
65676 **
65677 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65678 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
65679 ** to coerce both inputs according to this affinity before the
65680 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65681 ** affinity is used. Note that the affinity conversions are stored
65682 ** back into the input registers P1 and P3.  So this opcode can cause
65683 ** persistent changes to registers P1 and P3.
65684 **
65685 ** Once any conversions have taken place, and neither value is NULL, 
65686 ** the values are compared. If both values are blobs then memcmp() is
65687 ** used to determine the results of the comparison.  If both values
65688 ** are text, then the appropriate collating function specified in
65689 ** P4 is  used to do the comparison.  If P4 is not specified then
65690 ** memcmp() is used to compare text string.  If both values are
65691 ** numeric, then a numeric comparison is used. If the two values
65692 ** are of different types, then numbers are considered less than
65693 ** strings and strings are considered less than blobs.
65694 **
65695 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
65696 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65697 **
65698 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
65699 ** equal to one another, provided that they do not have their MEM_Cleared
65700 ** bit set.
65701 */
65702 /* Opcode: Ne P1 P2 P3 P4 P5
65703 **
65704 ** This works just like the Lt opcode except that the jump is taken if
65705 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
65706 ** additional information.
65707 **
65708 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65709 ** true or false and is never NULL.  If both operands are NULL then the result
65710 ** of comparison is false.  If either operand is NULL then the result is true.
65711 ** If neither operand is NULL the result is the same as it would be if
65712 ** the SQLITE_NULLEQ flag were omitted from P5.
65713 */
65714 /* Opcode: Eq P1 P2 P3 P4 P5
65715 **
65716 ** This works just like the Lt opcode except that the jump is taken if
65717 ** the operands in registers P1 and P3 are equal.
65718 ** See the Lt opcode for additional information.
65719 **
65720 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65721 ** true or false and is never NULL.  If both operands are NULL then the result
65722 ** of comparison is true.  If either operand is NULL then the result is false.
65723 ** If neither operand is NULL the result is the same as it would be if
65724 ** the SQLITE_NULLEQ flag were omitted from P5.
65725 */
65726 /* Opcode: Le P1 P2 P3 P4 P5
65727 **
65728 ** This works just like the Lt opcode except that the jump is taken if
65729 ** the content of register P3 is less than or equal to the content of
65730 ** register P1.  See the Lt opcode for additional information.
65731 */
65732 /* Opcode: Gt P1 P2 P3 P4 P5
65733 **
65734 ** This works just like the Lt opcode except that the jump is taken if
65735 ** the content of register P3 is greater than the content of
65736 ** register P1.  See the Lt opcode for additional information.
65737 */
65738 /* Opcode: Ge P1 P2 P3 P4 P5
65739 **
65740 ** This works just like the Lt opcode except that the jump is taken if
65741 ** the content of register P3 is greater than or equal to the content of
65742 ** register P1.  See the Lt opcode for additional information.
65743 */
65744 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
65745 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
65746 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
65747 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
65748 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
65749 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
65750 #if 0  /* local variables moved into u.ak */
65751   int res;            /* Result of the comparison of pIn1 against pIn3 */
65752   char affinity;      /* Affinity to use for comparison */
65753   u16 flags1;         /* Copy of initial value of pIn1->flags */
65754   u16 flags3;         /* Copy of initial value of pIn3->flags */
65755 #endif /* local variables moved into u.ak */
65756
65757   pIn1 = &aMem[pOp->p1];
65758   pIn3 = &aMem[pOp->p3];
65759   u.ak.flags1 = pIn1->flags;
65760   u.ak.flags3 = pIn3->flags;
65761   if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
65762     /* One or both operands are NULL */
65763     if( pOp->p5 & SQLITE_NULLEQ ){
65764       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65765       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65766       ** or not both operands are null.
65767       */
65768       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65769       assert( (u.ak.flags1 & MEM_Cleared)==0 );
65770       if( (u.ak.flags1&MEM_Null)!=0
65771        && (u.ak.flags3&MEM_Null)!=0
65772        && (u.ak.flags3&MEM_Cleared)==0
65773       ){
65774         u.ak.res = 0;  /* Results are equal */
65775       }else{
65776         u.ak.res = 1;  /* Results are not equal */
65777       }
65778     }else{
65779       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65780       ** then the result is always NULL.
65781       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65782       */
65783       if( pOp->p5 & SQLITE_STOREP2 ){
65784         pOut = &aMem[pOp->p2];
65785         MemSetTypeFlag(pOut, MEM_Null);
65786         REGISTER_TRACE(pOp->p2, pOut);
65787       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65788         pc = pOp->p2-1;
65789       }
65790       break;
65791     }
65792   }else{
65793     /* Neither operand is NULL.  Do a comparison. */
65794     u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
65795     if( u.ak.affinity ){
65796       applyAffinity(pIn1, u.ak.affinity, encoding);
65797       applyAffinity(pIn3, u.ak.affinity, encoding);
65798       if( db->mallocFailed ) goto no_mem;
65799     }
65800
65801     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65802     ExpandBlob(pIn1);
65803     ExpandBlob(pIn3);
65804     u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65805   }
65806   switch( pOp->opcode ){
65807     case OP_Eq:    u.ak.res = u.ak.res==0;     break;
65808     case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
65809     case OP_Lt:    u.ak.res = u.ak.res<0;      break;
65810     case OP_Le:    u.ak.res = u.ak.res<=0;     break;
65811     case OP_Gt:    u.ak.res = u.ak.res>0;      break;
65812     default:       u.ak.res = u.ak.res>=0;     break;
65813   }
65814
65815   if( pOp->p5 & SQLITE_STOREP2 ){
65816     pOut = &aMem[pOp->p2];
65817     memAboutToChange(p, pOut);
65818     MemSetTypeFlag(pOut, MEM_Int);
65819     pOut->u.i = u.ak.res;
65820     REGISTER_TRACE(pOp->p2, pOut);
65821   }else if( u.ak.res ){
65822     pc = pOp->p2-1;
65823   }
65824
65825   /* Undo any changes made by applyAffinity() to the input registers. */
65826   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
65827   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
65828   break;
65829 }
65830
65831 /* Opcode: Permutation * * * P4 *
65832 **
65833 ** Set the permutation used by the OP_Compare operator to be the array
65834 ** of integers in P4.
65835 **
65836 ** The permutation is only valid until the next OP_Compare that has
65837 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
65838 ** occur immediately prior to the OP_Compare.
65839 */
65840 case OP_Permutation: {
65841   assert( pOp->p4type==P4_INTARRAY );
65842   assert( pOp->p4.ai );
65843   aPermute = pOp->p4.ai;
65844   break;
65845 }
65846
65847 /* Opcode: Compare P1 P2 P3 P4 P5
65848 **
65849 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
65850 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
65851 ** the comparison for use by the next OP_Jump instruct.
65852 **
65853 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
65854 ** determined by the most recent OP_Permutation operator.  If the
65855 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
65856 ** order.
65857 **
65858 ** P4 is a KeyInfo structure that defines collating sequences and sort
65859 ** orders for the comparison.  The permutation applies to registers
65860 ** only.  The KeyInfo elements are used sequentially.
65861 **
65862 ** The comparison is a sort comparison, so NULLs compare equal,
65863 ** NULLs are less than numbers, numbers are less than strings,
65864 ** and strings are less than blobs.
65865 */
65866 case OP_Compare: {
65867 #if 0  /* local variables moved into u.al */
65868   int n;
65869   int i;
65870   int p1;
65871   int p2;
65872   const KeyInfo *pKeyInfo;
65873   int idx;
65874   CollSeq *pColl;    /* Collating sequence to use on this term */
65875   int bRev;          /* True for DESCENDING sort order */
65876 #endif /* local variables moved into u.al */
65877
65878   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
65879   u.al.n = pOp->p3;
65880   u.al.pKeyInfo = pOp->p4.pKeyInfo;
65881   assert( u.al.n>0 );
65882   assert( u.al.pKeyInfo!=0 );
65883   u.al.p1 = pOp->p1;
65884   u.al.p2 = pOp->p2;
65885 #if SQLITE_DEBUG
65886   if( aPermute ){
65887     int k, mx = 0;
65888     for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
65889     assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
65890     assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
65891   }else{
65892     assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
65893     assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
65894   }
65895 #endif /* SQLITE_DEBUG */
65896   for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
65897     u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
65898     assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
65899     assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
65900     REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
65901     REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
65902     assert( u.al.i<u.al.pKeyInfo->nField );
65903     u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
65904     u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
65905     iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
65906     if( iCompare ){
65907       if( u.al.bRev ) iCompare = -iCompare;
65908       break;
65909     }
65910   }
65911   aPermute = 0;
65912   break;
65913 }
65914
65915 /* Opcode: Jump P1 P2 P3 * *
65916 **
65917 ** Jump to the instruction at address P1, P2, or P3 depending on whether
65918 ** in the most recent OP_Compare instruction the P1 vector was less than
65919 ** equal to, or greater than the P2 vector, respectively.
65920 */
65921 case OP_Jump: {             /* jump */
65922   if( iCompare<0 ){
65923     pc = pOp->p1 - 1;
65924   }else if( iCompare==0 ){
65925     pc = pOp->p2 - 1;
65926   }else{
65927     pc = pOp->p3 - 1;
65928   }
65929   break;
65930 }
65931
65932 /* Opcode: And P1 P2 P3 * *
65933 **
65934 ** Take the logical AND of the values in registers P1 and P2 and
65935 ** write the result into register P3.
65936 **
65937 ** If either P1 or P2 is 0 (false) then the result is 0 even if
65938 ** the other input is NULL.  A NULL and true or two NULLs give
65939 ** a NULL output.
65940 */
65941 /* Opcode: Or P1 P2 P3 * *
65942 **
65943 ** Take the logical OR of the values in register P1 and P2 and
65944 ** store the answer in register P3.
65945 **
65946 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
65947 ** even if the other input is NULL.  A NULL and false or two NULLs
65948 ** give a NULL output.
65949 */
65950 case OP_And:              /* same as TK_AND, in1, in2, out3 */
65951 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
65952 #if 0  /* local variables moved into u.am */
65953   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65954   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65955 #endif /* local variables moved into u.am */
65956
65957   pIn1 = &aMem[pOp->p1];
65958   if( pIn1->flags & MEM_Null ){
65959     u.am.v1 = 2;
65960   }else{
65961     u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
65962   }
65963   pIn2 = &aMem[pOp->p2];
65964   if( pIn2->flags & MEM_Null ){
65965     u.am.v2 = 2;
65966   }else{
65967     u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
65968   }
65969   if( pOp->opcode==OP_And ){
65970     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
65971     u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
65972   }else{
65973     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
65974     u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
65975   }
65976   pOut = &aMem[pOp->p3];
65977   if( u.am.v1==2 ){
65978     MemSetTypeFlag(pOut, MEM_Null);
65979   }else{
65980     pOut->u.i = u.am.v1;
65981     MemSetTypeFlag(pOut, MEM_Int);
65982   }
65983   break;
65984 }
65985
65986 /* Opcode: Not P1 P2 * * *
65987 **
65988 ** Interpret the value in register P1 as a boolean value.  Store the
65989 ** boolean complement in register P2.  If the value in register P1 is 
65990 ** NULL, then a NULL is stored in P2.
65991 */
65992 case OP_Not: {                /* same as TK_NOT, in1, out2 */
65993   pIn1 = &aMem[pOp->p1];
65994   pOut = &aMem[pOp->p2];
65995   if( pIn1->flags & MEM_Null ){
65996     sqlite3VdbeMemSetNull(pOut);
65997   }else{
65998     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
65999   }
66000   break;
66001 }
66002
66003 /* Opcode: BitNot P1 P2 * * *
66004 **
66005 ** Interpret the content of register P1 as an integer.  Store the
66006 ** ones-complement of the P1 value into register P2.  If P1 holds
66007 ** a NULL then store a NULL in P2.
66008 */
66009 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66010   pIn1 = &aMem[pOp->p1];
66011   pOut = &aMem[pOp->p2];
66012   if( pIn1->flags & MEM_Null ){
66013     sqlite3VdbeMemSetNull(pOut);
66014   }else{
66015     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
66016   }
66017   break;
66018 }
66019
66020 /* Opcode: Once P1 P2 * * *
66021 **
66022 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
66023 ** set the flag and fall through to the next instruction.
66024 */
66025 case OP_Once: {             /* jump */
66026   assert( pOp->p1<p->nOnceFlag );
66027   if( p->aOnceFlag[pOp->p1] ){
66028     pc = pOp->p2-1;
66029   }else{
66030     p->aOnceFlag[pOp->p1] = 1;
66031   }
66032   break;
66033 }
66034
66035 /* Opcode: If P1 P2 P3 * *
66036 **
66037 ** Jump to P2 if the value in register P1 is true.  The value
66038 ** is considered true if it is numeric and non-zero.  If the value
66039 ** in P1 is NULL then take the jump if P3 is non-zero.
66040 */
66041 /* Opcode: IfNot P1 P2 P3 * *
66042 **
66043 ** Jump to P2 if the value in register P1 is False.  The value
66044 ** is considered false if it has a numeric value of zero.  If the value
66045 ** in P1 is NULL then take the jump if P3 is zero.
66046 */
66047 case OP_If:                 /* jump, in1 */
66048 case OP_IfNot: {            /* jump, in1 */
66049 #if 0  /* local variables moved into u.an */
66050   int c;
66051 #endif /* local variables moved into u.an */
66052   pIn1 = &aMem[pOp->p1];
66053   if( pIn1->flags & MEM_Null ){
66054     u.an.c = pOp->p3;
66055   }else{
66056 #ifdef SQLITE_OMIT_FLOATING_POINT
66057     u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
66058 #else
66059     u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
66060 #endif
66061     if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
66062   }
66063   if( u.an.c ){
66064     pc = pOp->p2-1;
66065   }
66066   break;
66067 }
66068
66069 /* Opcode: IsNull P1 P2 * * *
66070 **
66071 ** Jump to P2 if the value in register P1 is NULL.
66072 */
66073 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66074   pIn1 = &aMem[pOp->p1];
66075   if( (pIn1->flags & MEM_Null)!=0 ){
66076     pc = pOp->p2 - 1;
66077   }
66078   break;
66079 }
66080
66081 /* Opcode: NotNull P1 P2 * * *
66082 **
66083 ** Jump to P2 if the value in register P1 is not NULL.  
66084 */
66085 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66086   pIn1 = &aMem[pOp->p1];
66087   if( (pIn1->flags & MEM_Null)==0 ){
66088     pc = pOp->p2 - 1;
66089   }
66090   break;
66091 }
66092
66093 /* Opcode: Column P1 P2 P3 P4 P5
66094 **
66095 ** Interpret the data that cursor P1 points to as a structure built using
66096 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66097 ** information about the format of the data.)  Extract the P2-th column
66098 ** from this record.  If there are less that (P2+1) 
66099 ** values in the record, extract a NULL.
66100 **
66101 ** The value extracted is stored in register P3.
66102 **
66103 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66104 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
66105 ** the result.
66106 **
66107 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66108 ** then the cache of the cursor is reset prior to extracting the column.
66109 ** The first OP_Column against a pseudo-table after the value of the content
66110 ** register has changed should have this bit set.
66111 **
66112 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
66113 ** the result is guaranteed to only be used as the argument of a length()
66114 ** or typeof() function, respectively.  The loading of large blobs can be
66115 ** skipped for length() and all content loading can be skipped for typeof().
66116 */
66117 case OP_Column: {
66118 #if 0  /* local variables moved into u.ao */
66119   u32 payloadSize;   /* Number of bytes in the record */
66120   i64 payloadSize64; /* Number of bytes in the record */
66121   int p1;            /* P1 value of the opcode */
66122   int p2;            /* column number to retrieve */
66123   VdbeCursor *pC;    /* The VDBE cursor */
66124   char *zRec;        /* Pointer to complete record-data */
66125   BtCursor *pCrsr;   /* The BTree cursor */
66126   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
66127   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
66128   int nField;        /* number of fields in the record */
66129   int len;           /* The length of the serialized data for the column */
66130   int i;             /* Loop counter */
66131   char *zData;       /* Part of the record being decoded */
66132   Mem *pDest;        /* Where to write the extracted value */
66133   Mem sMem;          /* For storing the record being decoded */
66134   u8 *zIdx;          /* Index into header */
66135   u8 *zEndHdr;       /* Pointer to first byte after the header */
66136   u32 offset;        /* Offset into the data */
66137   u32 szField;       /* Number of bytes in the content of a field */
66138   int szHdr;         /* Size of the header size field at start of record */
66139   int avail;         /* Number of bytes of available data */
66140   u32 t;             /* A type code from the record header */
66141   Mem *pReg;         /* PseudoTable input register */
66142 #endif /* local variables moved into u.ao */
66143
66144
66145   u.ao.p1 = pOp->p1;
66146   u.ao.p2 = pOp->p2;
66147   u.ao.pC = 0;
66148   memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
66149   assert( u.ao.p1<p->nCursor );
66150   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66151   u.ao.pDest = &aMem[pOp->p3];
66152   memAboutToChange(p, u.ao.pDest);
66153   u.ao.zRec = 0;
66154
66155   /* This block sets the variable u.ao.payloadSize to be the total number of
66156   ** bytes in the record.
66157   **
66158   ** u.ao.zRec is set to be the complete text of the record if it is available.
66159   ** The complete record text is always available for pseudo-tables
66160   ** If the record is stored in a cursor, the complete record text
66161   ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
66162   ** If the data is unavailable,  u.ao.zRec is set to NULL.
66163   **
66164   ** We also compute the number of columns in the record.  For cursors,
66165   ** the number of columns is stored in the VdbeCursor.nField element.
66166   */
66167   u.ao.pC = p->apCsr[u.ao.p1];
66168   assert( u.ao.pC!=0 );
66169 #ifndef SQLITE_OMIT_VIRTUALTABLE
66170   assert( u.ao.pC->pVtabCursor==0 );
66171 #endif
66172   u.ao.pCrsr = u.ao.pC->pCursor;
66173   if( u.ao.pCrsr!=0 ){
66174     /* The record is stored in a B-Tree */
66175     rc = sqlite3VdbeCursorMoveto(u.ao.pC);
66176     if( rc ) goto abort_due_to_error;
66177     if( u.ao.pC->nullRow ){
66178       u.ao.payloadSize = 0;
66179     }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
66180       u.ao.payloadSize = u.ao.pC->payloadSize;
66181       u.ao.zRec = (char*)u.ao.pC->aRow;
66182     }else if( u.ao.pC->isIndex ){
66183       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66184       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
66185       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
66186       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
66187       ** payload size, so it is impossible for u.ao.payloadSize64 to be
66188       ** larger than 32 bits. */
66189       assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
66190       u.ao.payloadSize = (u32)u.ao.payloadSize64;
66191     }else{
66192       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66193       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
66194       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
66195     }
66196   }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
66197     u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
66198     if( u.ao.pC->multiPseudo ){
66199       sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
66200       Deephemeralize(u.ao.pDest);
66201       goto op_column_out;
66202     }
66203     assert( u.ao.pReg->flags & MEM_Blob );
66204     assert( memIsValid(u.ao.pReg) );
66205     u.ao.payloadSize = u.ao.pReg->n;
66206     u.ao.zRec = u.ao.pReg->z;
66207     u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
66208     assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
66209   }else{
66210     /* Consider the row to be NULL */
66211     u.ao.payloadSize = 0;
66212   }
66213
66214   /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
66215   ** nullRow or because of a corrupt database. */
66216   if( u.ao.payloadSize==0 ){
66217     MemSetTypeFlag(u.ao.pDest, MEM_Null);
66218     goto op_column_out;
66219   }
66220   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
66221   if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66222     goto too_big;
66223   }
66224
66225   u.ao.nField = u.ao.pC->nField;
66226   assert( u.ao.p2<u.ao.nField );
66227
66228   /* Read and parse the table header.  Store the results of the parse
66229   ** into the record header cache fields of the cursor.
66230   */
66231   u.ao.aType = u.ao.pC->aType;
66232   if( u.ao.pC->cacheStatus==p->cacheCtr ){
66233     u.ao.aOffset = u.ao.pC->aOffset;
66234   }else{
66235     assert(u.ao.aType);
66236     u.ao.avail = 0;
66237     u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
66238     u.ao.pC->payloadSize = u.ao.payloadSize;
66239     u.ao.pC->cacheStatus = p->cacheCtr;
66240
66241     /* Figure out how many bytes are in the header */
66242     if( u.ao.zRec ){
66243       u.ao.zData = u.ao.zRec;
66244     }else{
66245       if( u.ao.pC->isIndex ){
66246         u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
66247       }else{
66248         u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
66249       }
66250       /* If KeyFetch()/DataFetch() managed to get the entire payload,
66251       ** save the payload in the u.ao.pC->aRow cache.  That will save us from
66252       ** having to make additional calls to fetch the content portion of
66253       ** the record.
66254       */
66255       assert( u.ao.avail>=0 );
66256       if( u.ao.payloadSize <= (u32)u.ao.avail ){
66257         u.ao.zRec = u.ao.zData;
66258         u.ao.pC->aRow = (u8*)u.ao.zData;
66259       }else{
66260         u.ao.pC->aRow = 0;
66261       }
66262     }
66263     /* The following assert is true in all cases except when
66264     ** the database file has been corrupted externally.
66265     **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
66266     u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
66267
66268     /* Make sure a corrupt database has not given us an oversize header.
66269     ** Do this now to avoid an oversize memory allocation.
66270     **
66271     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
66272     ** types use so much data space that there can only be 4096 and 32 of
66273     ** them, respectively.  So the maximum header length results from a
66274     ** 3-byte type for each of the maximum of 32768 columns plus three
66275     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
66276     */
66277     if( u.ao.offset > 98307 ){
66278       rc = SQLITE_CORRUPT_BKPT;
66279       goto op_column_out;
66280     }
66281
66282     /* Compute in u.ao.len the number of bytes of data we need to read in order
66283     ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
66284     ** u.ao.nField might be significantly less than the true number of columns
66285     ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
66286     ** We want to minimize u.ao.len in order to limit the size of the memory
66287     ** allocation, especially if a corrupt database file has caused u.ao.offset
66288     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
66289     ** still exceed Robson memory allocation limits on some configurations.
66290     ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
66291     ** will likely be much smaller since u.ao.nField will likely be less than
66292     ** 20 or so.  This insures that Robson memory allocation limits are
66293     ** not exceeded even for corrupt database files.
66294     */
66295     u.ao.len = u.ao.nField*5 + 3;
66296     if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
66297
66298     /* The KeyFetch() or DataFetch() above are fast and will get the entire
66299     ** record header in most cases.  But they will fail to get the complete
66300     ** record header if the record header does not fit on a single page
66301     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
66302     ** acquire the complete header text.
66303     */
66304     if( !u.ao.zRec && u.ao.avail<u.ao.len ){
66305       u.ao.sMem.flags = 0;
66306       u.ao.sMem.db = 0;
66307       rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
66308       if( rc!=SQLITE_OK ){
66309         goto op_column_out;
66310       }
66311       u.ao.zData = u.ao.sMem.z;
66312     }
66313     u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
66314     u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
66315
66316     /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
66317     ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
66318     ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
66319     ** of the record to the start of the data for the u.ao.i-th column
66320     */
66321     for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
66322       if( u.ao.zIdx<u.ao.zEndHdr ){
66323         u.ao.aOffset[u.ao.i] = u.ao.offset;
66324         if( u.ao.zIdx[0]<0x80 ){
66325           u.ao.t = u.ao.zIdx[0];
66326           u.ao.zIdx++;
66327         }else{
66328           u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
66329         }
66330         u.ao.aType[u.ao.i] = u.ao.t;
66331         u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
66332         u.ao.offset += u.ao.szField;
66333         if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
66334           u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
66335           break;
66336         }
66337       }else{
66338         /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
66339         ** record than SetNumColumns indicated there are columns in the
66340         ** table. Set the u.ao.offset for any extra columns not present in
66341         ** the record to 0. This tells code below to store the default value
66342         ** for the column instead of deserializing a value from the record.
66343         */
66344         u.ao.aOffset[u.ao.i] = 0;
66345       }
66346     }
66347     sqlite3VdbeMemRelease(&u.ao.sMem);
66348     u.ao.sMem.flags = MEM_Null;
66349
66350     /* If we have read more header data than was contained in the header,
66351     ** or if the end of the last field appears to be past the end of the
66352     ** record, or if the end of the last field appears to be before the end
66353     ** of the record (when all fields present), then we must be dealing
66354     ** with a corrupt database.
66355     */
66356     if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
66357          || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
66358       rc = SQLITE_CORRUPT_BKPT;
66359       goto op_column_out;
66360     }
66361   }
66362
66363   /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
66364   ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
66365   ** then there are not enough fields in the record to satisfy the
66366   ** request.  In this case, set the value NULL or to P4 if P4 is
66367   ** a pointer to a Mem object.
66368   */
66369   if( u.ao.aOffset[u.ao.p2] ){
66370     assert( rc==SQLITE_OK );
66371     if( u.ao.zRec ){
66372       /* This is the common case where the whole row fits on a single page */
66373       VdbeMemRelease(u.ao.pDest);
66374       sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
66375     }else{
66376       /* This branch happens only when the row overflows onto multiple pages */
66377       u.ao.t = u.ao.aType[u.ao.p2];
66378       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
66379        && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
66380       ){
66381         /* Content is irrelevant for the typeof() function and for
66382         ** the length(X) function if X is a blob.  So we might as well use
66383         ** bogus content rather than reading content from disk.  NULL works
66384         ** for text and blob and whatever is in the u.ao.payloadSize64 variable
66385         ** will work for everything else. */
66386         u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
66387       }else{
66388         u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
66389         sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
66390         rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
66391                                      &u.ao.sMem);
66392         if( rc!=SQLITE_OK ){
66393           goto op_column_out;
66394         }
66395         u.ao.zData = u.ao.sMem.z;
66396       }
66397       sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
66398     }
66399     u.ao.pDest->enc = encoding;
66400   }else{
66401     if( pOp->p4type==P4_MEM ){
66402       sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
66403     }else{
66404       MemSetTypeFlag(u.ao.pDest, MEM_Null);
66405     }
66406   }
66407
66408   /* If we dynamically allocated space to hold the data (in the
66409   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
66410   ** dynamically allocated space over to the u.ao.pDest structure.
66411   ** This prevents a memory copy.
66412   */
66413   if( u.ao.sMem.zMalloc ){
66414     assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
66415     assert( !(u.ao.pDest->flags & MEM_Dyn) );
66416     assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
66417     u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
66418     u.ao.pDest->flags |= MEM_Term;
66419     u.ao.pDest->z = u.ao.sMem.z;
66420     u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
66421   }
66422
66423   rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
66424
66425 op_column_out:
66426   UPDATE_MAX_BLOBSIZE(u.ao.pDest);
66427   REGISTER_TRACE(pOp->p3, u.ao.pDest);
66428   break;
66429 }
66430
66431 /* Opcode: Affinity P1 P2 * P4 *
66432 **
66433 ** Apply affinities to a range of P2 registers starting with P1.
66434 **
66435 ** P4 is a string that is P2 characters long. The nth character of the
66436 ** string indicates the column affinity that should be used for the nth
66437 ** memory cell in the range.
66438 */
66439 case OP_Affinity: {
66440 #if 0  /* local variables moved into u.ap */
66441   const char *zAffinity;   /* The affinity to be applied */
66442   char cAff;               /* A single character of affinity */
66443 #endif /* local variables moved into u.ap */
66444
66445   u.ap.zAffinity = pOp->p4.z;
66446   assert( u.ap.zAffinity!=0 );
66447   assert( u.ap.zAffinity[pOp->p2]==0 );
66448   pIn1 = &aMem[pOp->p1];
66449   while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
66450     assert( pIn1 <= &p->aMem[p->nMem] );
66451     assert( memIsValid(pIn1) );
66452     ExpandBlob(pIn1);
66453     applyAffinity(pIn1, u.ap.cAff, encoding);
66454     pIn1++;
66455   }
66456   break;
66457 }
66458
66459 /* Opcode: MakeRecord P1 P2 P3 P4 *
66460 **
66461 ** Convert P2 registers beginning with P1 into the [record format]
66462 ** use as a data record in a database table or as a key
66463 ** in an index.  The OP_Column opcode can decode the record later.
66464 **
66465 ** P4 may be a string that is P2 characters long.  The nth character of the
66466 ** string indicates the column affinity that should be used for the nth
66467 ** field of the index key.
66468 **
66469 ** The mapping from character to affinity is given by the SQLITE_AFF_
66470 ** macros defined in sqliteInt.h.
66471 **
66472 ** If P4 is NULL then all index fields have the affinity NONE.
66473 */
66474 case OP_MakeRecord: {
66475 #if 0  /* local variables moved into u.aq */
66476   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
66477   Mem *pRec;             /* The new record */
66478   u64 nData;             /* Number of bytes of data space */
66479   int nHdr;              /* Number of bytes of header space */
66480   i64 nByte;             /* Data space required for this record */
66481   int nZero;             /* Number of zero bytes at the end of the record */
66482   int nVarint;           /* Number of bytes in a varint */
66483   u32 serial_type;       /* Type field */
66484   Mem *pData0;           /* First field to be combined into the record */
66485   Mem *pLast;            /* Last field of the record */
66486   int nField;            /* Number of fields in the record */
66487   char *zAffinity;       /* The affinity string for the record */
66488   int file_format;       /* File format to use for encoding */
66489   int i;                 /* Space used in zNewRecord[] */
66490   int len;               /* Length of a field */
66491 #endif /* local variables moved into u.aq */
66492
66493   /* Assuming the record contains N fields, the record format looks
66494   ** like this:
66495   **
66496   ** ------------------------------------------------------------------------
66497   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
66498   ** ------------------------------------------------------------------------
66499   **
66500   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
66501   ** and so froth.
66502   **
66503   ** Each type field is a varint representing the serial type of the
66504   ** corresponding data element (see sqlite3VdbeSerialType()). The
66505   ** hdr-size field is also a varint which is the offset from the beginning
66506   ** of the record to data0.
66507   */
66508   u.aq.nData = 0;         /* Number of bytes of data space */
66509   u.aq.nHdr = 0;          /* Number of bytes of header space */
66510   u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
66511   u.aq.nField = pOp->p1;
66512   u.aq.zAffinity = pOp->p4.z;
66513   assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
66514   u.aq.pData0 = &aMem[u.aq.nField];
66515   u.aq.nField = pOp->p2;
66516   u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
66517   u.aq.file_format = p->minWriteFileFormat;
66518
66519   /* Identify the output register */
66520   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
66521   pOut = &aMem[pOp->p3];
66522   memAboutToChange(p, pOut);
66523
66524   /* Loop through the elements that will make up the record to figure
66525   ** out how much space is required for the new record.
66526   */
66527   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66528     assert( memIsValid(u.aq.pRec) );
66529     if( u.aq.zAffinity ){
66530       applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
66531     }
66532     if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
66533       sqlite3VdbeMemExpandBlob(u.aq.pRec);
66534     }
66535     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66536     u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
66537     u.aq.nData += u.aq.len;
66538     u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
66539     if( u.aq.pRec->flags & MEM_Zero ){
66540       /* Only pure zero-filled BLOBs can be input to this Opcode.
66541       ** We do not allow blobs with a prefix and a zero-filled tail. */
66542       u.aq.nZero += u.aq.pRec->u.nZero;
66543     }else if( u.aq.len ){
66544       u.aq.nZero = 0;
66545     }
66546   }
66547
66548   /* Add the initial header varint and total the size */
66549   u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
66550   if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
66551     u.aq.nHdr++;
66552   }
66553   u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
66554   if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66555     goto too_big;
66556   }
66557
66558   /* Make sure the output register has a buffer large enough to store
66559   ** the new record. The output register (pOp->p3) is not allowed to
66560   ** be one of the input registers (because the following call to
66561   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
66562   */
66563   if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
66564     goto no_mem;
66565   }
66566   u.aq.zNewRecord = (u8 *)pOut->z;
66567
66568   /* Write the record */
66569   u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
66570   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66571     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66572     u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
66573   }
66574   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
66575     u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
66576   }
66577   assert( u.aq.i==u.aq.nByte );
66578
66579   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66580   pOut->n = (int)u.aq.nByte;
66581   pOut->flags = MEM_Blob | MEM_Dyn;
66582   pOut->xDel = 0;
66583   if( u.aq.nZero ){
66584     pOut->u.nZero = u.aq.nZero;
66585     pOut->flags |= MEM_Zero;
66586   }
66587   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
66588   REGISTER_TRACE(pOp->p3, pOut);
66589   UPDATE_MAX_BLOBSIZE(pOut);
66590   break;
66591 }
66592
66593 /* Opcode: Count P1 P2 * * *
66594 **
66595 ** Store the number of entries (an integer value) in the table or index 
66596 ** opened by cursor P1 in register P2
66597 */
66598 #ifndef SQLITE_OMIT_BTREECOUNT
66599 case OP_Count: {         /* out2-prerelease */
66600 #if 0  /* local variables moved into u.ar */
66601   i64 nEntry;
66602   BtCursor *pCrsr;
66603 #endif /* local variables moved into u.ar */
66604
66605   u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
66606   if( ALWAYS(u.ar.pCrsr) ){
66607     rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
66608   }else{
66609     u.ar.nEntry = 0;
66610   }
66611   pOut->u.i = u.ar.nEntry;
66612   break;
66613 }
66614 #endif
66615
66616 /* Opcode: Savepoint P1 * * P4 *
66617 **
66618 ** Open, release or rollback the savepoint named by parameter P4, depending
66619 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66620 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66621 */
66622 case OP_Savepoint: {
66623 #if 0  /* local variables moved into u.as */
66624   int p1;                         /* Value of P1 operand */
66625   char *zName;                    /* Name of savepoint */
66626   int nName;
66627   Savepoint *pNew;
66628   Savepoint *pSavepoint;
66629   Savepoint *pTmp;
66630   int iSavepoint;
66631   int ii;
66632 #endif /* local variables moved into u.as */
66633
66634   u.as.p1 = pOp->p1;
66635   u.as.zName = pOp->p4.z;
66636
66637   /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
66638   ** transaction, then there cannot be any savepoints.
66639   */
66640   assert( db->pSavepoint==0 || db->autoCommit==0 );
66641   assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
66642   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66643   assert( checkSavepointCount(db) );
66644
66645   if( u.as.p1==SAVEPOINT_BEGIN ){
66646     if( db->writeVdbeCnt>0 ){
66647       /* A new savepoint cannot be created if there are active write
66648       ** statements (i.e. open read/write incremental blob handles).
66649       */
66650       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66651         "SQL statements in progress");
66652       rc = SQLITE_BUSY;
66653     }else{
66654       u.as.nName = sqlite3Strlen30(u.as.zName);
66655
66656 #ifndef SQLITE_OMIT_VIRTUALTABLE
66657       /* This call is Ok even if this savepoint is actually a transaction
66658       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66659       ** If this is a transaction savepoint being opened, it is guaranteed
66660       ** that the db->aVTrans[] array is empty.  */
66661       assert( db->autoCommit==0 || db->nVTrans==0 );
66662       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66663                                 db->nStatement+db->nSavepoint);
66664       if( rc!=SQLITE_OK ) goto abort_due_to_error;
66665 #endif
66666
66667       /* Create a new savepoint structure. */
66668       u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
66669       if( u.as.pNew ){
66670         u.as.pNew->zName = (char *)&u.as.pNew[1];
66671         memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
66672
66673         /* If there is no open transaction, then mark this as a special
66674         ** "transaction savepoint". */
66675         if( db->autoCommit ){
66676           db->autoCommit = 0;
66677           db->isTransactionSavepoint = 1;
66678         }else{
66679           db->nSavepoint++;
66680         }
66681
66682         /* Link the new savepoint into the database handle's list. */
66683         u.as.pNew->pNext = db->pSavepoint;
66684         db->pSavepoint = u.as.pNew;
66685         u.as.pNew->nDeferredCons = db->nDeferredCons;
66686       }
66687     }
66688   }else{
66689     u.as.iSavepoint = 0;
66690
66691     /* Find the named savepoint. If there is no such savepoint, then an
66692     ** an error is returned to the user.  */
66693     for(
66694       u.as.pSavepoint = db->pSavepoint;
66695       u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
66696       u.as.pSavepoint = u.as.pSavepoint->pNext
66697     ){
66698       u.as.iSavepoint++;
66699     }
66700     if( !u.as.pSavepoint ){
66701       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
66702       rc = SQLITE_ERROR;
66703     }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
66704       /* It is not possible to release (commit) a savepoint if there are
66705       ** active write statements.
66706       */
66707       sqlite3SetString(&p->zErrMsg, db,
66708         "cannot release savepoint - SQL statements in progress"
66709       );
66710       rc = SQLITE_BUSY;
66711     }else{
66712
66713       /* Determine whether or not this is a transaction savepoint. If so,
66714       ** and this is a RELEASE command, then the current transaction
66715       ** is committed.
66716       */
66717       int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66718       if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
66719         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66720           goto vdbe_return;
66721         }
66722         db->autoCommit = 1;
66723         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66724           p->pc = pc;
66725           db->autoCommit = 0;
66726           p->rc = rc = SQLITE_BUSY;
66727           goto vdbe_return;
66728         }
66729         db->isTransactionSavepoint = 0;
66730         rc = p->rc;
66731       }else{
66732         u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
66733         if( u.as.p1==SAVEPOINT_ROLLBACK ){
66734           for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66735             sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
66736           }
66737         }
66738         for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66739           rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
66740           if( rc!=SQLITE_OK ){
66741             goto abort_due_to_error;
66742           }
66743         }
66744         if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66745           sqlite3ExpirePreparedStatements(db);
66746           sqlite3ResetAllSchemasOfConnection(db);
66747           db->flags = (db->flags | SQLITE_InternChanges);
66748         }
66749       }
66750
66751       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66752       ** savepoints nested inside of the savepoint being operated on. */
66753       while( db->pSavepoint!=u.as.pSavepoint ){
66754         u.as.pTmp = db->pSavepoint;
66755         db->pSavepoint = u.as.pTmp->pNext;
66756         sqlite3DbFree(db, u.as.pTmp);
66757         db->nSavepoint--;
66758       }
66759
66760       /* If it is a RELEASE, then destroy the savepoint being operated on
66761       ** too. If it is a ROLLBACK TO, then set the number of deferred
66762       ** constraint violations present in the database to the value stored
66763       ** when the savepoint was created.  */
66764       if( u.as.p1==SAVEPOINT_RELEASE ){
66765         assert( u.as.pSavepoint==db->pSavepoint );
66766         db->pSavepoint = u.as.pSavepoint->pNext;
66767         sqlite3DbFree(db, u.as.pSavepoint);
66768         if( !isTransaction ){
66769           db->nSavepoint--;
66770         }
66771       }else{
66772         db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
66773       }
66774
66775       if( !isTransaction ){
66776         rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
66777         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66778       }
66779     }
66780   }
66781
66782   break;
66783 }
66784
66785 /* Opcode: AutoCommit P1 P2 * * *
66786 **
66787 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66788 ** back any currently active btree transactions. If there are any active
66789 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
66790 ** there are active writing VMs or active VMs that use shared cache.
66791 **
66792 ** This instruction causes the VM to halt.
66793 */
66794 case OP_AutoCommit: {
66795 #if 0  /* local variables moved into u.at */
66796   int desiredAutoCommit;
66797   int iRollback;
66798   int turnOnAC;
66799 #endif /* local variables moved into u.at */
66800
66801   u.at.desiredAutoCommit = pOp->p1;
66802   u.at.iRollback = pOp->p2;
66803   u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
66804   assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
66805   assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
66806   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
66807
66808 #if 0
66809   if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
66810     /* If this instruction implements a ROLLBACK and other VMs are
66811     ** still running, and a transaction is active, return an error indicating
66812     ** that the other VMs must complete first.
66813     */
66814     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66815         "SQL statements in progress");
66816     rc = SQLITE_BUSY;
66817   }else
66818 #endif
66819   if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
66820     /* If this instruction implements a COMMIT and other VMs are writing
66821     ** return an error indicating that the other VMs must complete first.
66822     */
66823     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66824         "SQL statements in progress");
66825     rc = SQLITE_BUSY;
66826   }else if( u.at.desiredAutoCommit!=db->autoCommit ){
66827     if( u.at.iRollback ){
66828       assert( u.at.desiredAutoCommit==1 );
66829       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
66830       db->autoCommit = 1;
66831     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66832       goto vdbe_return;
66833     }else{
66834       db->autoCommit = (u8)u.at.desiredAutoCommit;
66835       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66836         p->pc = pc;
66837         db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
66838         p->rc = rc = SQLITE_BUSY;
66839         goto vdbe_return;
66840       }
66841     }
66842     assert( db->nStatement==0 );
66843     sqlite3CloseSavepoints(db);
66844     if( p->rc==SQLITE_OK ){
66845       rc = SQLITE_DONE;
66846     }else{
66847       rc = SQLITE_ERROR;
66848     }
66849     goto vdbe_return;
66850   }else{
66851     sqlite3SetString(&p->zErrMsg, db,
66852         (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
66853         (u.at.iRollback)?"cannot rollback - no transaction is active":
66854                    "cannot commit - no transaction is active"));
66855
66856     rc = SQLITE_ERROR;
66857   }
66858   break;
66859 }
66860
66861 /* Opcode: Transaction P1 P2 * * *
66862 **
66863 ** Begin a transaction.  The transaction ends when a Commit or Rollback
66864 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
66865 ** transaction might also be rolled back if an error is encountered.
66866 **
66867 ** P1 is the index of the database file on which the transaction is
66868 ** started.  Index 0 is the main database file and index 1 is the
66869 ** file used for temporary tables.  Indices of 2 or more are used for
66870 ** attached databases.
66871 **
66872 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
66873 ** obtained on the database file when a write-transaction is started.  No
66874 ** other process can start another write transaction while this transaction is
66875 ** underway.  Starting a write transaction also creates a rollback journal. A
66876 ** write transaction must be started before any changes can be made to the
66877 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
66878 ** on the file.
66879 **
66880 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
66881 ** true (this flag is set if the Vdbe may modify more than one row and may
66882 ** throw an ABORT exception), a statement transaction may also be opened.
66883 ** More specifically, a statement transaction is opened iff the database
66884 ** connection is currently not in autocommit mode, or if there are other
66885 ** active statements. A statement transaction allows the changes made by this
66886 ** VDBE to be rolled back after an error without having to roll back the
66887 ** entire transaction. If no error is encountered, the statement transaction
66888 ** will automatically commit when the VDBE halts.
66889 **
66890 ** If P2 is zero, then a read-lock is obtained on the database file.
66891 */
66892 case OP_Transaction: {
66893 #if 0  /* local variables moved into u.au */
66894   Btree *pBt;
66895 #endif /* local variables moved into u.au */
66896
66897   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66898   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66899   u.au.pBt = db->aDb[pOp->p1].pBt;
66900
66901   if( u.au.pBt ){
66902     rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
66903     if( rc==SQLITE_BUSY ){
66904       p->pc = pc;
66905       p->rc = rc = SQLITE_BUSY;
66906       goto vdbe_return;
66907     }
66908     if( rc!=SQLITE_OK ){
66909       goto abort_due_to_error;
66910     }
66911
66912     if( pOp->p2 && p->usesStmtJournal
66913      && (db->autoCommit==0 || db->activeVdbeCnt>1)
66914     ){
66915       assert( sqlite3BtreeIsInTrans(u.au.pBt) );
66916       if( p->iStatement==0 ){
66917         assert( db->nStatement>=0 && db->nSavepoint>=0 );
66918         db->nStatement++;
66919         p->iStatement = db->nSavepoint + db->nStatement;
66920       }
66921
66922       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
66923       if( rc==SQLITE_OK ){
66924         rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
66925       }
66926
66927       /* Store the current value of the database handles deferred constraint
66928       ** counter. If the statement transaction needs to be rolled back,
66929       ** the value of this counter needs to be restored too.  */
66930       p->nStmtDefCons = db->nDeferredCons;
66931     }
66932   }
66933   break;
66934 }
66935
66936 /* Opcode: ReadCookie P1 P2 P3 * *
66937 **
66938 ** Read cookie number P3 from database P1 and write it into register P2.
66939 ** P3==1 is the schema version.  P3==2 is the database format.
66940 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
66941 ** the main database file and P1==1 is the database file used to store
66942 ** temporary tables.
66943 **
66944 ** There must be a read-lock on the database (either a transaction
66945 ** must be started or there must be an open cursor) before
66946 ** executing this instruction.
66947 */
66948 case OP_ReadCookie: {               /* out2-prerelease */
66949 #if 0  /* local variables moved into u.av */
66950   int iMeta;
66951   int iDb;
66952   int iCookie;
66953 #endif /* local variables moved into u.av */
66954
66955   u.av.iDb = pOp->p1;
66956   u.av.iCookie = pOp->p3;
66957   assert( pOp->p3<SQLITE_N_BTREE_META );
66958   assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
66959   assert( db->aDb[u.av.iDb].pBt!=0 );
66960   assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
66961
66962   sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
66963   pOut->u.i = u.av.iMeta;
66964   break;
66965 }
66966
66967 /* Opcode: SetCookie P1 P2 P3 * *
66968 **
66969 ** Write the content of register P3 (interpreted as an integer)
66970 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
66971 ** P2==2 is the database format. P2==3 is the recommended pager cache 
66972 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
66973 ** database file used to store temporary tables.
66974 **
66975 ** A transaction must be started before executing this opcode.
66976 */
66977 case OP_SetCookie: {       /* in3 */
66978 #if 0  /* local variables moved into u.aw */
66979   Db *pDb;
66980 #endif /* local variables moved into u.aw */
66981   assert( pOp->p2<SQLITE_N_BTREE_META );
66982   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66983   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66984   u.aw.pDb = &db->aDb[pOp->p1];
66985   assert( u.aw.pDb->pBt!=0 );
66986   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66987   pIn3 = &aMem[pOp->p3];
66988   sqlite3VdbeMemIntegerify(pIn3);
66989   /* See note about index shifting on OP_ReadCookie */
66990   rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
66991   if( pOp->p2==BTREE_SCHEMA_VERSION ){
66992     /* When the schema cookie changes, record the new cookie internally */
66993     u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
66994     db->flags |= SQLITE_InternChanges;
66995   }else if( pOp->p2==BTREE_FILE_FORMAT ){
66996     /* Record changes in the file format */
66997     u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
66998   }
66999   if( pOp->p1==1 ){
67000     /* Invalidate all prepared statements whenever the TEMP database
67001     ** schema is changed.  Ticket #1644 */
67002     sqlite3ExpirePreparedStatements(db);
67003     p->expired = 0;
67004   }
67005   break;
67006 }
67007
67008 /* Opcode: VerifyCookie P1 P2 P3 * *
67009 **
67010 ** Check the value of global database parameter number 0 (the
67011 ** schema version) and make sure it is equal to P2 and that the
67012 ** generation counter on the local schema parse equals P3.
67013 **
67014 ** P1 is the database number which is 0 for the main database file
67015 ** and 1 for the file holding temporary tables and some higher number
67016 ** for auxiliary databases.
67017 **
67018 ** The cookie changes its value whenever the database schema changes.
67019 ** This operation is used to detect when that the cookie has changed
67020 ** and that the current process needs to reread the schema.
67021 **
67022 ** Either a transaction needs to have been started or an OP_Open needs
67023 ** to be executed (to establish a read lock) before this opcode is
67024 ** invoked.
67025 */
67026 case OP_VerifyCookie: {
67027 #if 0  /* local variables moved into u.ax */
67028   int iMeta;
67029   int iGen;
67030   Btree *pBt;
67031 #endif /* local variables moved into u.ax */
67032
67033   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67034   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67035   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67036   u.ax.pBt = db->aDb[pOp->p1].pBt;
67037   if( u.ax.pBt ){
67038     sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
67039     u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67040   }else{
67041     u.ax.iGen = u.ax.iMeta = 0;
67042   }
67043   if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
67044     sqlite3DbFree(db, p->zErrMsg);
67045     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
67046     /* If the schema-cookie from the database file matches the cookie
67047     ** stored with the in-memory representation of the schema, do
67048     ** not reload the schema from the database file.
67049     **
67050     ** If virtual-tables are in use, this is not just an optimization.
67051     ** Often, v-tables store their data in other SQLite tables, which
67052     ** are queried from within xNext() and other v-table methods using
67053     ** prepared queries. If such a query is out-of-date, we do not want to
67054     ** discard the database schema, as the user code implementing the
67055     ** v-table would have to be ready for the sqlite3_vtab structure itself
67056     ** to be invalidated whenever sqlite3_step() is called from within
67057     ** a v-table method.
67058     */
67059     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
67060       sqlite3ResetOneSchema(db, pOp->p1);
67061     }
67062
67063     p->expired = 1;
67064     rc = SQLITE_SCHEMA;
67065   }
67066   break;
67067 }
67068
67069 /* Opcode: OpenRead P1 P2 P3 P4 P5
67070 **
67071 ** Open a read-only cursor for the database table whose root page is
67072 ** P2 in a database file.  The database file is determined by P3. 
67073 ** P3==0 means the main database, P3==1 means the database used for 
67074 ** temporary tables, and P3>1 means used the corresponding attached
67075 ** database.  Give the new cursor an identifier of P1.  The P1
67076 ** values need not be contiguous but all P1 values should be small integers.
67077 ** It is an error for P1 to be negative.
67078 **
67079 ** If P5!=0 then use the content of register P2 as the root page, not
67080 ** the value of P2 itself.
67081 **
67082 ** There will be a read lock on the database whenever there is an
67083 ** open cursor.  If the database was unlocked prior to this instruction
67084 ** then a read lock is acquired as part of this instruction.  A read
67085 ** lock allows other processes to read the database but prohibits
67086 ** any other process from modifying the database.  The read lock is
67087 ** released when all cursors are closed.  If this instruction attempts
67088 ** to get a read lock but fails, the script terminates with an
67089 ** SQLITE_BUSY error code.
67090 **
67091 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67092 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67093 ** structure, then said structure defines the content and collating 
67094 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67095 ** value, it is set to the number of columns in the table.
67096 **
67097 ** See also OpenWrite.
67098 */
67099 /* Opcode: OpenWrite P1 P2 P3 P4 P5
67100 **
67101 ** Open a read/write cursor named P1 on the table or index whose root
67102 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
67103 ** root page.
67104 **
67105 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67106 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
67107 ** structure, then said structure defines the content and collating 
67108 ** sequence of the index being opened. Otherwise, if P4 is an integer 
67109 ** value, it is set to the number of columns in the table, or to the
67110 ** largest index of any column of the table that is actually used.
67111 **
67112 ** This instruction works just like OpenRead except that it opens the cursor
67113 ** in read/write mode.  For a given table, there can be one or more read-only
67114 ** cursors or a single read/write cursor but not both.
67115 **
67116 ** See also OpenRead.
67117 */
67118 case OP_OpenRead:
67119 case OP_OpenWrite: {
67120 #if 0  /* local variables moved into u.ay */
67121   int nField;
67122   KeyInfo *pKeyInfo;
67123   int p2;
67124   int iDb;
67125   int wrFlag;
67126   Btree *pX;
67127   VdbeCursor *pCur;
67128   Db *pDb;
67129 #endif /* local variables moved into u.ay */
67130
67131   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
67132   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
67133
67134   if( p->expired ){
67135     rc = SQLITE_ABORT;
67136     break;
67137   }
67138
67139   u.ay.nField = 0;
67140   u.ay.pKeyInfo = 0;
67141   u.ay.p2 = pOp->p2;
67142   u.ay.iDb = pOp->p3;
67143   assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
67144   assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
67145   u.ay.pDb = &db->aDb[u.ay.iDb];
67146   u.ay.pX = u.ay.pDb->pBt;
67147   assert( u.ay.pX!=0 );
67148   if( pOp->opcode==OP_OpenWrite ){
67149     u.ay.wrFlag = 1;
67150     assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
67151     if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
67152       p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
67153     }
67154   }else{
67155     u.ay.wrFlag = 0;
67156   }
67157   if( pOp->p5 & OPFLAG_P2ISREG ){
67158     assert( u.ay.p2>0 );
67159     assert( u.ay.p2<=p->nMem );
67160     pIn2 = &aMem[u.ay.p2];
67161     assert( memIsValid(pIn2) );
67162     assert( (pIn2->flags & MEM_Int)!=0 );
67163     sqlite3VdbeMemIntegerify(pIn2);
67164     u.ay.p2 = (int)pIn2->u.i;
67165     /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
67166     ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
67167     ** If there were a failure, the prepared statement would have halted
67168     ** before reaching this instruction. */
67169     if( NEVER(u.ay.p2<2) ) {
67170       rc = SQLITE_CORRUPT_BKPT;
67171       goto abort_due_to_error;
67172     }
67173   }
67174   if( pOp->p4type==P4_KEYINFO ){
67175     u.ay.pKeyInfo = pOp->p4.pKeyInfo;
67176     u.ay.pKeyInfo->enc = ENC(p->db);
67177     u.ay.nField = u.ay.pKeyInfo->nField+1;
67178   }else if( pOp->p4type==P4_INT32 ){
67179     u.ay.nField = pOp->p4.i;
67180   }
67181   assert( pOp->p1>=0 );
67182   u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
67183   if( u.ay.pCur==0 ) goto no_mem;
67184   u.ay.pCur->nullRow = 1;
67185   u.ay.pCur->isOrdered = 1;
67186   rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
67187   u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
67188   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
67189   sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
67190
67191   /* Since it performs no memory allocation or IO, the only value that
67192   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
67193   assert( rc==SQLITE_OK );
67194
67195   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
67196   ** SQLite used to check if the root-page flags were sane at this point
67197   ** and report database corruption if they were not, but this check has
67198   ** since moved into the btree layer.  */
67199   u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
67200   u.ay.pCur->isIndex = !u.ay.pCur->isTable;
67201   break;
67202 }
67203
67204 /* Opcode: OpenEphemeral P1 P2 * P4 P5
67205 **
67206 ** Open a new cursor P1 to a transient table.
67207 ** The cursor is always opened read/write even if 
67208 ** the main database is read-only.  The ephemeral
67209 ** table is deleted automatically when the cursor is closed.
67210 **
67211 ** P2 is the number of columns in the ephemeral table.
67212 ** The cursor points to a BTree table if P4==0 and to a BTree index
67213 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
67214 ** that defines the format of keys in the index.
67215 **
67216 ** This opcode was once called OpenTemp.  But that created
67217 ** confusion because the term "temp table", might refer either
67218 ** to a TEMP table at the SQL level, or to a table opened by
67219 ** this opcode.  Then this opcode was call OpenVirtual.  But
67220 ** that created confusion with the whole virtual-table idea.
67221 **
67222 ** The P5 parameter can be a mask of the BTREE_* flags defined
67223 ** in btree.h.  These flags control aspects of the operation of
67224 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
67225 ** added automatically.
67226 */
67227 /* Opcode: OpenAutoindex P1 P2 * P4 *
67228 **
67229 ** This opcode works the same as OP_OpenEphemeral.  It has a
67230 ** different name to distinguish its use.  Tables created using
67231 ** by this opcode will be used for automatically created transient
67232 ** indices in joins.
67233 */
67234 case OP_OpenAutoindex: 
67235 case OP_OpenEphemeral: {
67236 #if 0  /* local variables moved into u.az */
67237   VdbeCursor *pCx;
67238 #endif /* local variables moved into u.az */
67239   static const int vfsFlags =
67240       SQLITE_OPEN_READWRITE |
67241       SQLITE_OPEN_CREATE |
67242       SQLITE_OPEN_EXCLUSIVE |
67243       SQLITE_OPEN_DELETEONCLOSE |
67244       SQLITE_OPEN_TRANSIENT_DB;
67245
67246   assert( pOp->p1>=0 );
67247   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67248   if( u.az.pCx==0 ) goto no_mem;
67249   u.az.pCx->nullRow = 1;
67250   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
67251                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
67252   if( rc==SQLITE_OK ){
67253     rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
67254   }
67255   if( rc==SQLITE_OK ){
67256     /* If a transient index is required, create it by calling
67257     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
67258     ** opening it. If a transient table is required, just use the
67259     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
67260     */
67261     if( pOp->p4.pKeyInfo ){
67262       int pgno;
67263       assert( pOp->p4type==P4_KEYINFO );
67264       rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
67265       if( rc==SQLITE_OK ){
67266         assert( pgno==MASTER_ROOT+1 );
67267         rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
67268                                 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
67269         u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67270         u.az.pCx->pKeyInfo->enc = ENC(p->db);
67271       }
67272       u.az.pCx->isTable = 0;
67273     }else{
67274       rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
67275       u.az.pCx->isTable = 1;
67276     }
67277   }
67278   u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
67279   u.az.pCx->isIndex = !u.az.pCx->isTable;
67280   break;
67281 }
67282
67283 /* Opcode: SorterOpen P1 P2 * P4 *
67284 **
67285 ** This opcode works like OP_OpenEphemeral except that it opens
67286 ** a transient index that is specifically designed to sort large
67287 ** tables using an external merge-sort algorithm.
67288 */
67289 case OP_SorterOpen: {
67290 #if 0  /* local variables moved into u.ba */
67291   VdbeCursor *pCx;
67292 #endif /* local variables moved into u.ba */
67293
67294 #ifndef SQLITE_OMIT_MERGE_SORT
67295   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67296   if( u.ba.pCx==0 ) goto no_mem;
67297   u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67298   u.ba.pCx->pKeyInfo->enc = ENC(p->db);
67299   u.ba.pCx->isSorter = 1;
67300   rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
67301 #else
67302   pOp->opcode = OP_OpenEphemeral;
67303   pc--;
67304 #endif
67305   break;
67306 }
67307
67308 /* Opcode: OpenPseudo P1 P2 P3 * P5
67309 **
67310 ** Open a new cursor that points to a fake table that contains a single
67311 ** row of data.  The content of that one row in the content of memory
67312 ** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the 
67313 ** MEM_Blob content contained in register P2.  When P5==1, then the
67314 ** row is represented by P3 consecutive registers beginning with P2.
67315 **
67316 ** A pseudo-table created by this opcode is used to hold a single
67317 ** row output from the sorter so that the row can be decomposed into
67318 ** individual columns using the OP_Column opcode.  The OP_Column opcode
67319 ** is the only cursor opcode that works with a pseudo-table.
67320 **
67321 ** P3 is the number of fields in the records that will be stored by
67322 ** the pseudo-table.
67323 */
67324 case OP_OpenPseudo: {
67325 #if 0  /* local variables moved into u.bb */
67326   VdbeCursor *pCx;
67327 #endif /* local variables moved into u.bb */
67328
67329   assert( pOp->p1>=0 );
67330   u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
67331   if( u.bb.pCx==0 ) goto no_mem;
67332   u.bb.pCx->nullRow = 1;
67333   u.bb.pCx->pseudoTableReg = pOp->p2;
67334   u.bb.pCx->isTable = 1;
67335   u.bb.pCx->isIndex = 0;
67336   u.bb.pCx->multiPseudo = pOp->p5;
67337   break;
67338 }
67339
67340 /* Opcode: Close P1 * * * *
67341 **
67342 ** Close a cursor previously opened as P1.  If P1 is not
67343 ** currently open, this instruction is a no-op.
67344 */
67345 case OP_Close: {
67346   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67347   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
67348   p->apCsr[pOp->p1] = 0;
67349   break;
67350 }
67351
67352 /* Opcode: SeekGe P1 P2 P3 P4 *
67353 **
67354 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67355 ** use the value in register P3 as the key.  If cursor P1 refers 
67356 ** to an SQL index, then P3 is the first in an array of P4 registers 
67357 ** that are used as an unpacked index key. 
67358 **
67359 ** Reposition cursor P1 so that  it points to the smallest entry that 
67360 ** is greater than or equal to the key value. If there are no records 
67361 ** greater than or equal to the key and P2 is not zero, then jump to P2.
67362 **
67363 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
67364 */
67365 /* Opcode: SeekGt P1 P2 P3 P4 *
67366 **
67367 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67368 ** use the value in register P3 as a key. If cursor P1 refers 
67369 ** to an SQL index, then P3 is the first in an array of P4 registers 
67370 ** that are used as an unpacked index key. 
67371 **
67372 ** Reposition cursor P1 so that  it points to the smallest entry that 
67373 ** is greater than the key value. If there are no records greater than 
67374 ** the key and P2 is not zero, then jump to P2.
67375 **
67376 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
67377 */
67378 /* Opcode: SeekLt P1 P2 P3 P4 * 
67379 **
67380 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67381 ** use the value in register P3 as a key. If cursor P1 refers 
67382 ** to an SQL index, then P3 is the first in an array of P4 registers 
67383 ** that are used as an unpacked index key. 
67384 **
67385 ** Reposition cursor P1 so that  it points to the largest entry that 
67386 ** is less than the key value. If there are no records less than 
67387 ** the key and P2 is not zero, then jump to P2.
67388 **
67389 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
67390 */
67391 /* Opcode: SeekLe P1 P2 P3 P4 *
67392 **
67393 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
67394 ** use the value in register P3 as a key. If cursor P1 refers 
67395 ** to an SQL index, then P3 is the first in an array of P4 registers 
67396 ** that are used as an unpacked index key. 
67397 **
67398 ** Reposition cursor P1 so that it points to the largest entry that 
67399 ** is less than or equal to the key value. If there are no records 
67400 ** less than or equal to the key and P2 is not zero, then jump to P2.
67401 **
67402 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
67403 */
67404 case OP_SeekLt:         /* jump, in3 */
67405 case OP_SeekLe:         /* jump, in3 */
67406 case OP_SeekGe:         /* jump, in3 */
67407 case OP_SeekGt: {       /* jump, in3 */
67408 #if 0  /* local variables moved into u.bc */
67409   int res;
67410   int oc;
67411   VdbeCursor *pC;
67412   UnpackedRecord r;
67413   int nField;
67414   i64 iKey;      /* The rowid we are to seek to */
67415 #endif /* local variables moved into u.bc */
67416
67417   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67418   assert( pOp->p2!=0 );
67419   u.bc.pC = p->apCsr[pOp->p1];
67420   assert( u.bc.pC!=0 );
67421   assert( u.bc.pC->pseudoTableReg==0 );
67422   assert( OP_SeekLe == OP_SeekLt+1 );
67423   assert( OP_SeekGe == OP_SeekLt+2 );
67424   assert( OP_SeekGt == OP_SeekLt+3 );
67425   assert( u.bc.pC->isOrdered );
67426   if( ALWAYS(u.bc.pC->pCursor!=0) ){
67427     u.bc.oc = pOp->opcode;
67428     u.bc.pC->nullRow = 0;
67429     if( u.bc.pC->isTable ){
67430       /* The input value in P3 might be of any type: integer, real, string,
67431       ** blob, or NULL.  But it needs to be an integer before we can do
67432       ** the seek, so covert it. */
67433       pIn3 = &aMem[pOp->p3];
67434       applyNumericAffinity(pIn3);
67435       u.bc.iKey = sqlite3VdbeIntValue(pIn3);
67436       u.bc.pC->rowidIsValid = 0;
67437
67438       /* If the P3 value could not be converted into an integer without
67439       ** loss of information, then special processing is required... */
67440       if( (pIn3->flags & MEM_Int)==0 ){
67441         if( (pIn3->flags & MEM_Real)==0 ){
67442           /* If the P3 value cannot be converted into any kind of a number,
67443           ** then the seek is not possible, so jump to P2 */
67444           pc = pOp->p2 - 1;
67445           break;
67446         }
67447         /* If we reach this point, then the P3 value must be a floating
67448         ** point number. */
67449         assert( (pIn3->flags & MEM_Real)!=0 );
67450
67451         if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
67452           /* The P3 value is too large in magnitude to be expressed as an
67453           ** integer. */
67454           u.bc.res = 1;
67455           if( pIn3->r<0 ){
67456             if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67457               rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
67458               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67459             }
67460           }else{
67461             if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67462               rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
67463               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67464             }
67465           }
67466           if( u.bc.res ){
67467             pc = pOp->p2 - 1;
67468           }
67469           break;
67470         }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
67471           /* Use the ceiling() function to convert real->int */
67472           if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
67473         }else{
67474           /* Use the floor() function to convert real->int */
67475           assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
67476           if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
67477         }
67478       }
67479       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
67480       if( rc!=SQLITE_OK ){
67481         goto abort_due_to_error;
67482       }
67483       if( u.bc.res==0 ){
67484         u.bc.pC->rowidIsValid = 1;
67485         u.bc.pC->lastRowid = u.bc.iKey;
67486       }
67487     }else{
67488       u.bc.nField = pOp->p4.i;
67489       assert( pOp->p4type==P4_INT32 );
67490       assert( u.bc.nField>0 );
67491       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
67492       u.bc.r.nField = (u16)u.bc.nField;
67493
67494       /* The next line of code computes as follows, only faster:
67495       **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
67496       **     u.bc.r.flags = UNPACKED_INCRKEY;
67497       **   }else{
67498       **     u.bc.r.flags = 0;
67499       **   }
67500       */
67501       u.bc.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
67502       assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
67503       assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
67504       assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
67505       assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
67506
67507       u.bc.r.aMem = &aMem[pOp->p3];
67508 #ifdef SQLITE_DEBUG
67509       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
67510 #endif
67511       ExpandBlob(u.bc.r.aMem);
67512       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
67513       if( rc!=SQLITE_OK ){
67514         goto abort_due_to_error;
67515       }
67516       u.bc.pC->rowidIsValid = 0;
67517     }
67518     u.bc.pC->deferredMoveto = 0;
67519     u.bc.pC->cacheStatus = CACHE_STALE;
67520 #ifdef SQLITE_TEST
67521     sqlite3_search_count++;
67522 #endif
67523     if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67524       if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
67525         rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
67526         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67527         u.bc.pC->rowidIsValid = 0;
67528       }else{
67529         u.bc.res = 0;
67530       }
67531     }else{
67532       assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67533       if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
67534         rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
67535         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67536         u.bc.pC->rowidIsValid = 0;
67537       }else{
67538         /* u.bc.res might be negative because the table is empty.  Check to
67539         ** see if this is the case.
67540         */
67541         u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
67542       }
67543     }
67544     assert( pOp->p2>0 );
67545     if( u.bc.res ){
67546       pc = pOp->p2 - 1;
67547     }
67548   }else{
67549     /* This happens when attempting to open the sqlite3_master table
67550     ** for read access returns SQLITE_EMPTY. In this case always
67551     ** take the jump (since there are no records in the table).
67552     */
67553     pc = pOp->p2 - 1;
67554   }
67555   break;
67556 }
67557
67558 /* Opcode: Seek P1 P2 * * *
67559 **
67560 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
67561 ** for P1 to move so that it points to the rowid given by P2.
67562 **
67563 ** This is actually a deferred seek.  Nothing actually happens until
67564 ** the cursor is used to read a record.  That way, if no reads
67565 ** occur, no unnecessary I/O happens.
67566 */
67567 case OP_Seek: {    /* in2 */
67568 #if 0  /* local variables moved into u.bd */
67569   VdbeCursor *pC;
67570 #endif /* local variables moved into u.bd */
67571
67572   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67573   u.bd.pC = p->apCsr[pOp->p1];
67574   assert( u.bd.pC!=0 );
67575   if( ALWAYS(u.bd.pC->pCursor!=0) ){
67576     assert( u.bd.pC->isTable );
67577     u.bd.pC->nullRow = 0;
67578     pIn2 = &aMem[pOp->p2];
67579     u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
67580     u.bd.pC->rowidIsValid = 0;
67581     u.bd.pC->deferredMoveto = 1;
67582   }
67583   break;
67584 }
67585   
67586
67587 /* Opcode: Found P1 P2 P3 P4 *
67588 **
67589 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67590 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67591 ** record.
67592 **
67593 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67594 ** is a prefix of any entry in P1 then a jump is made to P2 and
67595 ** P1 is left pointing at the matching entry.
67596 */
67597 /* Opcode: NotFound P1 P2 P3 P4 *
67598 **
67599 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67600 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67601 ** record.
67602 ** 
67603 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67604 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
67605 ** does contain an entry whose prefix matches the P3/P4 record then control
67606 ** falls through to the next instruction and P1 is left pointing at the
67607 ** matching entry.
67608 **
67609 ** See also: Found, NotExists, IsUnique
67610 */
67611 case OP_NotFound:       /* jump, in3 */
67612 case OP_Found: {        /* jump, in3 */
67613 #if 0  /* local variables moved into u.be */
67614   int alreadyExists;
67615   VdbeCursor *pC;
67616   int res;
67617   char *pFree;
67618   UnpackedRecord *pIdxKey;
67619   UnpackedRecord r;
67620   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67621 #endif /* local variables moved into u.be */
67622
67623 #ifdef SQLITE_TEST
67624   sqlite3_found_count++;
67625 #endif
67626
67627   u.be.alreadyExists = 0;
67628   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67629   assert( pOp->p4type==P4_INT32 );
67630   u.be.pC = p->apCsr[pOp->p1];
67631   assert( u.be.pC!=0 );
67632   pIn3 = &aMem[pOp->p3];
67633   if( ALWAYS(u.be.pC->pCursor!=0) ){
67634
67635     assert( u.be.pC->isTable==0 );
67636     if( pOp->p4.i>0 ){
67637       u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
67638       u.be.r.nField = (u16)pOp->p4.i;
67639       u.be.r.aMem = pIn3;
67640 #ifdef SQLITE_DEBUG
67641       { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
67642 #endif
67643       u.be.r.flags = UNPACKED_PREFIX_MATCH;
67644       u.be.pIdxKey = &u.be.r;
67645     }else{
67646       u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67647           u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
67648       );
67649       if( u.be.pIdxKey==0 ) goto no_mem;
67650       assert( pIn3->flags & MEM_Blob );
67651       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
67652       sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
67653       u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67654     }
67655     rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
67656     if( pOp->p4.i==0 ){
67657       sqlite3DbFree(db, u.be.pFree);
67658     }
67659     if( rc!=SQLITE_OK ){
67660       break;
67661     }
67662     u.be.alreadyExists = (u.be.res==0);
67663     u.be.pC->deferredMoveto = 0;
67664     u.be.pC->cacheStatus = CACHE_STALE;
67665   }
67666   if( pOp->opcode==OP_Found ){
67667     if( u.be.alreadyExists ) pc = pOp->p2 - 1;
67668   }else{
67669     if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
67670   }
67671   break;
67672 }
67673
67674 /* Opcode: IsUnique P1 P2 P3 P4 *
67675 **
67676 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67677 ** no data and where the key are records generated by OP_MakeRecord with
67678 ** the list field being the integer ROWID of the entry that the index
67679 ** entry refers to.
67680 **
67681 ** The P3 register contains an integer record number. Call this record 
67682 ** number R. Register P4 is the first in a set of N contiguous registers
67683 ** that make up an unpacked index key that can be used with cursor P1.
67684 ** The value of N can be inferred from the cursor. N includes the rowid
67685 ** value appended to the end of the index record. This rowid value may
67686 ** or may not be the same as R.
67687 **
67688 ** If any of the N registers beginning with register P4 contains a NULL
67689 ** value, jump immediately to P2.
67690 **
67691 ** Otherwise, this instruction checks if cursor P1 contains an entry
67692 ** where the first (N-1) fields match but the rowid value at the end
67693 ** of the index entry is not R. If there is no such entry, control jumps
67694 ** to instruction P2. Otherwise, the rowid of the conflicting index
67695 ** entry is copied to register P3 and control falls through to the next
67696 ** instruction.
67697 **
67698 ** See also: NotFound, NotExists, Found
67699 */
67700 case OP_IsUnique: {        /* jump, in3 */
67701 #if 0  /* local variables moved into u.bf */
67702   u16 ii;
67703   VdbeCursor *pCx;
67704   BtCursor *pCrsr;
67705   u16 nField;
67706   Mem *aMx;
67707   UnpackedRecord r;                  /* B-Tree index search key */
67708   i64 R;                             /* Rowid stored in register P3 */
67709 #endif /* local variables moved into u.bf */
67710
67711   pIn3 = &aMem[pOp->p3];
67712   u.bf.aMx = &aMem[pOp->p4.i];
67713   /* Assert that the values of parameters P1 and P4 are in range. */
67714   assert( pOp->p4type==P4_INT32 );
67715   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67716   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67717
67718   /* Find the index cursor. */
67719   u.bf.pCx = p->apCsr[pOp->p1];
67720   assert( u.bf.pCx->deferredMoveto==0 );
67721   u.bf.pCx->seekResult = 0;
67722   u.bf.pCx->cacheStatus = CACHE_STALE;
67723   u.bf.pCrsr = u.bf.pCx->pCursor;
67724
67725   /* If any of the values are NULL, take the jump. */
67726   u.bf.nField = u.bf.pCx->pKeyInfo->nField;
67727   for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
67728     if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
67729       pc = pOp->p2 - 1;
67730       u.bf.pCrsr = 0;
67731       break;
67732     }
67733   }
67734   assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
67735
67736   if( u.bf.pCrsr!=0 ){
67737     /* Populate the index search key. */
67738     u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
67739     u.bf.r.nField = u.bf.nField + 1;
67740     u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
67741     u.bf.r.aMem = u.bf.aMx;
67742 #ifdef SQLITE_DEBUG
67743     { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
67744 #endif
67745
67746     /* Extract the value of u.bf.R from register P3. */
67747     sqlite3VdbeMemIntegerify(pIn3);
67748     u.bf.R = pIn3->u.i;
67749
67750     /* Search the B-Tree index. If no conflicting record is found, jump
67751     ** to P2. Otherwise, copy the rowid of the conflicting record to
67752     ** register P3 and fall through to the next instruction.  */
67753     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
67754     if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
67755       pc = pOp->p2 - 1;
67756     }else{
67757       pIn3->u.i = u.bf.r.rowid;
67758     }
67759   }
67760   break;
67761 }
67762
67763 /* Opcode: NotExists P1 P2 P3 * *
67764 **
67765 ** Use the content of register P3 as an integer key.  If a record 
67766 ** with that key does not exist in table of P1, then jump to P2. 
67767 ** If the record does exist, then fall through.  The cursor is left 
67768 ** pointing to the record if it exists.
67769 **
67770 ** The difference between this operation and NotFound is that this
67771 ** operation assumes the key is an integer and that P1 is a table whereas
67772 ** NotFound assumes key is a blob constructed from MakeRecord and
67773 ** P1 is an index.
67774 **
67775 ** See also: Found, NotFound, IsUnique
67776 */
67777 case OP_NotExists: {        /* jump, in3 */
67778 #if 0  /* local variables moved into u.bg */
67779   VdbeCursor *pC;
67780   BtCursor *pCrsr;
67781   int res;
67782   u64 iKey;
67783 #endif /* local variables moved into u.bg */
67784
67785   pIn3 = &aMem[pOp->p3];
67786   assert( pIn3->flags & MEM_Int );
67787   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67788   u.bg.pC = p->apCsr[pOp->p1];
67789   assert( u.bg.pC!=0 );
67790   assert( u.bg.pC->isTable );
67791   assert( u.bg.pC->pseudoTableReg==0 );
67792   u.bg.pCrsr = u.bg.pC->pCursor;
67793   if( ALWAYS(u.bg.pCrsr!=0) ){
67794     u.bg.res = 0;
67795     u.bg.iKey = pIn3->u.i;
67796     rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
67797     u.bg.pC->lastRowid = pIn3->u.i;
67798     u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
67799     u.bg.pC->nullRow = 0;
67800     u.bg.pC->cacheStatus = CACHE_STALE;
67801     u.bg.pC->deferredMoveto = 0;
67802     if( u.bg.res!=0 ){
67803       pc = pOp->p2 - 1;
67804       assert( u.bg.pC->rowidIsValid==0 );
67805     }
67806     u.bg.pC->seekResult = u.bg.res;
67807   }else{
67808     /* This happens when an attempt to open a read cursor on the
67809     ** sqlite_master table returns SQLITE_EMPTY.
67810     */
67811     pc = pOp->p2 - 1;
67812     assert( u.bg.pC->rowidIsValid==0 );
67813     u.bg.pC->seekResult = 0;
67814   }
67815   break;
67816 }
67817
67818 /* Opcode: Sequence P1 P2 * * *
67819 **
67820 ** Find the next available sequence number for cursor P1.
67821 ** Write the sequence number into register P2.
67822 ** The sequence number on the cursor is incremented after this
67823 ** instruction.  
67824 */
67825 case OP_Sequence: {           /* out2-prerelease */
67826   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67827   assert( p->apCsr[pOp->p1]!=0 );
67828   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67829   break;
67830 }
67831
67832
67833 /* Opcode: NewRowid P1 P2 P3 * *
67834 **
67835 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
67836 ** The record number is not previously used as a key in the database
67837 ** table that cursor P1 points to.  The new record number is written
67838 ** written to register P2.
67839 **
67840 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
67841 ** the largest previously generated record number. No new record numbers are
67842 ** allowed to be less than this value. When this value reaches its maximum, 
67843 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
67844 ** generated record number. This P3 mechanism is used to help implement the
67845 ** AUTOINCREMENT feature.
67846 */
67847 case OP_NewRowid: {           /* out2-prerelease */
67848 #if 0  /* local variables moved into u.bh */
67849   i64 v;                 /* The new rowid */
67850   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
67851   int res;               /* Result of an sqlite3BtreeLast() */
67852   int cnt;               /* Counter to limit the number of searches */
67853   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
67854   VdbeFrame *pFrame;     /* Root frame of VDBE */
67855 #endif /* local variables moved into u.bh */
67856
67857   u.bh.v = 0;
67858   u.bh.res = 0;
67859   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67860   u.bh.pC = p->apCsr[pOp->p1];
67861   assert( u.bh.pC!=0 );
67862   if( NEVER(u.bh.pC->pCursor==0) ){
67863     /* The zero initialization above is all that is needed */
67864   }else{
67865     /* The next rowid or record number (different terms for the same
67866     ** thing) is obtained in a two-step algorithm.
67867     **
67868     ** First we attempt to find the largest existing rowid and add one
67869     ** to that.  But if the largest existing rowid is already the maximum
67870     ** positive integer, we have to fall through to the second
67871     ** probabilistic algorithm
67872     **
67873     ** The second algorithm is to select a rowid at random and see if
67874     ** it already exists in the table.  If it does not exist, we have
67875     ** succeeded.  If the random rowid does exist, we select a new one
67876     ** and try again, up to 100 times.
67877     */
67878     assert( u.bh.pC->isTable );
67879
67880 #ifdef SQLITE_32BIT_ROWID
67881 #   define MAX_ROWID 0x7fffffff
67882 #else
67883     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
67884     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
67885     ** to provide the constant while making all compilers happy.
67886     */
67887 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
67888 #endif
67889
67890     if( !u.bh.pC->useRandomRowid ){
67891       u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
67892       if( u.bh.v==0 ){
67893         rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
67894         if( rc!=SQLITE_OK ){
67895           goto abort_due_to_error;
67896         }
67897         if( u.bh.res ){
67898           u.bh.v = 1;   /* IMP: R-61914-48074 */
67899         }else{
67900           assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
67901           rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
67902           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
67903           if( u.bh.v>=MAX_ROWID ){
67904             u.bh.pC->useRandomRowid = 1;
67905           }else{
67906             u.bh.v++;   /* IMP: R-29538-34987 */
67907           }
67908         }
67909       }
67910
67911 #ifndef SQLITE_OMIT_AUTOINCREMENT
67912       if( pOp->p3 ){
67913         /* Assert that P3 is a valid memory cell. */
67914         assert( pOp->p3>0 );
67915         if( p->pFrame ){
67916           for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
67917           /* Assert that P3 is a valid memory cell. */
67918           assert( pOp->p3<=u.bh.pFrame->nMem );
67919           u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
67920         }else{
67921           /* Assert that P3 is a valid memory cell. */
67922           assert( pOp->p3<=p->nMem );
67923           u.bh.pMem = &aMem[pOp->p3];
67924           memAboutToChange(p, u.bh.pMem);
67925         }
67926         assert( memIsValid(u.bh.pMem) );
67927
67928         REGISTER_TRACE(pOp->p3, u.bh.pMem);
67929         sqlite3VdbeMemIntegerify(u.bh.pMem);
67930         assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
67931         if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
67932           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
67933           goto abort_due_to_error;
67934         }
67935         if( u.bh.v<u.bh.pMem->u.i+1 ){
67936           u.bh.v = u.bh.pMem->u.i + 1;
67937         }
67938         u.bh.pMem->u.i = u.bh.v;
67939       }
67940 #endif
67941
67942       sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
67943     }
67944     if( u.bh.pC->useRandomRowid ){
67945       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
67946       ** largest possible integer (9223372036854775807) then the database
67947       ** engine starts picking positive candidate ROWIDs at random until
67948       ** it finds one that is not previously used. */
67949       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
67950                              ** an AUTOINCREMENT table. */
67951       /* on the first attempt, simply do one more than previous */
67952       u.bh.v = lastRowid;
67953       u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67954       u.bh.v++; /* ensure non-zero */
67955       u.bh.cnt = 0;
67956       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
67957                                                  0, &u.bh.res))==SQLITE_OK)
67958             && (u.bh.res==0)
67959             && (++u.bh.cnt<100)){
67960         /* collision - try another random rowid */
67961         sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
67962         if( u.bh.cnt<5 ){
67963           /* try "small" random rowids for the initial attempts */
67964           u.bh.v &= 0xffffff;
67965         }else{
67966           u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67967         }
67968         u.bh.v++; /* ensure non-zero */
67969       }
67970       if( rc==SQLITE_OK && u.bh.res==0 ){
67971         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
67972         goto abort_due_to_error;
67973       }
67974       assert( u.bh.v>0 );  /* EV: R-40812-03570 */
67975     }
67976     u.bh.pC->rowidIsValid = 0;
67977     u.bh.pC->deferredMoveto = 0;
67978     u.bh.pC->cacheStatus = CACHE_STALE;
67979   }
67980   pOut->u.i = u.bh.v;
67981   break;
67982 }
67983
67984 /* Opcode: Insert P1 P2 P3 P4 P5
67985 **
67986 ** Write an entry into the table of cursor P1.  A new entry is
67987 ** created if it doesn't already exist or the data for an existing
67988 ** entry is overwritten.  The data is the value MEM_Blob stored in register
67989 ** number P2. The key is stored in register P3. The key must
67990 ** be a MEM_Int.
67991 **
67992 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
67993 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
67994 ** then rowid is stored for subsequent return by the
67995 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
67996 **
67997 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
67998 ** the last seek operation (OP_NotExists) was a success, then this
67999 ** operation will not attempt to find the appropriate row before doing
68000 ** the insert but will instead overwrite the row that the cursor is
68001 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
68002 ** has already positioned the cursor correctly.  This is an optimization
68003 ** that boosts performance by avoiding redundant seeks.
68004 **
68005 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68006 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68007 ** is part of an INSERT operation.  The difference is only important to
68008 ** the update hook.
68009 **
68010 ** Parameter P4 may point to a string containing the table-name, or
68011 ** may be NULL. If it is not NULL, then the update-hook 
68012 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
68013 **
68014 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68015 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
68016 ** and register P2 becomes ephemeral.  If the cursor is changed, the
68017 ** value of register P2 will then change.  Make sure this does not
68018 ** cause any problems.)
68019 **
68020 ** This instruction only works on tables.  The equivalent instruction
68021 ** for indices is OP_IdxInsert.
68022 */
68023 /* Opcode: InsertInt P1 P2 P3 P4 P5
68024 **
68025 ** This works exactly like OP_Insert except that the key is the
68026 ** integer value P3, not the value of the integer stored in register P3.
68027 */
68028 case OP_Insert: 
68029 case OP_InsertInt: {
68030 #if 0  /* local variables moved into u.bi */
68031   Mem *pData;       /* MEM cell holding data for the record to be inserted */
68032   Mem *pKey;        /* MEM cell holding key  for the record */
68033   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68034   VdbeCursor *pC;   /* Cursor to table into which insert is written */
68035   int nZero;        /* Number of zero-bytes to append */
68036   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68037   const char *zDb;  /* database name - used by the update hook */
68038   const char *zTbl; /* Table name - used by the opdate hook */
68039   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
68040 #endif /* local variables moved into u.bi */
68041
68042   u.bi.pData = &aMem[pOp->p2];
68043   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68044   assert( memIsValid(u.bi.pData) );
68045   u.bi.pC = p->apCsr[pOp->p1];
68046   assert( u.bi.pC!=0 );
68047   assert( u.bi.pC->pCursor!=0 );
68048   assert( u.bi.pC->pseudoTableReg==0 );
68049   assert( u.bi.pC->isTable );
68050   REGISTER_TRACE(pOp->p2, u.bi.pData);
68051
68052   if( pOp->opcode==OP_Insert ){
68053     u.bi.pKey = &aMem[pOp->p3];
68054     assert( u.bi.pKey->flags & MEM_Int );
68055     assert( memIsValid(u.bi.pKey) );
68056     REGISTER_TRACE(pOp->p3, u.bi.pKey);
68057     u.bi.iKey = u.bi.pKey->u.i;
68058   }else{
68059     assert( pOp->opcode==OP_InsertInt );
68060     u.bi.iKey = pOp->p3;
68061   }
68062
68063   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68064   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
68065   if( u.bi.pData->flags & MEM_Null ){
68066     u.bi.pData->z = 0;
68067     u.bi.pData->n = 0;
68068   }else{
68069     assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
68070   }
68071   u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
68072   if( u.bi.pData->flags & MEM_Zero ){
68073     u.bi.nZero = u.bi.pData->u.nZero;
68074   }else{
68075     u.bi.nZero = 0;
68076   }
68077   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
68078   rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
68079                           u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
68080                           pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
68081   );
68082   u.bi.pC->rowidIsValid = 0;
68083   u.bi.pC->deferredMoveto = 0;
68084   u.bi.pC->cacheStatus = CACHE_STALE;
68085
68086   /* Invoke the update-hook if required. */
68087   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68088     u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
68089     u.bi.zTbl = pOp->p4.z;
68090     u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
68091     assert( u.bi.pC->isTable );
68092     db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
68093     assert( u.bi.pC->iDb>=0 );
68094   }
68095   break;
68096 }
68097
68098 /* Opcode: Delete P1 P2 * P4 *
68099 **
68100 ** Delete the record at which the P1 cursor is currently pointing.
68101 **
68102 ** The cursor will be left pointing at either the next or the previous
68103 ** record in the table. If it is left pointing at the next record, then
68104 ** the next Next instruction will be a no-op.  Hence it is OK to delete
68105 ** a record from within an Next loop.
68106 **
68107 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68108 ** incremented (otherwise not).
68109 **
68110 ** P1 must not be pseudo-table.  It has to be a real table with
68111 ** multiple rows.
68112 **
68113 ** If P4 is not NULL, then it is the name of the table that P1 is
68114 ** pointing to.  The update hook will be invoked, if it exists.
68115 ** If P4 is not NULL then the P1 cursor must have been positioned
68116 ** using OP_NotFound prior to invoking this opcode.
68117 */
68118 case OP_Delete: {
68119 #if 0  /* local variables moved into u.bj */
68120   i64 iKey;
68121   VdbeCursor *pC;
68122 #endif /* local variables moved into u.bj */
68123
68124   u.bj.iKey = 0;
68125   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68126   u.bj.pC = p->apCsr[pOp->p1];
68127   assert( u.bj.pC!=0 );
68128   assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68129
68130   /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
68131   ** row being deleted.
68132   */
68133   if( db->xUpdateCallback && pOp->p4.z ){
68134     assert( u.bj.pC->isTable );
68135     assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68136     u.bj.iKey = u.bj.pC->lastRowid;
68137   }
68138
68139   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68140   ** OP_Column on the same table without any intervening operations that
68141   ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
68142   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
68143   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68144   ** to guard against future changes to the code generator.
68145   **/
68146   assert( u.bj.pC->deferredMoveto==0 );
68147   rc = sqlite3VdbeCursorMoveto(u.bj.pC);
68148   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68149
68150   sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
68151   rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
68152   u.bj.pC->cacheStatus = CACHE_STALE;
68153
68154   /* Invoke the update-hook if required. */
68155   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68156     const char *zDb = db->aDb[u.bj.pC->iDb].zName;
68157     const char *zTbl = pOp->p4.z;
68158     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
68159     assert( u.bj.pC->iDb>=0 );
68160   }
68161   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
68162   break;
68163 }
68164 /* Opcode: ResetCount * * * * *
68165 **
68166 ** The value of the change counter is copied to the database handle
68167 ** change counter (returned by subsequent calls to sqlite3_changes()).
68168 ** Then the VMs internal change counter resets to 0.
68169 ** This is used by trigger programs.
68170 */
68171 case OP_ResetCount: {
68172   sqlite3VdbeSetChanges(db, p->nChange);
68173   p->nChange = 0;
68174   break;
68175 }
68176
68177 /* Opcode: SorterCompare P1 P2 P3
68178 **
68179 ** P1 is a sorter cursor. This instruction compares the record blob in 
68180 ** register P3 with the entry that the sorter cursor currently points to.
68181 ** If, excluding the rowid fields at the end, the two records are a match,
68182 ** fall through to the next instruction. Otherwise, jump to instruction P2.
68183 */
68184 case OP_SorterCompare: {
68185 #if 0  /* local variables moved into u.bk */
68186   VdbeCursor *pC;
68187   int res;
68188 #endif /* local variables moved into u.bk */
68189
68190   u.bk.pC = p->apCsr[pOp->p1];
68191   assert( isSorter(u.bk.pC) );
68192   pIn3 = &aMem[pOp->p3];
68193   rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
68194   if( u.bk.res ){
68195     pc = pOp->p2-1;
68196   }
68197   break;
68198 };
68199
68200 /* Opcode: SorterData P1 P2 * * *
68201 **
68202 ** Write into register P2 the current sorter data for sorter cursor P1.
68203 */
68204 case OP_SorterData: {
68205 #if 0  /* local variables moved into u.bl */
68206   VdbeCursor *pC;
68207 #endif /* local variables moved into u.bl */
68208
68209 #ifndef SQLITE_OMIT_MERGE_SORT
68210   pOut = &aMem[pOp->p2];
68211   u.bl.pC = p->apCsr[pOp->p1];
68212   assert( u.bl.pC->isSorter );
68213   rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
68214 #else
68215   pOp->opcode = OP_RowKey;
68216   pc--;
68217 #endif
68218   break;
68219 }
68220
68221 /* Opcode: RowData P1 P2 * * *
68222 **
68223 ** Write into register P2 the complete row data for cursor P1.
68224 ** There is no interpretation of the data.  
68225 ** It is just copied onto the P2 register exactly as 
68226 ** it is found in the database file.
68227 **
68228 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68229 ** of a real table, not a pseudo-table.
68230 */
68231 /* Opcode: RowKey P1 P2 * * *
68232 **
68233 ** Write into register P2 the complete row key for cursor P1.
68234 ** There is no interpretation of the data.  
68235 ** The key is copied onto the P3 register exactly as 
68236 ** it is found in the database file.
68237 **
68238 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68239 ** of a real table, not a pseudo-table.
68240 */
68241 case OP_RowKey:
68242 case OP_RowData: {
68243 #if 0  /* local variables moved into u.bm */
68244   VdbeCursor *pC;
68245   BtCursor *pCrsr;
68246   u32 n;
68247   i64 n64;
68248 #endif /* local variables moved into u.bm */
68249
68250   pOut = &aMem[pOp->p2];
68251   memAboutToChange(p, pOut);
68252
68253   /* Note that RowKey and RowData are really exactly the same instruction */
68254   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68255   u.bm.pC = p->apCsr[pOp->p1];
68256   assert( u.bm.pC->isSorter==0 );
68257   assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
68258   assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
68259   assert( u.bm.pC!=0 );
68260   assert( u.bm.pC->nullRow==0 );
68261   assert( u.bm.pC->pseudoTableReg==0 );
68262   assert( u.bm.pC->pCursor!=0 );
68263   u.bm.pCrsr = u.bm.pC->pCursor;
68264   assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
68265
68266   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
68267   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
68268   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
68269   ** a no-op and can never fail.  But we leave it in place as a safety.
68270   */
68271   assert( u.bm.pC->deferredMoveto==0 );
68272   rc = sqlite3VdbeCursorMoveto(u.bm.pC);
68273   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68274
68275   if( u.bm.pC->isIndex ){
68276     assert( !u.bm.pC->isTable );
68277     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
68278     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
68279     if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68280       goto too_big;
68281     }
68282     u.bm.n = (u32)u.bm.n64;
68283   }else{
68284     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
68285     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
68286     if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
68287       goto too_big;
68288     }
68289   }
68290   if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
68291     goto no_mem;
68292   }
68293   pOut->n = u.bm.n;
68294   MemSetTypeFlag(pOut, MEM_Blob);
68295   if( u.bm.pC->isIndex ){
68296     rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68297   }else{
68298     rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68299   }
68300   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
68301   UPDATE_MAX_BLOBSIZE(pOut);
68302   break;
68303 }
68304
68305 /* Opcode: Rowid P1 P2 * * *
68306 **
68307 ** Store in register P2 an integer which is the key of the table entry that
68308 ** P1 is currently point to.
68309 **
68310 ** P1 can be either an ordinary table or a virtual table.  There used to
68311 ** be a separate OP_VRowid opcode for use with virtual tables, but this
68312 ** one opcode now works for both table types.
68313 */
68314 case OP_Rowid: {                 /* out2-prerelease */
68315 #if 0  /* local variables moved into u.bn */
68316   VdbeCursor *pC;
68317   i64 v;
68318   sqlite3_vtab *pVtab;
68319   const sqlite3_module *pModule;
68320 #endif /* local variables moved into u.bn */
68321
68322   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68323   u.bn.pC = p->apCsr[pOp->p1];
68324   assert( u.bn.pC!=0 );
68325   assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
68326   if( u.bn.pC->nullRow ){
68327     pOut->flags = MEM_Null;
68328     break;
68329   }else if( u.bn.pC->deferredMoveto ){
68330     u.bn.v = u.bn.pC->movetoTarget;
68331 #ifndef SQLITE_OMIT_VIRTUALTABLE
68332   }else if( u.bn.pC->pVtabCursor ){
68333     u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
68334     u.bn.pModule = u.bn.pVtab->pModule;
68335     assert( u.bn.pModule->xRowid );
68336     rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
68337     importVtabErrMsg(p, u.bn.pVtab);
68338 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68339   }else{
68340     assert( u.bn.pC->pCursor!=0 );
68341     rc = sqlite3VdbeCursorMoveto(u.bn.pC);
68342     if( rc ) goto abort_due_to_error;
68343     if( u.bn.pC->rowidIsValid ){
68344       u.bn.v = u.bn.pC->lastRowid;
68345     }else{
68346       rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
68347       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
68348     }
68349   }
68350   pOut->u.i = u.bn.v;
68351   break;
68352 }
68353
68354 /* Opcode: NullRow P1 * * * *
68355 **
68356 ** Move the cursor P1 to a null row.  Any OP_Column operations
68357 ** that occur while the cursor is on the null row will always
68358 ** write a NULL.
68359 */
68360 case OP_NullRow: {
68361 #if 0  /* local variables moved into u.bo */
68362   VdbeCursor *pC;
68363 #endif /* local variables moved into u.bo */
68364
68365   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68366   u.bo.pC = p->apCsr[pOp->p1];
68367   assert( u.bo.pC!=0 );
68368   u.bo.pC->nullRow = 1;
68369   u.bo.pC->rowidIsValid = 0;
68370   assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
68371   if( u.bo.pC->pCursor ){
68372     sqlite3BtreeClearCursor(u.bo.pC->pCursor);
68373   }
68374   break;
68375 }
68376
68377 /* Opcode: Last P1 P2 * * *
68378 **
68379 ** The next use of the Rowid or Column or Next instruction for P1 
68380 ** will refer to the last entry in the database table or index.
68381 ** If the table or index is empty and P2>0, then jump immediately to P2.
68382 ** If P2 is 0 or if the table or index is not empty, fall through
68383 ** to the following instruction.
68384 */
68385 case OP_Last: {        /* jump */
68386 #if 0  /* local variables moved into u.bp */
68387   VdbeCursor *pC;
68388   BtCursor *pCrsr;
68389   int res;
68390 #endif /* local variables moved into u.bp */
68391
68392   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68393   u.bp.pC = p->apCsr[pOp->p1];
68394   assert( u.bp.pC!=0 );
68395   u.bp.pCrsr = u.bp.pC->pCursor;
68396   u.bp.res = 0;
68397   if( ALWAYS(u.bp.pCrsr!=0) ){
68398     rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
68399   }
68400   u.bp.pC->nullRow = (u8)u.bp.res;
68401   u.bp.pC->deferredMoveto = 0;
68402   u.bp.pC->rowidIsValid = 0;
68403   u.bp.pC->cacheStatus = CACHE_STALE;
68404   if( pOp->p2>0 && u.bp.res ){
68405     pc = pOp->p2 - 1;
68406   }
68407   break;
68408 }
68409
68410
68411 /* Opcode: Sort P1 P2 * * *
68412 **
68413 ** This opcode does exactly the same thing as OP_Rewind except that
68414 ** it increments an undocumented global variable used for testing.
68415 **
68416 ** Sorting is accomplished by writing records into a sorting index,
68417 ** then rewinding that index and playing it back from beginning to
68418 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
68419 ** rewinding so that the global variable will be incremented and
68420 ** regression tests can determine whether or not the optimizer is
68421 ** correctly optimizing out sorts.
68422 */
68423 case OP_SorterSort:    /* jump */
68424 #ifdef SQLITE_OMIT_MERGE_SORT
68425   pOp->opcode = OP_Sort;
68426 #endif
68427 case OP_Sort: {        /* jump */
68428 #ifdef SQLITE_TEST
68429   sqlite3_sort_count++;
68430   sqlite3_search_count--;
68431 #endif
68432   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
68433   /* Fall through into OP_Rewind */
68434 }
68435 /* Opcode: Rewind P1 P2 * * *
68436 **
68437 ** The next use of the Rowid or Column or Next instruction for P1 
68438 ** will refer to the first entry in the database table or index.
68439 ** If the table or index is empty and P2>0, then jump immediately to P2.
68440 ** If P2 is 0 or if the table or index is not empty, fall through
68441 ** to the following instruction.
68442 */
68443 case OP_Rewind: {        /* jump */
68444 #if 0  /* local variables moved into u.bq */
68445   VdbeCursor *pC;
68446   BtCursor *pCrsr;
68447   int res;
68448 #endif /* local variables moved into u.bq */
68449
68450   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68451   u.bq.pC = p->apCsr[pOp->p1];
68452   assert( u.bq.pC!=0 );
68453   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
68454   u.bq.res = 1;
68455   if( isSorter(u.bq.pC) ){
68456     rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
68457   }else{
68458     u.bq.pCrsr = u.bq.pC->pCursor;
68459     assert( u.bq.pCrsr );
68460     rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
68461     u.bq.pC->atFirst = u.bq.res==0 ?1:0;
68462     u.bq.pC->deferredMoveto = 0;
68463     u.bq.pC->cacheStatus = CACHE_STALE;
68464     u.bq.pC->rowidIsValid = 0;
68465   }
68466   u.bq.pC->nullRow = (u8)u.bq.res;
68467   assert( pOp->p2>0 && pOp->p2<p->nOp );
68468   if( u.bq.res ){
68469     pc = pOp->p2 - 1;
68470   }
68471   break;
68472 }
68473
68474 /* Opcode: Next P1 P2 * P4 P5
68475 **
68476 ** Advance cursor P1 so that it points to the next key/data pair in its
68477 ** table or index.  If there are no more key/value pairs then fall through
68478 ** to the following instruction.  But if the cursor advance was successful,
68479 ** jump immediately to P2.
68480 **
68481 ** The P1 cursor must be for a real table, not a pseudo-table.
68482 **
68483 ** P4 is always of type P4_ADVANCE. The function pointer points to
68484 ** sqlite3BtreeNext().
68485 **
68486 ** If P5 is positive and the jump is taken, then event counter
68487 ** number P5-1 in the prepared statement is incremented.
68488 **
68489 ** See also: Prev
68490 */
68491 /* Opcode: Prev P1 P2 * * P5
68492 **
68493 ** Back up cursor P1 so that it points to the previous key/data pair in its
68494 ** table or index.  If there is no previous key/value pairs then fall through
68495 ** to the following instruction.  But if the cursor backup was successful,
68496 ** jump immediately to P2.
68497 **
68498 ** The P1 cursor must be for a real table, not a pseudo-table.
68499 **
68500 ** P4 is always of type P4_ADVANCE. The function pointer points to
68501 ** sqlite3BtreePrevious().
68502 **
68503 ** If P5 is positive and the jump is taken, then event counter
68504 ** number P5-1 in the prepared statement is incremented.
68505 */
68506 case OP_SorterNext:    /* jump */
68507 #ifdef SQLITE_OMIT_MERGE_SORT
68508   pOp->opcode = OP_Next;
68509 #endif
68510 case OP_Prev:          /* jump */
68511 case OP_Next: {        /* jump */
68512 #if 0  /* local variables moved into u.br */
68513   VdbeCursor *pC;
68514   int res;
68515 #endif /* local variables moved into u.br */
68516
68517   CHECK_FOR_INTERRUPT;
68518   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68519   assert( pOp->p5<=ArraySize(p->aCounter) );
68520   u.br.pC = p->apCsr[pOp->p1];
68521   if( u.br.pC==0 ){
68522     break;  /* See ticket #2273 */
68523   }
68524   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
68525   if( isSorter(u.br.pC) ){
68526     assert( pOp->opcode==OP_SorterNext );
68527     rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
68528   }else{
68529     u.br.res = 1;
68530     assert( u.br.pC->deferredMoveto==0 );
68531     assert( u.br.pC->pCursor );
68532     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
68533     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
68534     rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
68535   }
68536   u.br.pC->nullRow = (u8)u.br.res;
68537   u.br.pC->cacheStatus = CACHE_STALE;
68538   if( u.br.res==0 ){
68539     pc = pOp->p2 - 1;
68540     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
68541 #ifdef SQLITE_TEST
68542     sqlite3_search_count++;
68543 #endif
68544   }
68545   u.br.pC->rowidIsValid = 0;
68546   break;
68547 }
68548
68549 /* Opcode: IdxInsert P1 P2 P3 * P5
68550 **
68551 ** Register P2 holds an SQL index key made using the
68552 ** MakeRecord instructions.  This opcode writes that key
68553 ** into the index P1.  Data for the entry is nil.
68554 **
68555 ** P3 is a flag that provides a hint to the b-tree layer that this
68556 ** insert is likely to be an append.
68557 **
68558 ** This instruction only works for indices.  The equivalent instruction
68559 ** for tables is OP_Insert.
68560 */
68561 case OP_SorterInsert:       /* in2 */
68562 #ifdef SQLITE_OMIT_MERGE_SORT
68563   pOp->opcode = OP_IdxInsert;
68564 #endif
68565 case OP_IdxInsert: {        /* in2 */
68566 #if 0  /* local variables moved into u.bs */
68567   VdbeCursor *pC;
68568   BtCursor *pCrsr;
68569   int nKey;
68570   const char *zKey;
68571 #endif /* local variables moved into u.bs */
68572
68573   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68574   u.bs.pC = p->apCsr[pOp->p1];
68575   assert( u.bs.pC!=0 );
68576   assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
68577   pIn2 = &aMem[pOp->p2];
68578   assert( pIn2->flags & MEM_Blob );
68579   u.bs.pCrsr = u.bs.pC->pCursor;
68580   if( ALWAYS(u.bs.pCrsr!=0) ){
68581     assert( u.bs.pC->isTable==0 );
68582     rc = ExpandBlob(pIn2);
68583     if( rc==SQLITE_OK ){
68584       if( isSorter(u.bs.pC) ){
68585         rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
68586       }else{
68587         u.bs.nKey = pIn2->n;
68588         u.bs.zKey = pIn2->z;
68589         rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
68590             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
68591             );
68592         assert( u.bs.pC->deferredMoveto==0 );
68593         u.bs.pC->cacheStatus = CACHE_STALE;
68594       }
68595     }
68596   }
68597   break;
68598 }
68599
68600 /* Opcode: IdxDelete P1 P2 P3 * *
68601 **
68602 ** The content of P3 registers starting at register P2 form
68603 ** an unpacked index key. This opcode removes that entry from the 
68604 ** index opened by cursor P1.
68605 */
68606 case OP_IdxDelete: {
68607 #if 0  /* local variables moved into u.bt */
68608   VdbeCursor *pC;
68609   BtCursor *pCrsr;
68610   int res;
68611   UnpackedRecord r;
68612 #endif /* local variables moved into u.bt */
68613
68614   assert( pOp->p3>0 );
68615   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68616   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68617   u.bt.pC = p->apCsr[pOp->p1];
68618   assert( u.bt.pC!=0 );
68619   u.bt.pCrsr = u.bt.pC->pCursor;
68620   if( ALWAYS(u.bt.pCrsr!=0) ){
68621     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
68622     u.bt.r.nField = (u16)pOp->p3;
68623     u.bt.r.flags = 0;
68624     u.bt.r.aMem = &aMem[pOp->p2];
68625 #ifdef SQLITE_DEBUG
68626     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
68627 #endif
68628     rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
68629     if( rc==SQLITE_OK && u.bt.res==0 ){
68630       rc = sqlite3BtreeDelete(u.bt.pCrsr);
68631     }
68632     assert( u.bt.pC->deferredMoveto==0 );
68633     u.bt.pC->cacheStatus = CACHE_STALE;
68634   }
68635   break;
68636 }
68637
68638 /* Opcode: IdxRowid P1 P2 * * *
68639 **
68640 ** Write into register P2 an integer which is the last entry in the record at
68641 ** the end of the index key pointed to by cursor P1.  This integer should be
68642 ** the rowid of the table entry to which this index entry points.
68643 **
68644 ** See also: Rowid, MakeRecord.
68645 */
68646 case OP_IdxRowid: {              /* out2-prerelease */
68647 #if 0  /* local variables moved into u.bu */
68648   BtCursor *pCrsr;
68649   VdbeCursor *pC;
68650   i64 rowid;
68651 #endif /* local variables moved into u.bu */
68652
68653   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68654   u.bu.pC = p->apCsr[pOp->p1];
68655   assert( u.bu.pC!=0 );
68656   u.bu.pCrsr = u.bu.pC->pCursor;
68657   pOut->flags = MEM_Null;
68658   if( ALWAYS(u.bu.pCrsr!=0) ){
68659     rc = sqlite3VdbeCursorMoveto(u.bu.pC);
68660     if( NEVER(rc) ) goto abort_due_to_error;
68661     assert( u.bu.pC->deferredMoveto==0 );
68662     assert( u.bu.pC->isTable==0 );
68663     if( !u.bu.pC->nullRow ){
68664       rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
68665       if( rc!=SQLITE_OK ){
68666         goto abort_due_to_error;
68667       }
68668       pOut->u.i = u.bu.rowid;
68669       pOut->flags = MEM_Int;
68670     }
68671   }
68672   break;
68673 }
68674
68675 /* Opcode: IdxGE P1 P2 P3 P4 P5
68676 **
68677 ** The P4 register values beginning with P3 form an unpacked index 
68678 ** key that omits the ROWID.  Compare this key value against the index 
68679 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68680 **
68681 ** If the P1 index entry is greater than or equal to the key value
68682 ** then jump to P2.  Otherwise fall through to the next instruction.
68683 **
68684 ** If P5 is non-zero then the key value is increased by an epsilon 
68685 ** prior to the comparison.  This make the opcode work like IdxGT except
68686 ** that if the key from register P3 is a prefix of the key in the cursor,
68687 ** the result is false whereas it would be true with IdxGT.
68688 */
68689 /* Opcode: IdxLT P1 P2 P3 P4 P5
68690 **
68691 ** The P4 register values beginning with P3 form an unpacked index 
68692 ** key that omits the ROWID.  Compare this key value against the index 
68693 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68694 **
68695 ** If the P1 index entry is less than the key value then jump to P2.
68696 ** Otherwise fall through to the next instruction.
68697 **
68698 ** If P5 is non-zero then the key value is increased by an epsilon prior 
68699 ** to the comparison.  This makes the opcode work like IdxLE.
68700 */
68701 case OP_IdxLT:          /* jump */
68702 case OP_IdxGE: {        /* jump */
68703 #if 0  /* local variables moved into u.bv */
68704   VdbeCursor *pC;
68705   int res;
68706   UnpackedRecord r;
68707 #endif /* local variables moved into u.bv */
68708
68709   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68710   u.bv.pC = p->apCsr[pOp->p1];
68711   assert( u.bv.pC!=0 );
68712   assert( u.bv.pC->isOrdered );
68713   if( ALWAYS(u.bv.pC->pCursor!=0) ){
68714     assert( u.bv.pC->deferredMoveto==0 );
68715     assert( pOp->p5==0 || pOp->p5==1 );
68716     assert( pOp->p4type==P4_INT32 );
68717     u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
68718     u.bv.r.nField = (u16)pOp->p4.i;
68719     if( pOp->p5 ){
68720       u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
68721     }else{
68722       u.bv.r.flags = UNPACKED_PREFIX_MATCH;
68723     }
68724     u.bv.r.aMem = &aMem[pOp->p3];
68725 #ifdef SQLITE_DEBUG
68726     { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
68727 #endif
68728     rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
68729     if( pOp->opcode==OP_IdxLT ){
68730       u.bv.res = -u.bv.res;
68731     }else{
68732       assert( pOp->opcode==OP_IdxGE );
68733       u.bv.res++;
68734     }
68735     if( u.bv.res>0 ){
68736       pc = pOp->p2 - 1 ;
68737     }
68738   }
68739   break;
68740 }
68741
68742 /* Opcode: Destroy P1 P2 P3 * *
68743 **
68744 ** Delete an entire database table or index whose root page in the database
68745 ** file is given by P1.
68746 **
68747 ** The table being destroyed is in the main database file if P3==0.  If
68748 ** P3==1 then the table to be clear is in the auxiliary database file
68749 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68750 **
68751 ** If AUTOVACUUM is enabled then it is possible that another root page
68752 ** might be moved into the newly deleted root page in order to keep all
68753 ** root pages contiguous at the beginning of the database.  The former
68754 ** value of the root page that moved - its value before the move occurred -
68755 ** is stored in register P2.  If no page 
68756 ** movement was required (because the table being dropped was already 
68757 ** the last one in the database) then a zero is stored in register P2.
68758 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68759 **
68760 ** See also: Clear
68761 */
68762 case OP_Destroy: {     /* out2-prerelease */
68763 #if 0  /* local variables moved into u.bw */
68764   int iMoved;
68765   int iCnt;
68766   Vdbe *pVdbe;
68767   int iDb;
68768 #endif /* local variables moved into u.bw */
68769
68770 #ifndef SQLITE_OMIT_VIRTUALTABLE
68771   u.bw.iCnt = 0;
68772   for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
68773     if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
68774       u.bw.iCnt++;
68775     }
68776   }
68777 #else
68778   u.bw.iCnt = db->activeVdbeCnt;
68779 #endif
68780   pOut->flags = MEM_Null;
68781   if( u.bw.iCnt>1 ){
68782     rc = SQLITE_LOCKED;
68783     p->errorAction = OE_Abort;
68784   }else{
68785     u.bw.iDb = pOp->p3;
68786     assert( u.bw.iCnt==1 );
68787     assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
68788     rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
68789     pOut->flags = MEM_Int;
68790     pOut->u.i = u.bw.iMoved;
68791 #ifndef SQLITE_OMIT_AUTOVACUUM
68792     if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
68793       sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
68794       /* All OP_Destroy operations occur on the same btree */
68795       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
68796       resetSchemaOnFault = u.bw.iDb+1;
68797     }
68798 #endif
68799   }
68800   break;
68801 }
68802
68803 /* Opcode: Clear P1 P2 P3
68804 **
68805 ** Delete all contents of the database table or index whose root page
68806 ** in the database file is given by P1.  But, unlike Destroy, do not
68807 ** remove the table or index from the database file.
68808 **
68809 ** The table being clear is in the main database file if P2==0.  If
68810 ** P2==1 then the table to be clear is in the auxiliary database file
68811 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68812 **
68813 ** If the P3 value is non-zero, then the table referred to must be an
68814 ** intkey table (an SQL table, not an index). In this case the row change 
68815 ** count is incremented by the number of rows in the table being cleared. 
68816 ** If P3 is greater than zero, then the value stored in register P3 is
68817 ** also incremented by the number of rows in the table being cleared.
68818 **
68819 ** See also: Destroy
68820 */
68821 case OP_Clear: {
68822 #if 0  /* local variables moved into u.bx */
68823   int nChange;
68824 #endif /* local variables moved into u.bx */
68825
68826   u.bx.nChange = 0;
68827   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68828   rc = sqlite3BtreeClearTable(
68829       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
68830   );
68831   if( pOp->p3 ){
68832     p->nChange += u.bx.nChange;
68833     if( pOp->p3>0 ){
68834       assert( memIsValid(&aMem[pOp->p3]) );
68835       memAboutToChange(p, &aMem[pOp->p3]);
68836       aMem[pOp->p3].u.i += u.bx.nChange;
68837     }
68838   }
68839   break;
68840 }
68841
68842 /* Opcode: CreateTable P1 P2 * * *
68843 **
68844 ** Allocate a new table in the main database file if P1==0 or in the
68845 ** auxiliary database file if P1==1 or in an attached database if
68846 ** P1>1.  Write the root page number of the new table into
68847 ** register P2
68848 **
68849 ** The difference between a table and an index is this:  A table must
68850 ** have a 4-byte integer key and can have arbitrary data.  An index
68851 ** has an arbitrary key but no data.
68852 **
68853 ** See also: CreateIndex
68854 */
68855 /* Opcode: CreateIndex P1 P2 * * *
68856 **
68857 ** Allocate a new index in the main database file if P1==0 or in the
68858 ** auxiliary database file if P1==1 or in an attached database if
68859 ** P1>1.  Write the root page number of the new table into
68860 ** register P2.
68861 **
68862 ** See documentation on OP_CreateTable for additional information.
68863 */
68864 case OP_CreateIndex:            /* out2-prerelease */
68865 case OP_CreateTable: {          /* out2-prerelease */
68866 #if 0  /* local variables moved into u.by */
68867   int pgno;
68868   int flags;
68869   Db *pDb;
68870 #endif /* local variables moved into u.by */
68871
68872   u.by.pgno = 0;
68873   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68874   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68875   u.by.pDb = &db->aDb[pOp->p1];
68876   assert( u.by.pDb->pBt!=0 );
68877   if( pOp->opcode==OP_CreateTable ){
68878     /* u.by.flags = BTREE_INTKEY; */
68879     u.by.flags = BTREE_INTKEY;
68880   }else{
68881     u.by.flags = BTREE_BLOBKEY;
68882   }
68883   rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
68884   pOut->u.i = u.by.pgno;
68885   break;
68886 }
68887
68888 /* Opcode: ParseSchema P1 * * P4 *
68889 **
68890 ** Read and parse all entries from the SQLITE_MASTER table of database P1
68891 ** that match the WHERE clause P4. 
68892 **
68893 ** This opcode invokes the parser to create a new virtual machine,
68894 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
68895 */
68896 case OP_ParseSchema: {
68897 #if 0  /* local variables moved into u.bz */
68898   int iDb;
68899   const char *zMaster;
68900   char *zSql;
68901   InitData initData;
68902 #endif /* local variables moved into u.bz */
68903
68904   /* Any prepared statement that invokes this opcode will hold mutexes
68905   ** on every btree.  This is a prerequisite for invoking
68906   ** sqlite3InitCallback().
68907   */
68908 #ifdef SQLITE_DEBUG
68909   for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
68910     assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
68911   }
68912 #endif
68913
68914   u.bz.iDb = pOp->p1;
68915   assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
68916   assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
68917   /* Used to be a conditional */ {
68918     u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
68919     u.bz.initData.db = db;
68920     u.bz.initData.iDb = pOp->p1;
68921     u.bz.initData.pzErrMsg = &p->zErrMsg;
68922     u.bz.zSql = sqlite3MPrintf(db,
68923        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
68924        db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
68925     if( u.bz.zSql==0 ){
68926       rc = SQLITE_NOMEM;
68927     }else{
68928       assert( db->init.busy==0 );
68929       db->init.busy = 1;
68930       u.bz.initData.rc = SQLITE_OK;
68931       assert( !db->mallocFailed );
68932       rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
68933       if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
68934       sqlite3DbFree(db, u.bz.zSql);
68935       db->init.busy = 0;
68936     }
68937   }
68938   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
68939   if( rc==SQLITE_NOMEM ){
68940     goto no_mem;
68941   }
68942   break;
68943 }
68944
68945 #if !defined(SQLITE_OMIT_ANALYZE)
68946 /* Opcode: LoadAnalysis P1 * * * *
68947 **
68948 ** Read the sqlite_stat1 table for database P1 and load the content
68949 ** of that table into the internal index hash table.  This will cause
68950 ** the analysis to be used when preparing all subsequent queries.
68951 */
68952 case OP_LoadAnalysis: {
68953   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68954   rc = sqlite3AnalysisLoad(db, pOp->p1);
68955   break;  
68956 }
68957 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
68958
68959 /* Opcode: DropTable P1 * * P4 *
68960 **
68961 ** Remove the internal (in-memory) data structures that describe
68962 ** the table named P4 in database P1.  This is called after a table
68963 ** is dropped in order to keep the internal representation of the
68964 ** schema consistent with what is on disk.
68965 */
68966 case OP_DropTable: {
68967   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
68968   break;
68969 }
68970
68971 /* Opcode: DropIndex P1 * * P4 *
68972 **
68973 ** Remove the internal (in-memory) data structures that describe
68974 ** the index named P4 in database P1.  This is called after an index
68975 ** is dropped in order to keep the internal representation of the
68976 ** schema consistent with what is on disk.
68977 */
68978 case OP_DropIndex: {
68979   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
68980   break;
68981 }
68982
68983 /* Opcode: DropTrigger P1 * * P4 *
68984 **
68985 ** Remove the internal (in-memory) data structures that describe
68986 ** the trigger named P4 in database P1.  This is called after a trigger
68987 ** is dropped in order to keep the internal representation of the
68988 ** schema consistent with what is on disk.
68989 */
68990 case OP_DropTrigger: {
68991   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
68992   break;
68993 }
68994
68995
68996 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68997 /* Opcode: IntegrityCk P1 P2 P3 * P5
68998 **
68999 ** Do an analysis of the currently open database.  Store in
69000 ** register P1 the text of an error message describing any problems.
69001 ** If no problems are found, store a NULL in register P1.
69002 **
69003 ** The register P3 contains the maximum number of allowed errors.
69004 ** At most reg(P3) errors will be reported.
69005 ** In other words, the analysis stops as soon as reg(P1) errors are 
69006 ** seen.  Reg(P1) is updated with the number of errors remaining.
69007 **
69008 ** The root page numbers of all tables in the database are integer
69009 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69010 ** total.
69011 **
69012 ** If P5 is not zero, the check is done on the auxiliary database
69013 ** file, not the main database file.
69014 **
69015 ** This opcode is used to implement the integrity_check pragma.
69016 */
69017 case OP_IntegrityCk: {
69018 #if 0  /* local variables moved into u.ca */
69019   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69020   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69021   int j;          /* Loop counter */
69022   int nErr;       /* Number of errors reported */
69023   char *z;        /* Text of the error report */
69024   Mem *pnErr;     /* Register keeping track of errors remaining */
69025 #endif /* local variables moved into u.ca */
69026
69027   u.ca.nRoot = pOp->p2;
69028   assert( u.ca.nRoot>0 );
69029   u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
69030   if( u.ca.aRoot==0 ) goto no_mem;
69031   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69032   u.ca.pnErr = &aMem[pOp->p3];
69033   assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
69034   assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69035   pIn1 = &aMem[pOp->p1];
69036   for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
69037     u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
69038   }
69039   u.ca.aRoot[u.ca.j] = 0;
69040   assert( pOp->p5<db->nDb );
69041   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69042   u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
69043                                  (int)u.ca.pnErr->u.i, &u.ca.nErr);
69044   sqlite3DbFree(db, u.ca.aRoot);
69045   u.ca.pnErr->u.i -= u.ca.nErr;
69046   sqlite3VdbeMemSetNull(pIn1);
69047   if( u.ca.nErr==0 ){
69048     assert( u.ca.z==0 );
69049   }else if( u.ca.z==0 ){
69050     goto no_mem;
69051   }else{
69052     sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
69053   }
69054   UPDATE_MAX_BLOBSIZE(pIn1);
69055   sqlite3VdbeChangeEncoding(pIn1, encoding);
69056   break;
69057 }
69058 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69059
69060 /* Opcode: RowSetAdd P1 P2 * * *
69061 **
69062 ** Insert the integer value held by register P2 into a boolean index
69063 ** held in register P1.
69064 **
69065 ** An assertion fails if P2 is not an integer.
69066 */
69067 case OP_RowSetAdd: {       /* in1, in2 */
69068   pIn1 = &aMem[pOp->p1];
69069   pIn2 = &aMem[pOp->p2];
69070   assert( (pIn2->flags & MEM_Int)!=0 );
69071   if( (pIn1->flags & MEM_RowSet)==0 ){
69072     sqlite3VdbeMemSetRowSet(pIn1);
69073     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69074   }
69075   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69076   break;
69077 }
69078
69079 /* Opcode: RowSetRead P1 P2 P3 * *
69080 **
69081 ** Extract the smallest value from boolean index P1 and put that value into
69082 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
69083 ** unchanged and jump to instruction P2.
69084 */
69085 case OP_RowSetRead: {       /* jump, in1, out3 */
69086 #if 0  /* local variables moved into u.cb */
69087   i64 val;
69088 #endif /* local variables moved into u.cb */
69089   CHECK_FOR_INTERRUPT;
69090   pIn1 = &aMem[pOp->p1];
69091   if( (pIn1->flags & MEM_RowSet)==0
69092    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
69093   ){
69094     /* The boolean index is empty */
69095     sqlite3VdbeMemSetNull(pIn1);
69096     pc = pOp->p2 - 1;
69097   }else{
69098     /* A value was pulled from the index */
69099     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
69100   }
69101   break;
69102 }
69103
69104 /* Opcode: RowSetTest P1 P2 P3 P4
69105 **
69106 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
69107 ** contains a RowSet object and that RowSet object contains
69108 ** the value held in P3, jump to register P2. Otherwise, insert the
69109 ** integer in P3 into the RowSet and continue on to the
69110 ** next opcode.
69111 **
69112 ** The RowSet object is optimized for the case where successive sets
69113 ** of integers, where each set contains no duplicates. Each set
69114 ** of values is identified by a unique P4 value. The first set
69115 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69116 ** non-negative.  For non-negative values of P4 only the lower 4
69117 ** bits are significant.
69118 **
69119 ** This allows optimizations: (a) when P4==0 there is no need to test
69120 ** the rowset object for P3, as it is guaranteed not to contain it,
69121 ** (b) when P4==-1 there is no need to insert the value, as it will
69122 ** never be tested for, and (c) when a value that is part of set X is
69123 ** inserted, there is no need to search to see if the same value was
69124 ** previously inserted as part of set X (only if it was previously
69125 ** inserted as part of some other set).
69126 */
69127 case OP_RowSetTest: {                     /* jump, in1, in3 */
69128 #if 0  /* local variables moved into u.cc */
69129   int iSet;
69130   int exists;
69131 #endif /* local variables moved into u.cc */
69132
69133   pIn1 = &aMem[pOp->p1];
69134   pIn3 = &aMem[pOp->p3];
69135   u.cc.iSet = pOp->p4.i;
69136   assert( pIn3->flags&MEM_Int );
69137
69138   /* If there is anything other than a rowset object in memory cell P1,
69139   ** delete it now and initialize P1 with an empty rowset
69140   */
69141   if( (pIn1->flags & MEM_RowSet)==0 ){
69142     sqlite3VdbeMemSetRowSet(pIn1);
69143     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69144   }
69145
69146   assert( pOp->p4type==P4_INT32 );
69147   assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
69148   if( u.cc.iSet ){
69149     u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
69150                                (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
69151                                pIn3->u.i);
69152     if( u.cc.exists ){
69153       pc = pOp->p2 - 1;
69154       break;
69155     }
69156   }
69157   if( u.cc.iSet>=0 ){
69158     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
69159   }
69160   break;
69161 }
69162
69163
69164 #ifndef SQLITE_OMIT_TRIGGER
69165
69166 /* Opcode: Program P1 P2 P3 P4 *
69167 **
69168 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
69169 **
69170 ** P1 contains the address of the memory cell that contains the first memory 
69171 ** cell in an array of values used as arguments to the sub-program. P2 
69172 ** contains the address to jump to if the sub-program throws an IGNORE 
69173 ** exception using the RAISE() function. Register P3 contains the address 
69174 ** of a memory cell in this (the parent) VM that is used to allocate the 
69175 ** memory required by the sub-vdbe at runtime.
69176 **
69177 ** P4 is a pointer to the VM containing the trigger program.
69178 */
69179 case OP_Program: {        /* jump */
69180 #if 0  /* local variables moved into u.cd */
69181   int nMem;               /* Number of memory registers for sub-program */
69182   int nByte;              /* Bytes of runtime space required for sub-program */
69183   Mem *pRt;               /* Register to allocate runtime space */
69184   Mem *pMem;              /* Used to iterate through memory cells */
69185   Mem *pEnd;              /* Last memory cell in new array */
69186   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
69187   SubProgram *pProgram;   /* Sub-program to execute */
69188   void *t;                /* Token identifying trigger */
69189 #endif /* local variables moved into u.cd */
69190
69191   u.cd.pProgram = pOp->p4.pProgram;
69192   u.cd.pRt = &aMem[pOp->p3];
69193   assert( u.cd.pProgram->nOp>0 );
69194
69195   /* If the p5 flag is clear, then recursive invocation of triggers is
69196   ** disabled for backwards compatibility (p5 is set if this sub-program
69197   ** is really a trigger, not a foreign key action, and the flag set
69198   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
69199   **
69200   ** It is recursive invocation of triggers, at the SQL level, that is
69201   ** disabled. In some cases a single trigger may generate more than one
69202   ** SubProgram (if the trigger may be executed with more than one different
69203   ** ON CONFLICT algorithm). SubProgram structures associated with a
69204   ** single trigger all have the same value for the SubProgram.token
69205   ** variable.  */
69206   if( pOp->p5 ){
69207     u.cd.t = u.cd.pProgram->token;
69208     for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
69209     if( u.cd.pFrame ) break;
69210   }
69211
69212   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
69213     rc = SQLITE_ERROR;
69214     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
69215     break;
69216   }
69217
69218   /* Register u.cd.pRt is used to store the memory required to save the state
69219   ** of the current program, and the memory required at runtime to execute
69220   ** the trigger program. If this trigger has been fired before, then u.cd.pRt
69221   ** is already allocated. Otherwise, it must be initialized.  */
69222   if( (u.cd.pRt->flags&MEM_Frame)==0 ){
69223     /* SubProgram.nMem is set to the number of memory cells used by the
69224     ** program stored in SubProgram.aOp. As well as these, one memory
69225     ** cell is required for each cursor used by the program. Set local
69226     ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
69227     */
69228     u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
69229     u.cd.nByte = ROUND8(sizeof(VdbeFrame))
69230               + u.cd.nMem * sizeof(Mem)
69231               + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
69232               + u.cd.pProgram->nOnce * sizeof(u8);
69233     u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
69234     if( !u.cd.pFrame ){
69235       goto no_mem;
69236     }
69237     sqlite3VdbeMemRelease(u.cd.pRt);
69238     u.cd.pRt->flags = MEM_Frame;
69239     u.cd.pRt->u.pFrame = u.cd.pFrame;
69240
69241     u.cd.pFrame->v = p;
69242     u.cd.pFrame->nChildMem = u.cd.nMem;
69243     u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
69244     u.cd.pFrame->pc = pc;
69245     u.cd.pFrame->aMem = p->aMem;
69246     u.cd.pFrame->nMem = p->nMem;
69247     u.cd.pFrame->apCsr = p->apCsr;
69248     u.cd.pFrame->nCursor = p->nCursor;
69249     u.cd.pFrame->aOp = p->aOp;
69250     u.cd.pFrame->nOp = p->nOp;
69251     u.cd.pFrame->token = u.cd.pProgram->token;
69252     u.cd.pFrame->aOnceFlag = p->aOnceFlag;
69253     u.cd.pFrame->nOnceFlag = p->nOnceFlag;
69254
69255     u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
69256     for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
69257       u.cd.pMem->flags = MEM_Invalid;
69258       u.cd.pMem->db = db;
69259     }
69260   }else{
69261     u.cd.pFrame = u.cd.pRt->u.pFrame;
69262     assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
69263     assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
69264     assert( pc==u.cd.pFrame->pc );
69265   }
69266
69267   p->nFrame++;
69268   u.cd.pFrame->pParent = p->pFrame;
69269   u.cd.pFrame->lastRowid = lastRowid;
69270   u.cd.pFrame->nChange = p->nChange;
69271   p->nChange = 0;
69272   p->pFrame = u.cd.pFrame;
69273   p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
69274   p->nMem = u.cd.pFrame->nChildMem;
69275   p->nCursor = (u16)u.cd.pFrame->nChildCsr;
69276   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
69277   p->aOp = aOp = u.cd.pProgram->aOp;
69278   p->nOp = u.cd.pProgram->nOp;
69279   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
69280   p->nOnceFlag = u.cd.pProgram->nOnce;
69281   pc = -1;
69282   memset(p->aOnceFlag, 0, p->nOnceFlag);
69283
69284   break;
69285 }
69286
69287 /* Opcode: Param P1 P2 * * *
69288 **
69289 ** This opcode is only ever present in sub-programs called via the 
69290 ** OP_Program instruction. Copy a value currently stored in a memory 
69291 ** cell of the calling (parent) frame to cell P2 in the current frames 
69292 ** address space. This is used by trigger programs to access the new.* 
69293 ** and old.* values.
69294 **
69295 ** The address of the cell in the parent frame is determined by adding
69296 ** the value of the P1 argument to the value of the P1 argument to the
69297 ** calling OP_Program instruction.
69298 */
69299 case OP_Param: {           /* out2-prerelease */
69300 #if 0  /* local variables moved into u.ce */
69301   VdbeFrame *pFrame;
69302   Mem *pIn;
69303 #endif /* local variables moved into u.ce */
69304   u.ce.pFrame = p->pFrame;
69305   u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
69306   sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
69307   break;
69308 }
69309
69310 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
69311
69312 #ifndef SQLITE_OMIT_FOREIGN_KEY
69313 /* Opcode: FkCounter P1 P2 * * *
69314 **
69315 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
69316 ** If P1 is non-zero, the database constraint counter is incremented 
69317 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
69318 ** statement counter is incremented (immediate foreign key constraints).
69319 */
69320 case OP_FkCounter: {
69321   if( pOp->p1 ){
69322     db->nDeferredCons += pOp->p2;
69323   }else{
69324     p->nFkConstraint += pOp->p2;
69325   }
69326   break;
69327 }
69328
69329 /* Opcode: FkIfZero P1 P2 * * *
69330 **
69331 ** This opcode tests if a foreign key constraint-counter is currently zero.
69332 ** If so, jump to instruction P2. Otherwise, fall through to the next 
69333 ** instruction.
69334 **
69335 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
69336 ** is zero (the one that counts deferred constraint violations). If P1 is
69337 ** zero, the jump is taken if the statement constraint-counter is zero
69338 ** (immediate foreign key constraint violations).
69339 */
69340 case OP_FkIfZero: {         /* jump */
69341   if( pOp->p1 ){
69342     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
69343   }else{
69344     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
69345   }
69346   break;
69347 }
69348 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
69349
69350 #ifndef SQLITE_OMIT_AUTOINCREMENT
69351 /* Opcode: MemMax P1 P2 * * *
69352 **
69353 ** P1 is a register in the root frame of this VM (the root frame is
69354 ** different from the current frame if this instruction is being executed
69355 ** within a sub-program). Set the value of register P1 to the maximum of 
69356 ** its current value and the value in register P2.
69357 **
69358 ** This instruction throws an error if the memory cell is not initially
69359 ** an integer.
69360 */
69361 case OP_MemMax: {        /* in2 */
69362 #if 0  /* local variables moved into u.cf */
69363   Mem *pIn1;
69364   VdbeFrame *pFrame;
69365 #endif /* local variables moved into u.cf */
69366   if( p->pFrame ){
69367     for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
69368     u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
69369   }else{
69370     u.cf.pIn1 = &aMem[pOp->p1];
69371   }
69372   assert( memIsValid(u.cf.pIn1) );
69373   sqlite3VdbeMemIntegerify(u.cf.pIn1);
69374   pIn2 = &aMem[pOp->p2];
69375   sqlite3VdbeMemIntegerify(pIn2);
69376   if( u.cf.pIn1->u.i<pIn2->u.i){
69377     u.cf.pIn1->u.i = pIn2->u.i;
69378   }
69379   break;
69380 }
69381 #endif /* SQLITE_OMIT_AUTOINCREMENT */
69382
69383 /* Opcode: IfPos P1 P2 * * *
69384 **
69385 ** If the value of register P1 is 1 or greater, jump to P2.
69386 **
69387 ** It is illegal to use this instruction on a register that does
69388 ** not contain an integer.  An assertion fault will result if you try.
69389 */
69390 case OP_IfPos: {        /* jump, in1 */
69391   pIn1 = &aMem[pOp->p1];
69392   assert( pIn1->flags&MEM_Int );
69393   if( pIn1->u.i>0 ){
69394      pc = pOp->p2 - 1;
69395   }
69396   break;
69397 }
69398
69399 /* Opcode: IfNeg P1 P2 * * *
69400 **
69401 ** If the value of register P1 is less than zero, jump to P2. 
69402 **
69403 ** It is illegal to use this instruction on a register that does
69404 ** not contain an integer.  An assertion fault will result if you try.
69405 */
69406 case OP_IfNeg: {        /* jump, in1 */
69407   pIn1 = &aMem[pOp->p1];
69408   assert( pIn1->flags&MEM_Int );
69409   if( pIn1->u.i<0 ){
69410      pc = pOp->p2 - 1;
69411   }
69412   break;
69413 }
69414
69415 /* Opcode: IfZero P1 P2 P3 * *
69416 **
69417 ** The register P1 must contain an integer.  Add literal P3 to the
69418 ** value in register P1.  If the result is exactly 0, jump to P2. 
69419 **
69420 ** It is illegal to use this instruction on a register that does
69421 ** not contain an integer.  An assertion fault will result if you try.
69422 */
69423 case OP_IfZero: {        /* jump, in1 */
69424   pIn1 = &aMem[pOp->p1];
69425   assert( pIn1->flags&MEM_Int );
69426   pIn1->u.i += pOp->p3;
69427   if( pIn1->u.i==0 ){
69428      pc = pOp->p2 - 1;
69429   }
69430   break;
69431 }
69432
69433 /* Opcode: AggStep * P2 P3 P4 P5
69434 **
69435 ** Execute the step function for an aggregate.  The
69436 ** function has P5 arguments.   P4 is a pointer to the FuncDef
69437 ** structure that specifies the function.  Use register
69438 ** P3 as the accumulator.
69439 **
69440 ** The P5 arguments are taken from register P2 and its
69441 ** successors.
69442 */
69443 case OP_AggStep: {
69444 #if 0  /* local variables moved into u.cg */
69445   int n;
69446   int i;
69447   Mem *pMem;
69448   Mem *pRec;
69449   sqlite3_context ctx;
69450   sqlite3_value **apVal;
69451 #endif /* local variables moved into u.cg */
69452
69453   u.cg.n = pOp->p5;
69454   assert( u.cg.n>=0 );
69455   u.cg.pRec = &aMem[pOp->p2];
69456   u.cg.apVal = p->apArg;
69457   assert( u.cg.apVal || u.cg.n==0 );
69458   for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
69459     assert( memIsValid(u.cg.pRec) );
69460     u.cg.apVal[u.cg.i] = u.cg.pRec;
69461     memAboutToChange(p, u.cg.pRec);
69462     sqlite3VdbeMemStoreType(u.cg.pRec);
69463   }
69464   u.cg.ctx.pFunc = pOp->p4.pFunc;
69465   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69466   u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
69467   u.cg.pMem->n++;
69468   u.cg.ctx.s.flags = MEM_Null;
69469   u.cg.ctx.s.z = 0;
69470   u.cg.ctx.s.zMalloc = 0;
69471   u.cg.ctx.s.xDel = 0;
69472   u.cg.ctx.s.db = db;
69473   u.cg.ctx.isError = 0;
69474   u.cg.ctx.pColl = 0;
69475   u.cg.ctx.skipFlag = 0;
69476   if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
69477     assert( pOp>p->aOp );
69478     assert( pOp[-1].p4type==P4_COLLSEQ );
69479     assert( pOp[-1].opcode==OP_CollSeq );
69480     u.cg.ctx.pColl = pOp[-1].p4.pColl;
69481   }
69482   (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
69483   if( u.cg.ctx.isError ){
69484     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
69485     rc = u.cg.ctx.isError;
69486   }
69487   if( u.cg.ctx.skipFlag ){
69488     assert( pOp[-1].opcode==OP_CollSeq );
69489     u.cg.i = pOp[-1].p1;
69490     if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
69491   }
69492
69493   sqlite3VdbeMemRelease(&u.cg.ctx.s);
69494
69495   break;
69496 }
69497
69498 /* Opcode: AggFinal P1 P2 * P4 *
69499 **
69500 ** Execute the finalizer function for an aggregate.  P1 is
69501 ** the memory location that is the accumulator for the aggregate.
69502 **
69503 ** P2 is the number of arguments that the step function takes and
69504 ** P4 is a pointer to the FuncDef for this function.  The P2
69505 ** argument is not used by this opcode.  It is only there to disambiguate
69506 ** functions that can take varying numbers of arguments.  The
69507 ** P4 argument is only needed for the degenerate case where
69508 ** the step function was not previously called.
69509 */
69510 case OP_AggFinal: {
69511 #if 0  /* local variables moved into u.ch */
69512   Mem *pMem;
69513 #endif /* local variables moved into u.ch */
69514   assert( pOp->p1>0 && pOp->p1<=p->nMem );
69515   u.ch.pMem = &aMem[pOp->p1];
69516   assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69517   rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
69518   if( rc ){
69519     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
69520   }
69521   sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
69522   UPDATE_MAX_BLOBSIZE(u.ch.pMem);
69523   if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
69524     goto too_big;
69525   }
69526   break;
69527 }
69528
69529 #ifndef SQLITE_OMIT_WAL
69530 /* Opcode: Checkpoint P1 P2 P3 * *
69531 **
69532 ** Checkpoint database P1. This is a no-op if P1 is not currently in
69533 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
69534 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
69535 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
69536 ** WAL after the checkpoint into mem[P3+1] and the number of pages
69537 ** in the WAL that have been checkpointed after the checkpoint
69538 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
69539 ** mem[P3+2] are initialized to -1.
69540 */
69541 case OP_Checkpoint: {
69542 #if 0  /* local variables moved into u.ci */
69543   int i;                          /* Loop counter */
69544   int aRes[3];                    /* Results */
69545   Mem *pMem;                      /* Write results here */
69546 #endif /* local variables moved into u.ci */
69547
69548   u.ci.aRes[0] = 0;
69549   u.ci.aRes[1] = u.ci.aRes[2] = -1;
69550   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
69551        || pOp->p2==SQLITE_CHECKPOINT_FULL
69552        || pOp->p2==SQLITE_CHECKPOINT_RESTART
69553   );
69554   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
69555   if( rc==SQLITE_BUSY ){
69556     rc = SQLITE_OK;
69557     u.ci.aRes[0] = 1;
69558   }
69559   for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
69560     sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
69561   }
69562   break;
69563 };  
69564 #endif
69565
69566 #ifndef SQLITE_OMIT_PRAGMA
69567 /* Opcode: JournalMode P1 P2 P3 * P5
69568 **
69569 ** Change the journal mode of database P1 to P3. P3 must be one of the
69570 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
69571 ** modes (delete, truncate, persist, off and memory), this is a simple
69572 ** operation. No IO is required.
69573 **
69574 ** If changing into or out of WAL mode the procedure is more complicated.
69575 **
69576 ** Write a string containing the final journal-mode to register P2.
69577 */
69578 case OP_JournalMode: {    /* out2-prerelease */
69579 #if 0  /* local variables moved into u.cj */
69580   Btree *pBt;                     /* Btree to change journal mode of */
69581   Pager *pPager;                  /* Pager associated with pBt */
69582   int eNew;                       /* New journal mode */
69583   int eOld;                       /* The old journal mode */
69584 #ifndef SQLITE_OMIT_WAL
69585   const char *zFilename;          /* Name of database file for pPager */
69586 #endif
69587 #endif /* local variables moved into u.cj */
69588
69589   u.cj.eNew = pOp->p3;
69590   assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
69591        || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
69592        || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
69593        || u.cj.eNew==PAGER_JOURNALMODE_OFF
69594        || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
69595        || u.cj.eNew==PAGER_JOURNALMODE_WAL
69596        || u.cj.eNew==PAGER_JOURNALMODE_QUERY
69597   );
69598   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69599
69600   u.cj.pBt = db->aDb[pOp->p1].pBt;
69601   u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
69602   u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
69603   if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
69604   if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
69605
69606 #ifndef SQLITE_OMIT_WAL
69607   u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
69608
69609   /* Do not allow a transition to journal_mode=WAL for a database
69610   ** in temporary storage or if the VFS does not support shared memory
69611   */
69612   if( u.cj.eNew==PAGER_JOURNALMODE_WAL
69613    && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
69614        || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
69615   ){
69616     u.cj.eNew = u.cj.eOld;
69617   }
69618
69619   if( (u.cj.eNew!=u.cj.eOld)
69620    && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
69621   ){
69622     if( !db->autoCommit || db->activeVdbeCnt>1 ){
69623       rc = SQLITE_ERROR;
69624       sqlite3SetString(&p->zErrMsg, db,
69625           "cannot change %s wal mode from within a transaction",
69626           (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69627       );
69628       break;
69629     }else{
69630
69631       if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
69632         /* If leaving WAL mode, close the log file. If successful, the call
69633         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69634         ** file. An EXCLUSIVE lock may still be held on the database file
69635         ** after a successful return.
69636         */
69637         rc = sqlite3PagerCloseWal(u.cj.pPager);
69638         if( rc==SQLITE_OK ){
69639           sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69640         }
69641       }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
69642         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
69643         ** as an intermediate */
69644         sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
69645       }
69646
69647       /* Open a transaction on the database file. Regardless of the journal
69648       ** mode, this transaction always uses a rollback journal.
69649       */
69650       assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
69651       if( rc==SQLITE_OK ){
69652         rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69653       }
69654     }
69655   }
69656 #endif /* ifndef SQLITE_OMIT_WAL */
69657
69658   if( rc ){
69659     u.cj.eNew = u.cj.eOld;
69660   }
69661   u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69662
69663   pOut = &aMem[pOp->p2];
69664   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69665   pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
69666   pOut->n = sqlite3Strlen30(pOut->z);
69667   pOut->enc = SQLITE_UTF8;
69668   sqlite3VdbeChangeEncoding(pOut, encoding);
69669   break;
69670 };
69671 #endif /* SQLITE_OMIT_PRAGMA */
69672
69673 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69674 /* Opcode: Vacuum * * * * *
69675 **
69676 ** Vacuum the entire database.  This opcode will cause other virtual
69677 ** machines to be created and run.  It may not be called from within
69678 ** a transaction.
69679 */
69680 case OP_Vacuum: {
69681   rc = sqlite3RunVacuum(&p->zErrMsg, db);
69682   break;
69683 }
69684 #endif
69685
69686 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69687 /* Opcode: IncrVacuum P1 P2 * * *
69688 **
69689 ** Perform a single step of the incremental vacuum procedure on
69690 ** the P1 database. If the vacuum has finished, jump to instruction
69691 ** P2. Otherwise, fall through to the next instruction.
69692 */
69693 case OP_IncrVacuum: {        /* jump */
69694 #if 0  /* local variables moved into u.ck */
69695   Btree *pBt;
69696 #endif /* local variables moved into u.ck */
69697
69698   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69699   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69700   u.ck.pBt = db->aDb[pOp->p1].pBt;
69701   rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
69702   if( rc==SQLITE_DONE ){
69703     pc = pOp->p2 - 1;
69704     rc = SQLITE_OK;
69705   }
69706   break;
69707 }
69708 #endif
69709
69710 /* Opcode: Expire P1 * * * *
69711 **
69712 ** Cause precompiled statements to become expired. An expired statement
69713 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
69714 ** (via sqlite3_step()).
69715 ** 
69716 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69717 ** then only the currently executing statement is affected. 
69718 */
69719 case OP_Expire: {
69720   if( !pOp->p1 ){
69721     sqlite3ExpirePreparedStatements(db);
69722   }else{
69723     p->expired = 1;
69724   }
69725   break;
69726 }
69727
69728 #ifndef SQLITE_OMIT_SHARED_CACHE
69729 /* Opcode: TableLock P1 P2 P3 P4 *
69730 **
69731 ** Obtain a lock on a particular table. This instruction is only used when
69732 ** the shared-cache feature is enabled. 
69733 **
69734 ** P1 is the index of the database in sqlite3.aDb[] of the database
69735 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
69736 ** a write lock if P3==1.
69737 **
69738 ** P2 contains the root-page of the table to lock.
69739 **
69740 ** P4 contains a pointer to the name of the table being locked. This is only
69741 ** used to generate an error message if the lock cannot be obtained.
69742 */
69743 case OP_TableLock: {
69744   u8 isWriteLock = (u8)pOp->p3;
69745   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69746     int p1 = pOp->p1; 
69747     assert( p1>=0 && p1<db->nDb );
69748     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69749     assert( isWriteLock==0 || isWriteLock==1 );
69750     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69751     if( (rc&0xFF)==SQLITE_LOCKED ){
69752       const char *z = pOp->p4.z;
69753       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69754     }
69755   }
69756   break;
69757 }
69758 #endif /* SQLITE_OMIT_SHARED_CACHE */
69759
69760 #ifndef SQLITE_OMIT_VIRTUALTABLE
69761 /* Opcode: VBegin * * * P4 *
69762 **
69763 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
69764 ** xBegin method for that table.
69765 **
69766 ** Also, whether or not P4 is set, check that this is not being called from
69767 ** within a callback to a virtual table xSync() method. If it is, the error
69768 ** code will be set to SQLITE_LOCKED.
69769 */
69770 case OP_VBegin: {
69771 #if 0  /* local variables moved into u.cl */
69772   VTable *pVTab;
69773 #endif /* local variables moved into u.cl */
69774   u.cl.pVTab = pOp->p4.pVtab;
69775   rc = sqlite3VtabBegin(db, u.cl.pVTab);
69776   if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
69777   break;
69778 }
69779 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69780
69781 #ifndef SQLITE_OMIT_VIRTUALTABLE
69782 /* Opcode: VCreate P1 * * P4 *
69783 **
69784 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69785 ** for that table.
69786 */
69787 case OP_VCreate: {
69788   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69789   break;
69790 }
69791 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69792
69793 #ifndef SQLITE_OMIT_VIRTUALTABLE
69794 /* Opcode: VDestroy P1 * * P4 *
69795 **
69796 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
69797 ** of that table.
69798 */
69799 case OP_VDestroy: {
69800   p->inVtabMethod = 2;
69801   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69802   p->inVtabMethod = 0;
69803   break;
69804 }
69805 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69806
69807 #ifndef SQLITE_OMIT_VIRTUALTABLE
69808 /* Opcode: VOpen P1 * * P4 *
69809 **
69810 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69811 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
69812 ** table and stores that cursor in P1.
69813 */
69814 case OP_VOpen: {
69815 #if 0  /* local variables moved into u.cm */
69816   VdbeCursor *pCur;
69817   sqlite3_vtab_cursor *pVtabCursor;
69818   sqlite3_vtab *pVtab;
69819   sqlite3_module *pModule;
69820 #endif /* local variables moved into u.cm */
69821
69822   u.cm.pCur = 0;
69823   u.cm.pVtabCursor = 0;
69824   u.cm.pVtab = pOp->p4.pVtab->pVtab;
69825   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
69826   assert(u.cm.pVtab && u.cm.pModule);
69827   rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
69828   importVtabErrMsg(p, u.cm.pVtab);
69829   if( SQLITE_OK==rc ){
69830     /* Initialize sqlite3_vtab_cursor base class */
69831     u.cm.pVtabCursor->pVtab = u.cm.pVtab;
69832
69833     /* Initialise vdbe cursor object */
69834     u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69835     if( u.cm.pCur ){
69836       u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
69837       u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
69838     }else{
69839       db->mallocFailed = 1;
69840       u.cm.pModule->xClose(u.cm.pVtabCursor);
69841     }
69842   }
69843   break;
69844 }
69845 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69846
69847 #ifndef SQLITE_OMIT_VIRTUALTABLE
69848 /* Opcode: VFilter P1 P2 P3 P4 *
69849 **
69850 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
69851 ** the filtered result set is empty.
69852 **
69853 ** P4 is either NULL or a string that was generated by the xBestIndex
69854 ** method of the module.  The interpretation of the P4 string is left
69855 ** to the module implementation.
69856 **
69857 ** This opcode invokes the xFilter method on the virtual table specified
69858 ** by P1.  The integer query plan parameter to xFilter is stored in register
69859 ** P3. Register P3+1 stores the argc parameter to be passed to the
69860 ** xFilter method. Registers P3+2..P3+1+argc are the argc
69861 ** additional parameters which are passed to
69862 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
69863 **
69864 ** A jump is made to P2 if the result set after filtering would be empty.
69865 */
69866 case OP_VFilter: {   /* jump */
69867 #if 0  /* local variables moved into u.cn */
69868   int nArg;
69869   int iQuery;
69870   const sqlite3_module *pModule;
69871   Mem *pQuery;
69872   Mem *pArgc;
69873   sqlite3_vtab_cursor *pVtabCursor;
69874   sqlite3_vtab *pVtab;
69875   VdbeCursor *pCur;
69876   int res;
69877   int i;
69878   Mem **apArg;
69879 #endif /* local variables moved into u.cn */
69880
69881   u.cn.pQuery = &aMem[pOp->p3];
69882   u.cn.pArgc = &u.cn.pQuery[1];
69883   u.cn.pCur = p->apCsr[pOp->p1];
69884   assert( memIsValid(u.cn.pQuery) );
69885   REGISTER_TRACE(pOp->p3, u.cn.pQuery);
69886   assert( u.cn.pCur->pVtabCursor );
69887   u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
69888   u.cn.pVtab = u.cn.pVtabCursor->pVtab;
69889   u.cn.pModule = u.cn.pVtab->pModule;
69890
69891   /* Grab the index number and argc parameters */
69892   assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
69893   u.cn.nArg = (int)u.cn.pArgc->u.i;
69894   u.cn.iQuery = (int)u.cn.pQuery->u.i;
69895
69896   /* Invoke the xFilter method */
69897   {
69898     u.cn.res = 0;
69899     u.cn.apArg = p->apArg;
69900     for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
69901       u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
69902       sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
69903     }
69904
69905     p->inVtabMethod = 1;
69906     rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
69907     p->inVtabMethod = 0;
69908     importVtabErrMsg(p, u.cn.pVtab);
69909     if( rc==SQLITE_OK ){
69910       u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
69911     }
69912
69913     if( u.cn.res ){
69914       pc = pOp->p2 - 1;
69915     }
69916   }
69917   u.cn.pCur->nullRow = 0;
69918
69919   break;
69920 }
69921 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69922
69923 #ifndef SQLITE_OMIT_VIRTUALTABLE
69924 /* Opcode: VColumn P1 P2 P3 * *
69925 **
69926 ** Store the value of the P2-th column of
69927 ** the row of the virtual-table that the 
69928 ** P1 cursor is pointing to into register P3.
69929 */
69930 case OP_VColumn: {
69931 #if 0  /* local variables moved into u.co */
69932   sqlite3_vtab *pVtab;
69933   const sqlite3_module *pModule;
69934   Mem *pDest;
69935   sqlite3_context sContext;
69936 #endif /* local variables moved into u.co */
69937
69938   VdbeCursor *pCur = p->apCsr[pOp->p1];
69939   assert( pCur->pVtabCursor );
69940   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69941   u.co.pDest = &aMem[pOp->p3];
69942   memAboutToChange(p, u.co.pDest);
69943   if( pCur->nullRow ){
69944     sqlite3VdbeMemSetNull(u.co.pDest);
69945     break;
69946   }
69947   u.co.pVtab = pCur->pVtabCursor->pVtab;
69948   u.co.pModule = u.co.pVtab->pModule;
69949   assert( u.co.pModule->xColumn );
69950   memset(&u.co.sContext, 0, sizeof(u.co.sContext));
69951
69952   /* The output cell may already have a buffer allocated. Move
69953   ** the current contents to u.co.sContext.s so in case the user-function
69954   ** can use the already allocated buffer instead of allocating a
69955   ** new one.
69956   */
69957   sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
69958   MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
69959
69960   rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
69961   importVtabErrMsg(p, u.co.pVtab);
69962   if( u.co.sContext.isError ){
69963     rc = u.co.sContext.isError;
69964   }
69965
69966   /* Copy the result of the function to the P3 register. We
69967   ** do this regardless of whether or not an error occurred to ensure any
69968   ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
69969   */
69970   sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
69971   sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
69972   REGISTER_TRACE(pOp->p3, u.co.pDest);
69973   UPDATE_MAX_BLOBSIZE(u.co.pDest);
69974
69975   if( sqlite3VdbeMemTooBig(u.co.pDest) ){
69976     goto too_big;
69977   }
69978   break;
69979 }
69980 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69981
69982 #ifndef SQLITE_OMIT_VIRTUALTABLE
69983 /* Opcode: VNext P1 P2 * * *
69984 **
69985 ** Advance virtual table P1 to the next row in its result set and
69986 ** jump to instruction P2.  Or, if the virtual table has reached
69987 ** the end of its result set, then fall through to the next instruction.
69988 */
69989 case OP_VNext: {   /* jump */
69990 #if 0  /* local variables moved into u.cp */
69991   sqlite3_vtab *pVtab;
69992   const sqlite3_module *pModule;
69993   int res;
69994   VdbeCursor *pCur;
69995 #endif /* local variables moved into u.cp */
69996
69997   u.cp.res = 0;
69998   u.cp.pCur = p->apCsr[pOp->p1];
69999   assert( u.cp.pCur->pVtabCursor );
70000   if( u.cp.pCur->nullRow ){
70001     break;
70002   }
70003   u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
70004   u.cp.pModule = u.cp.pVtab->pModule;
70005   assert( u.cp.pModule->xNext );
70006
70007   /* Invoke the xNext() method of the module. There is no way for the
70008   ** underlying implementation to return an error if one occurs during
70009   ** xNext(). Instead, if an error occurs, true is returned (indicating that
70010   ** data is available) and the error code returned when xColumn or
70011   ** some other method is next invoked on the save virtual table cursor.
70012   */
70013   p->inVtabMethod = 1;
70014   rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
70015   p->inVtabMethod = 0;
70016   importVtabErrMsg(p, u.cp.pVtab);
70017   if( rc==SQLITE_OK ){
70018     u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
70019   }
70020
70021   if( !u.cp.res ){
70022     /* If there is data, jump to P2 */
70023     pc = pOp->p2 - 1;
70024   }
70025   break;
70026 }
70027 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70028
70029 #ifndef SQLITE_OMIT_VIRTUALTABLE
70030 /* Opcode: VRename P1 * * P4 *
70031 **
70032 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70033 ** This opcode invokes the corresponding xRename method. The value
70034 ** in register P1 is passed as the zName argument to the xRename method.
70035 */
70036 case OP_VRename: {
70037 #if 0  /* local variables moved into u.cq */
70038   sqlite3_vtab *pVtab;
70039   Mem *pName;
70040 #endif /* local variables moved into u.cq */
70041
70042   u.cq.pVtab = pOp->p4.pVtab->pVtab;
70043   u.cq.pName = &aMem[pOp->p1];
70044   assert( u.cq.pVtab->pModule->xRename );
70045   assert( memIsValid(u.cq.pName) );
70046   REGISTER_TRACE(pOp->p1, u.cq.pName);
70047   assert( u.cq.pName->flags & MEM_Str );
70048   testcase( u.cq.pName->enc==SQLITE_UTF8 );
70049   testcase( u.cq.pName->enc==SQLITE_UTF16BE );
70050   testcase( u.cq.pName->enc==SQLITE_UTF16LE );
70051   rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
70052   if( rc==SQLITE_OK ){
70053     rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
70054     importVtabErrMsg(p, u.cq.pVtab);
70055     p->expired = 0;
70056   }
70057   break;
70058 }
70059 #endif
70060
70061 #ifndef SQLITE_OMIT_VIRTUALTABLE
70062 /* Opcode: VUpdate P1 P2 P3 P4 *
70063 **
70064 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70065 ** This opcode invokes the corresponding xUpdate method. P2 values
70066 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
70067 ** invocation. The value in register (P3+P2-1) corresponds to the 
70068 ** p2th element of the argv array passed to xUpdate.
70069 **
70070 ** The xUpdate method will do a DELETE or an INSERT or both.
70071 ** The argv[0] element (which corresponds to memory cell P3)
70072 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
70073 ** deletion occurs.  The argv[1] element is the rowid of the new 
70074 ** row.  This can be NULL to have the virtual table select the new 
70075 ** rowid for itself.  The subsequent elements in the array are 
70076 ** the values of columns in the new row.
70077 **
70078 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
70079 ** a row to delete.
70080 **
70081 ** P1 is a boolean flag. If it is set to true and the xUpdate call
70082 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
70083 ** is set to the value of the rowid for the row just inserted.
70084 */
70085 case OP_VUpdate: {
70086 #if 0  /* local variables moved into u.cr */
70087   sqlite3_vtab *pVtab;
70088   sqlite3_module *pModule;
70089   int nArg;
70090   int i;
70091   sqlite_int64 rowid;
70092   Mem **apArg;
70093   Mem *pX;
70094 #endif /* local variables moved into u.cr */
70095
70096   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70097        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70098   );
70099   u.cr.pVtab = pOp->p4.pVtab->pVtab;
70100   u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
70101   u.cr.nArg = pOp->p2;
70102   assert( pOp->p4type==P4_VTAB );
70103   if( ALWAYS(u.cr.pModule->xUpdate) ){
70104     u8 vtabOnConflict = db->vtabOnConflict;
70105     u.cr.apArg = p->apArg;
70106     u.cr.pX = &aMem[pOp->p3];
70107     for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
70108       assert( memIsValid(u.cr.pX) );
70109       memAboutToChange(p, u.cr.pX);
70110       sqlite3VdbeMemStoreType(u.cr.pX);
70111       u.cr.apArg[u.cr.i] = u.cr.pX;
70112       u.cr.pX++;
70113     }
70114     db->vtabOnConflict = pOp->p5;
70115     rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
70116     db->vtabOnConflict = vtabOnConflict;
70117     importVtabErrMsg(p, u.cr.pVtab);
70118     if( rc==SQLITE_OK && pOp->p1 ){
70119       assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
70120       db->lastRowid = lastRowid = u.cr.rowid;
70121     }
70122     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70123       if( pOp->p5==OE_Ignore ){
70124         rc = SQLITE_OK;
70125       }else{
70126         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70127       }
70128     }else{
70129       p->nChange++;
70130     }
70131   }
70132   break;
70133 }
70134 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70135
70136 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70137 /* Opcode: Pagecount P1 P2 * * *
70138 **
70139 ** Write the current number of pages in database P1 to memory cell P2.
70140 */
70141 case OP_Pagecount: {            /* out2-prerelease */
70142   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
70143   break;
70144 }
70145 #endif
70146
70147
70148 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70149 /* Opcode: MaxPgcnt P1 P2 P3 * *
70150 **
70151 ** Try to set the maximum page count for database P1 to the value in P3.
70152 ** Do not let the maximum page count fall below the current page count and
70153 ** do not change the maximum page count value if P3==0.
70154 **
70155 ** Store the maximum page count after the change in register P2.
70156 */
70157 case OP_MaxPgcnt: {            /* out2-prerelease */
70158   unsigned int newMax;
70159   Btree *pBt;
70160
70161   pBt = db->aDb[pOp->p1].pBt;
70162   newMax = 0;
70163   if( pOp->p3 ){
70164     newMax = sqlite3BtreeLastPage(pBt);
70165     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
70166   }
70167   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
70168   break;
70169 }
70170 #endif
70171
70172
70173 #ifndef SQLITE_OMIT_TRACE
70174 /* Opcode: Trace * * * P4 *
70175 **
70176 ** If tracing is enabled (by the sqlite3_trace()) interface, then
70177 ** the UTF-8 string contained in P4 is emitted on the trace callback.
70178 */
70179 case OP_Trace: {
70180 #if 0  /* local variables moved into u.cs */
70181   char *zTrace;
70182   char *z;
70183 #endif /* local variables moved into u.cs */
70184
70185   if( db->xTrace
70186    && !p->doingRerun
70187    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70188   ){
70189     u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
70190     db->xTrace(db->pTraceArg, u.cs.z);
70191     sqlite3DbFree(db, u.cs.z);
70192   }
70193 #ifdef SQLITE_DEBUG
70194   if( (db->flags & SQLITE_SqlTrace)!=0
70195    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70196   ){
70197     sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
70198   }
70199 #endif /* SQLITE_DEBUG */
70200   break;
70201 }
70202 #endif
70203
70204
70205 /* Opcode: Noop * * * * *
70206 **
70207 ** Do nothing.  This instruction is often useful as a jump
70208 ** destination.
70209 */
70210 /*
70211 ** The magic Explain opcode are only inserted when explain==2 (which
70212 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
70213 ** This opcode records information from the optimizer.  It is the
70214 ** the same as a no-op.  This opcodesnever appears in a real VM program.
70215 */
70216 default: {          /* This is really OP_Noop and OP_Explain */
70217   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
70218   break;
70219 }
70220
70221 /*****************************************************************************
70222 ** The cases of the switch statement above this line should all be indented
70223 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
70224 ** readability.  From this point on down, the normal indentation rules are
70225 ** restored.
70226 *****************************************************************************/
70227     }
70228
70229 #ifdef VDBE_PROFILE
70230     {
70231       u64 elapsed = sqlite3Hwtime() - start;
70232       pOp->cycles += elapsed;
70233       pOp->cnt++;
70234 #if 0
70235         fprintf(stdout, "%10llu ", elapsed);
70236         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
70237 #endif
70238     }
70239 #endif
70240
70241     /* The following code adds nothing to the actual functionality
70242     ** of the program.  It is only here for testing and debugging.
70243     ** On the other hand, it does burn CPU cycles every time through
70244     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
70245     */
70246 #ifndef NDEBUG
70247     assert( pc>=-1 && pc<p->nOp );
70248
70249 #ifdef SQLITE_DEBUG
70250     if( p->trace ){
70251       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
70252       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
70253         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
70254       }
70255       if( pOp->opflags & OPFLG_OUT3 ){
70256         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
70257       }
70258     }
70259 #endif  /* SQLITE_DEBUG */
70260 #endif  /* NDEBUG */
70261   }  /* The end of the for(;;) loop the loops through opcodes */
70262
70263   /* If we reach this point, it means that execution is finished with
70264   ** an error of some kind.
70265   */
70266 vdbe_error_halt:
70267   assert( rc );
70268   p->rc = rc;
70269   testcase( sqlite3GlobalConfig.xLog!=0 );
70270   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
70271                    pc, p->zSql, p->zErrMsg);
70272   sqlite3VdbeHalt(p);
70273   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
70274   rc = SQLITE_ERROR;
70275   if( resetSchemaOnFault>0 ){
70276     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
70277   }
70278
70279   /* This is the only way out of this procedure.  We have to
70280   ** release the mutexes on btrees that were acquired at the
70281   ** top. */
70282 vdbe_return:
70283   db->lastRowid = lastRowid;
70284   sqlite3VdbeLeave(p);
70285   return rc;
70286
70287   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
70288   ** is encountered.
70289   */
70290 too_big:
70291   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
70292   rc = SQLITE_TOOBIG;
70293   goto vdbe_error_halt;
70294
70295   /* Jump to here if a malloc() fails.
70296   */
70297 no_mem:
70298   db->mallocFailed = 1;
70299   sqlite3SetString(&p->zErrMsg, db, "out of memory");
70300   rc = SQLITE_NOMEM;
70301   goto vdbe_error_halt;
70302
70303   /* Jump to here for any other kind of fatal error.  The "rc" variable
70304   ** should hold the error number.
70305   */
70306 abort_due_to_error:
70307   assert( p->zErrMsg==0 );
70308   if( db->mallocFailed ) rc = SQLITE_NOMEM;
70309   if( rc!=SQLITE_IOERR_NOMEM ){
70310     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70311   }
70312   goto vdbe_error_halt;
70313
70314   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
70315   ** flag.
70316   */
70317 abort_due_to_interrupt:
70318   assert( db->u1.isInterrupted );
70319   rc = SQLITE_INTERRUPT;
70320   p->rc = rc;
70321   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70322   goto vdbe_error_halt;
70323 }
70324
70325 /************** End of vdbe.c ************************************************/
70326 /************** Begin file vdbeblob.c ****************************************/
70327 /*
70328 ** 2007 May 1
70329 **
70330 ** The author disclaims copyright to this source code.  In place of
70331 ** a legal notice, here is a blessing:
70332 **
70333 **    May you do good and not evil.
70334 **    May you find forgiveness for yourself and forgive others.
70335 **    May you share freely, never taking more than you give.
70336 **
70337 *************************************************************************
70338 **
70339 ** This file contains code used to implement incremental BLOB I/O.
70340 */
70341
70342
70343 #ifndef SQLITE_OMIT_INCRBLOB
70344
70345 /*
70346 ** Valid sqlite3_blob* handles point to Incrblob structures.
70347 */
70348 typedef struct Incrblob Incrblob;
70349 struct Incrblob {
70350   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
70351   int nByte;              /* Size of open blob, in bytes */
70352   int iOffset;            /* Byte offset of blob in cursor data */
70353   int iCol;               /* Table column this handle is open on */
70354   BtCursor *pCsr;         /* Cursor pointing at blob row */
70355   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
70356   sqlite3 *db;            /* The associated database */
70357 };
70358
70359
70360 /*
70361 ** This function is used by both blob_open() and blob_reopen(). It seeks
70362 ** the b-tree cursor associated with blob handle p to point to row iRow.
70363 ** If successful, SQLITE_OK is returned and subsequent calls to
70364 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
70365 **
70366 ** If an error occurs, or if the specified row does not exist or does not
70367 ** contain a value of type TEXT or BLOB in the column nominated when the
70368 ** blob handle was opened, then an error code is returned and *pzErr may
70369 ** be set to point to a buffer containing an error message. It is the
70370 ** responsibility of the caller to free the error message buffer using
70371 ** sqlite3DbFree().
70372 **
70373 ** If an error does occur, then the b-tree cursor is closed. All subsequent
70374 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
70375 ** immediately return SQLITE_ABORT.
70376 */
70377 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
70378   int rc;                         /* Error code */
70379   char *zErr = 0;                 /* Error message */
70380   Vdbe *v = (Vdbe *)p->pStmt;
70381
70382   /* Set the value of the SQL statements only variable to integer iRow. 
70383   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
70384   ** triggering asserts related to mutexes.
70385   */
70386   assert( v->aVar[0].flags&MEM_Int );
70387   v->aVar[0].u.i = iRow;
70388
70389   rc = sqlite3_step(p->pStmt);
70390   if( rc==SQLITE_ROW ){
70391     u32 type = v->apCsr[0]->aType[p->iCol];
70392     if( type<12 ){
70393       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
70394           type==0?"null": type==7?"real": "integer"
70395       );
70396       rc = SQLITE_ERROR;
70397       sqlite3_finalize(p->pStmt);
70398       p->pStmt = 0;
70399     }else{
70400       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
70401       p->nByte = sqlite3VdbeSerialTypeLen(type);
70402       p->pCsr =  v->apCsr[0]->pCursor;
70403       sqlite3BtreeEnterCursor(p->pCsr);
70404       sqlite3BtreeCacheOverflow(p->pCsr);
70405       sqlite3BtreeLeaveCursor(p->pCsr);
70406     }
70407   }
70408
70409   if( rc==SQLITE_ROW ){
70410     rc = SQLITE_OK;
70411   }else if( p->pStmt ){
70412     rc = sqlite3_finalize(p->pStmt);
70413     p->pStmt = 0;
70414     if( rc==SQLITE_OK ){
70415       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
70416       rc = SQLITE_ERROR;
70417     }else{
70418       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
70419     }
70420   }
70421
70422   assert( rc!=SQLITE_OK || zErr==0 );
70423   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
70424
70425   *pzErr = zErr;
70426   return rc;
70427 }
70428
70429 /*
70430 ** Open a blob handle.
70431 */
70432 SQLITE_API int sqlite3_blob_open(
70433   sqlite3* db,            /* The database connection */
70434   const char *zDb,        /* The attached database containing the blob */
70435   const char *zTable,     /* The table containing the blob */
70436   const char *zColumn,    /* The column containing the blob */
70437   sqlite_int64 iRow,      /* The row containing the glob */
70438   int flags,              /* True -> read/write access, false -> read-only */
70439   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
70440 ){
70441   int nAttempt = 0;
70442   int iCol;               /* Index of zColumn in row-record */
70443
70444   /* This VDBE program seeks a btree cursor to the identified 
70445   ** db/table/row entry. The reason for using a vdbe program instead
70446   ** of writing code to use the b-tree layer directly is that the
70447   ** vdbe program will take advantage of the various transaction,
70448   ** locking and error handling infrastructure built into the vdbe.
70449   **
70450   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
70451   ** Code external to the Vdbe then "borrows" the b-tree cursor and
70452   ** uses it to implement the blob_read(), blob_write() and 
70453   ** blob_bytes() functions.
70454   **
70455   ** The sqlite3_blob_close() function finalizes the vdbe program,
70456   ** which closes the b-tree cursor and (possibly) commits the 
70457   ** transaction.
70458   */
70459   static const VdbeOpList openBlob[] = {
70460     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
70461     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
70462     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
70463
70464     /* One of the following two instructions is replaced by an OP_Noop. */
70465     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
70466     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
70467
70468     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
70469     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
70470     {OP_Column, 0, 0, 1},          /* 7  */
70471     {OP_ResultRow, 1, 0, 0},       /* 8  */
70472     {OP_Goto, 0, 5, 0},            /* 9  */
70473     {OP_Close, 0, 0, 0},           /* 10 */
70474     {OP_Halt, 0, 0, 0},            /* 11 */
70475   };
70476
70477   int rc = SQLITE_OK;
70478   char *zErr = 0;
70479   Table *pTab;
70480   Parse *pParse = 0;
70481   Incrblob *pBlob = 0;
70482
70483   flags = !!flags;                /* flags = (flags ? 1 : 0); */
70484   *ppBlob = 0;
70485
70486   sqlite3_mutex_enter(db->mutex);
70487
70488   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
70489   if( !pBlob ) goto blob_open_out;
70490   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
70491   if( !pParse ) goto blob_open_out;
70492
70493   do {
70494     memset(pParse, 0, sizeof(Parse));
70495     pParse->db = db;
70496     sqlite3DbFree(db, zErr);
70497     zErr = 0;
70498
70499     sqlite3BtreeEnterAll(db);
70500     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
70501     if( pTab && IsVirtual(pTab) ){
70502       pTab = 0;
70503       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
70504     }
70505 #ifndef SQLITE_OMIT_VIEW
70506     if( pTab && pTab->pSelect ){
70507       pTab = 0;
70508       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
70509     }
70510 #endif
70511     if( !pTab ){
70512       if( pParse->zErrMsg ){
70513         sqlite3DbFree(db, zErr);
70514         zErr = pParse->zErrMsg;
70515         pParse->zErrMsg = 0;
70516       }
70517       rc = SQLITE_ERROR;
70518       sqlite3BtreeLeaveAll(db);
70519       goto blob_open_out;
70520     }
70521
70522     /* Now search pTab for the exact column. */
70523     for(iCol=0; iCol<pTab->nCol; iCol++) {
70524       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
70525         break;
70526       }
70527     }
70528     if( iCol==pTab->nCol ){
70529       sqlite3DbFree(db, zErr);
70530       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
70531       rc = SQLITE_ERROR;
70532       sqlite3BtreeLeaveAll(db);
70533       goto blob_open_out;
70534     }
70535
70536     /* If the value is being opened for writing, check that the
70537     ** column is not indexed, and that it is not part of a foreign key. 
70538     ** It is against the rules to open a column to which either of these
70539     ** descriptions applies for writing.  */
70540     if( flags ){
70541       const char *zFault = 0;
70542       Index *pIdx;
70543 #ifndef SQLITE_OMIT_FOREIGN_KEY
70544       if( db->flags&SQLITE_ForeignKeys ){
70545         /* Check that the column is not part of an FK child key definition. It
70546         ** is not necessary to check if it is part of a parent key, as parent
70547         ** key columns must be indexed. The check below will pick up this 
70548         ** case.  */
70549         FKey *pFKey;
70550         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
70551           int j;
70552           for(j=0; j<pFKey->nCol; j++){
70553             if( pFKey->aCol[j].iFrom==iCol ){
70554               zFault = "foreign key";
70555             }
70556           }
70557         }
70558       }
70559 #endif
70560       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70561         int j;
70562         for(j=0; j<pIdx->nColumn; j++){
70563           if( pIdx->aiColumn[j]==iCol ){
70564             zFault = "indexed";
70565           }
70566         }
70567       }
70568       if( zFault ){
70569         sqlite3DbFree(db, zErr);
70570         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
70571         rc = SQLITE_ERROR;
70572         sqlite3BtreeLeaveAll(db);
70573         goto blob_open_out;
70574       }
70575     }
70576
70577     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
70578     assert( pBlob->pStmt || db->mallocFailed );
70579     if( pBlob->pStmt ){
70580       Vdbe *v = (Vdbe *)pBlob->pStmt;
70581       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70582
70583       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
70584
70585
70586       /* Configure the OP_Transaction */
70587       sqlite3VdbeChangeP1(v, 0, iDb);
70588       sqlite3VdbeChangeP2(v, 0, flags);
70589
70590       /* Configure the OP_VerifyCookie */
70591       sqlite3VdbeChangeP1(v, 1, iDb);
70592       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
70593       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
70594
70595       /* Make sure a mutex is held on the table to be accessed */
70596       sqlite3VdbeUsesBtree(v, iDb); 
70597
70598       /* Configure the OP_TableLock instruction */
70599 #ifdef SQLITE_OMIT_SHARED_CACHE
70600       sqlite3VdbeChangeToNoop(v, 2);
70601 #else
70602       sqlite3VdbeChangeP1(v, 2, iDb);
70603       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
70604       sqlite3VdbeChangeP3(v, 2, flags);
70605       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
70606 #endif
70607
70608       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
70609       ** parameter of the other to pTab->tnum.  */
70610       sqlite3VdbeChangeToNoop(v, 4 - flags);
70611       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
70612       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
70613
70614       /* Configure the number of columns. Configure the cursor to
70615       ** think that the table has one more column than it really
70616       ** does. An OP_Column to retrieve this imaginary column will
70617       ** always return an SQL NULL. This is useful because it means
70618       ** we can invoke OP_Column to fill in the vdbe cursors type 
70619       ** and offset cache without causing any IO.
70620       */
70621       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
70622       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
70623       if( !db->mallocFailed ){
70624         pParse->nVar = 1;
70625         pParse->nMem = 1;
70626         pParse->nTab = 1;
70627         sqlite3VdbeMakeReady(v, pParse);
70628       }
70629     }
70630    
70631     pBlob->flags = flags;
70632     pBlob->iCol = iCol;
70633     pBlob->db = db;
70634     sqlite3BtreeLeaveAll(db);
70635     if( db->mallocFailed ){
70636       goto blob_open_out;
70637     }
70638     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70639     rc = blobSeekToRow(pBlob, iRow, &zErr);
70640   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70641
70642 blob_open_out:
70643   if( rc==SQLITE_OK && db->mallocFailed==0 ){
70644     *ppBlob = (sqlite3_blob *)pBlob;
70645   }else{
70646     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70647     sqlite3DbFree(db, pBlob);
70648   }
70649   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70650   sqlite3DbFree(db, zErr);
70651   sqlite3StackFree(db, pParse);
70652   rc = sqlite3ApiExit(db, rc);
70653   sqlite3_mutex_leave(db->mutex);
70654   return rc;
70655 }
70656
70657 /*
70658 ** Close a blob handle that was previously created using
70659 ** sqlite3_blob_open().
70660 */
70661 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70662   Incrblob *p = (Incrblob *)pBlob;
70663   int rc;
70664   sqlite3 *db;
70665
70666   if( p ){
70667     db = p->db;
70668     sqlite3_mutex_enter(db->mutex);
70669     rc = sqlite3_finalize(p->pStmt);
70670     sqlite3DbFree(db, p);
70671     sqlite3_mutex_leave(db->mutex);
70672   }else{
70673     rc = SQLITE_OK;
70674   }
70675   return rc;
70676 }
70677
70678 /*
70679 ** Perform a read or write operation on a blob
70680 */
70681 static int blobReadWrite(
70682   sqlite3_blob *pBlob, 
70683   void *z, 
70684   int n, 
70685   int iOffset, 
70686   int (*xCall)(BtCursor*, u32, u32, void*)
70687 ){
70688   int rc;
70689   Incrblob *p = (Incrblob *)pBlob;
70690   Vdbe *v;
70691   sqlite3 *db;
70692
70693   if( p==0 ) return SQLITE_MISUSE_BKPT;
70694   db = p->db;
70695   sqlite3_mutex_enter(db->mutex);
70696   v = (Vdbe*)p->pStmt;
70697
70698   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70699     /* Request is out of range. Return a transient error. */
70700     rc = SQLITE_ERROR;
70701     sqlite3Error(db, SQLITE_ERROR, 0);
70702   }else if( v==0 ){
70703     /* If there is no statement handle, then the blob-handle has
70704     ** already been invalidated. Return SQLITE_ABORT in this case.
70705     */
70706     rc = SQLITE_ABORT;
70707   }else{
70708     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70709     ** returned, clean-up the statement handle.
70710     */
70711     assert( db == v->db );
70712     sqlite3BtreeEnterCursor(p->pCsr);
70713     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70714     sqlite3BtreeLeaveCursor(p->pCsr);
70715     if( rc==SQLITE_ABORT ){
70716       sqlite3VdbeFinalize(v);
70717       p->pStmt = 0;
70718     }else{
70719       db->errCode = rc;
70720       v->rc = rc;
70721     }
70722   }
70723   rc = sqlite3ApiExit(db, rc);
70724   sqlite3_mutex_leave(db->mutex);
70725   return rc;
70726 }
70727
70728 /*
70729 ** Read data from a blob handle.
70730 */
70731 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70732   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70733 }
70734
70735 /*
70736 ** Write data to a blob handle.
70737 */
70738 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70739   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70740 }
70741
70742 /*
70743 ** Query a blob handle for the size of the data.
70744 **
70745 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70746 ** so no mutex is required for access.
70747 */
70748 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70749   Incrblob *p = (Incrblob *)pBlob;
70750   return (p && p->pStmt) ? p->nByte : 0;
70751 }
70752
70753 /*
70754 ** Move an existing blob handle to point to a different row of the same
70755 ** database table.
70756 **
70757 ** If an error occurs, or if the specified row does not exist or does not
70758 ** contain a blob or text value, then an error code is returned and the
70759 ** database handle error code and message set. If this happens, then all 
70760 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
70761 ** immediately return SQLITE_ABORT.
70762 */
70763 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70764   int rc;
70765   Incrblob *p = (Incrblob *)pBlob;
70766   sqlite3 *db;
70767
70768   if( p==0 ) return SQLITE_MISUSE_BKPT;
70769   db = p->db;
70770   sqlite3_mutex_enter(db->mutex);
70771
70772   if( p->pStmt==0 ){
70773     /* If there is no statement handle, then the blob-handle has
70774     ** already been invalidated. Return SQLITE_ABORT in this case.
70775     */
70776     rc = SQLITE_ABORT;
70777   }else{
70778     char *zErr;
70779     rc = blobSeekToRow(p, iRow, &zErr);
70780     if( rc!=SQLITE_OK ){
70781       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70782       sqlite3DbFree(db, zErr);
70783     }
70784     assert( rc!=SQLITE_SCHEMA );
70785   }
70786
70787   rc = sqlite3ApiExit(db, rc);
70788   assert( rc==SQLITE_OK || p->pStmt==0 );
70789   sqlite3_mutex_leave(db->mutex);
70790   return rc;
70791 }
70792
70793 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70794
70795 /************** End of vdbeblob.c ********************************************/
70796 /************** Begin file vdbesort.c ****************************************/
70797 /*
70798 ** 2011 July 9
70799 **
70800 ** The author disclaims copyright to this source code.  In place of
70801 ** a legal notice, here is a blessing:
70802 **
70803 **    May you do good and not evil.
70804 **    May you find forgiveness for yourself and forgive others.
70805 **    May you share freely, never taking more than you give.
70806 **
70807 *************************************************************************
70808 ** This file contains code for the VdbeSorter object, used in concert with
70809 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70810 ** example, by CREATE INDEX statements on tables too large to fit in main
70811 ** memory).
70812 */
70813
70814
70815 #ifndef SQLITE_OMIT_MERGE_SORT
70816
70817 typedef struct VdbeSorterIter VdbeSorterIter;
70818 typedef struct SorterRecord SorterRecord;
70819 typedef struct FileWriter FileWriter;
70820
70821 /*
70822 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70823 **
70824 ** As keys are added to the sorter, they are written to disk in a series
70825 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70826 ** the same as the cache-size allowed for temporary databases. In order
70827 ** to allow the caller to extract keys from the sorter in sorted order,
70828 ** all PMAs currently stored on disk must be merged together. This comment
70829 ** describes the data structure used to do so. The structure supports 
70830 ** merging any number of arrays in a single pass with no redundant comparison 
70831 ** operations.
70832 **
70833 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70834 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
70835 ** the purposes of the paragraphs below, we assume that the array is actually 
70836 ** N elements in size, where N is the smallest power of 2 greater to or equal 
70837 ** to the number of iterators being merged. The extra aIter[] elements are 
70838 ** treated as if they are empty (always at EOF).
70839 **
70840 ** The aTree[] array is also N elements in size. The value of N is stored in
70841 ** the VdbeSorter.nTree variable.
70842 **
70843 ** The final (N/2) elements of aTree[] contain the results of comparing
70844 ** pairs of iterator keys together. Element i contains the result of 
70845 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70846 ** aTree element is set to the index of it. 
70847 **
70848 ** For the purposes of this comparison, EOF is considered greater than any
70849 ** other key value. If the keys are equal (only possible with two EOF
70850 ** values), it doesn't matter which index is stored.
70851 **
70852 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
70853 ** above contains the index of the smallest of each block of 4 iterators.
70854 ** And so on. So that aTree[1] contains the index of the iterator that 
70855 ** currently points to the smallest key value. aTree[0] is unused.
70856 **
70857 ** Example:
70858 **
70859 **     aIter[0] -> Banana
70860 **     aIter[1] -> Feijoa
70861 **     aIter[2] -> Elderberry
70862 **     aIter[3] -> Currant
70863 **     aIter[4] -> Grapefruit
70864 **     aIter[5] -> Apple
70865 **     aIter[6] -> Durian
70866 **     aIter[7] -> EOF
70867 **
70868 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
70869 **
70870 ** The current element is "Apple" (the value of the key indicated by 
70871 ** iterator 5). When the Next() operation is invoked, iterator 5 will
70872 ** be advanced to the next key in its segment. Say the next key is
70873 ** "Eggplant":
70874 **
70875 **     aIter[5] -> Eggplant
70876 **
70877 ** The contents of aTree[] are updated first by comparing the new iterator
70878 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
70879 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
70880 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
70881 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
70882 ** so the value written into element 1 of the array is 0. As follows:
70883 **
70884 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
70885 **
70886 ** In other words, each time we advance to the next sorter element, log2(N)
70887 ** key comparison operations are required, where N is the number of segments
70888 ** being merged (rounded up to the next power of 2).
70889 */
70890 struct VdbeSorter {
70891   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
70892   i64 iReadOff;                   /* Current read offset within file pTemp1 */
70893   int nInMemory;                  /* Current size of pRecord list as PMA */
70894   int nTree;                      /* Used size of aTree/aIter (power of 2) */
70895   int nPMA;                       /* Number of PMAs stored in pTemp1 */
70896   int mnPmaSize;                  /* Minimum PMA size, in bytes */
70897   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
70898   VdbeSorterIter *aIter;          /* Array of iterators to merge */
70899   int *aTree;                     /* Current state of incremental merge */
70900   sqlite3_file *pTemp1;           /* PMA file 1 */
70901   SorterRecord *pRecord;          /* Head of in-memory record list */
70902   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
70903 };
70904
70905 /*
70906 ** The following type is an iterator for a PMA. It caches the current key in 
70907 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
70908 */
70909 struct VdbeSorterIter {
70910   i64 iReadOff;                   /* Current read offset */
70911   i64 iEof;                       /* 1 byte past EOF for this iterator */
70912   int nAlloc;                     /* Bytes of space at aAlloc */
70913   int nKey;                       /* Number of bytes in key */
70914   sqlite3_file *pFile;            /* File iterator is reading from */
70915   u8 *aAlloc;                     /* Allocated space */
70916   u8 *aKey;                       /* Pointer to current key */
70917   u8 *aBuffer;                    /* Current read buffer */
70918   int nBuffer;                    /* Size of read buffer in bytes */
70919 };
70920
70921 /*
70922 ** An instance of this structure is used to organize the stream of records
70923 ** being written to files by the merge-sort code into aligned, page-sized
70924 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
70925 ** faster on many operating systems.
70926 */
70927 struct FileWriter {
70928   int eFWErr;                     /* Non-zero if in an error state */
70929   u8 *aBuffer;                    /* Pointer to write buffer */
70930   int nBuffer;                    /* Size of write buffer in bytes */
70931   int iBufStart;                  /* First byte of buffer to write */
70932   int iBufEnd;                    /* Last byte of buffer to write */
70933   i64 iWriteOff;                  /* Offset of start of buffer in file */
70934   sqlite3_file *pFile;            /* File to write to */
70935 };
70936
70937 /*
70938 ** A structure to store a single record. All in-memory records are connected
70939 ** together into a linked list headed at VdbeSorter.pRecord using the 
70940 ** SorterRecord.pNext pointer.
70941 */
70942 struct SorterRecord {
70943   void *pVal;
70944   int nVal;
70945   SorterRecord *pNext;
70946 };
70947
70948 /* Minimum allowable value for the VdbeSorter.nWorking variable */
70949 #define SORTER_MIN_WORKING 10
70950
70951 /* Maximum number of segments to merge in a single pass. */
70952 #define SORTER_MAX_MERGE_COUNT 16
70953
70954 /*
70955 ** Free all memory belonging to the VdbeSorterIter object passed as the second
70956 ** argument. All structure fields are set to zero before returning.
70957 */
70958 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
70959   sqlite3DbFree(db, pIter->aAlloc);
70960   sqlite3DbFree(db, pIter->aBuffer);
70961   memset(pIter, 0, sizeof(VdbeSorterIter));
70962 }
70963
70964 /*
70965 ** Read nByte bytes of data from the stream of data iterated by object p.
70966 ** If successful, set *ppOut to point to a buffer containing the data
70967 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
70968 ** error code.
70969 **
70970 ** The buffer indicated by *ppOut may only be considered valid until the
70971 ** next call to this function.
70972 */
70973 static int vdbeSorterIterRead(
70974   sqlite3 *db,                    /* Database handle (for malloc) */
70975   VdbeSorterIter *p,              /* Iterator */
70976   int nByte,                      /* Bytes of data to read */
70977   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
70978 ){
70979   int iBuf;                       /* Offset within buffer to read from */
70980   int nAvail;                     /* Bytes of data available in buffer */
70981   assert( p->aBuffer );
70982
70983   /* If there is no more data to be read from the buffer, read the next 
70984   ** p->nBuffer bytes of data from the file into it. Or, if there are less
70985   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
70986   iBuf = p->iReadOff % p->nBuffer;
70987   if( iBuf==0 ){
70988     int nRead;                    /* Bytes to read from disk */
70989     int rc;                       /* sqlite3OsRead() return code */
70990
70991     /* Determine how many bytes of data to read. */
70992     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
70993       nRead = p->nBuffer;
70994     }else{
70995       nRead = (int)(p->iEof - p->iReadOff);
70996     }
70997     assert( nRead>0 );
70998
70999     /* Read data from the file. Return early if an error occurs. */
71000     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
71001     assert( rc!=SQLITE_IOERR_SHORT_READ );
71002     if( rc!=SQLITE_OK ) return rc;
71003   }
71004   nAvail = p->nBuffer - iBuf; 
71005
71006   if( nByte<=nAvail ){
71007     /* The requested data is available in the in-memory buffer. In this
71008     ** case there is no need to make a copy of the data, just return a 
71009     ** pointer into the buffer to the caller.  */
71010     *ppOut = &p->aBuffer[iBuf];
71011     p->iReadOff += nByte;
71012   }else{
71013     /* The requested data is not all available in the in-memory buffer.
71014     ** In this case, allocate space at p->aAlloc[] to copy the requested
71015     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
71016     int nRem;                     /* Bytes remaining to copy */
71017
71018     /* Extend the p->aAlloc[] allocation if required. */
71019     if( p->nAlloc<nByte ){
71020       int nNew = p->nAlloc*2;
71021       while( nByte>nNew ) nNew = nNew*2;
71022       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
71023       if( !p->aAlloc ) return SQLITE_NOMEM;
71024       p->nAlloc = nNew;
71025     }
71026
71027     /* Copy as much data as is available in the buffer into the start of
71028     ** p->aAlloc[].  */
71029     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
71030     p->iReadOff += nAvail;
71031     nRem = nByte - nAvail;
71032
71033     /* The following loop copies up to p->nBuffer bytes per iteration into
71034     ** the p->aAlloc[] buffer.  */
71035     while( nRem>0 ){
71036       int rc;                     /* vdbeSorterIterRead() return code */
71037       int nCopy;                  /* Number of bytes to copy */
71038       u8 *aNext;                  /* Pointer to buffer to copy data from */
71039
71040       nCopy = nRem;
71041       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
71042       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
71043       if( rc!=SQLITE_OK ) return rc;
71044       assert( aNext!=p->aAlloc );
71045       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
71046       nRem -= nCopy;
71047     }
71048
71049     *ppOut = p->aAlloc;
71050   }
71051
71052   return SQLITE_OK;
71053 }
71054
71055 /*
71056 ** Read a varint from the stream of data accessed by p. Set *pnOut to
71057 ** the value read.
71058 */
71059 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
71060   int iBuf;
71061
71062   iBuf = p->iReadOff % p->nBuffer;
71063   if( iBuf && (p->nBuffer-iBuf)>=9 ){
71064     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
71065   }else{
71066     u8 aVarint[16], *a;
71067     int i = 0, rc;
71068     do{
71069       rc = vdbeSorterIterRead(db, p, 1, &a);
71070       if( rc ) return rc;
71071       aVarint[(i++)&0xf] = a[0];
71072     }while( (a[0]&0x80)!=0 );
71073     sqlite3GetVarint(aVarint, pnOut);
71074   }
71075
71076   return SQLITE_OK;
71077 }
71078
71079
71080 /*
71081 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
71082 ** no error occurs, or an SQLite error code if one does.
71083 */
71084 static int vdbeSorterIterNext(
71085   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
71086   VdbeSorterIter *pIter           /* Iterator to advance */
71087 ){
71088   int rc;                         /* Return Code */
71089   u64 nRec = 0;                   /* Size of record in bytes */
71090
71091   if( pIter->iReadOff>=pIter->iEof ){
71092     /* This is an EOF condition */
71093     vdbeSorterIterZero(db, pIter);
71094     return SQLITE_OK;
71095   }
71096
71097   rc = vdbeSorterIterVarint(db, pIter, &nRec);
71098   if( rc==SQLITE_OK ){
71099     pIter->nKey = (int)nRec;
71100     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
71101   }
71102
71103   return rc;
71104 }
71105
71106 /*
71107 ** Initialize iterator pIter to scan through the PMA stored in file pFile
71108 ** starting at offset iStart and ending at offset iEof-1. This function 
71109 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
71110 ** PMA is empty).
71111 */
71112 static int vdbeSorterIterInit(
71113   sqlite3 *db,                    /* Database handle */
71114   const VdbeSorter *pSorter,      /* Sorter object */
71115   i64 iStart,                     /* Start offset in pFile */
71116   VdbeSorterIter *pIter,          /* Iterator to populate */
71117   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71118 ){
71119   int rc = SQLITE_OK;
71120   int nBuf;
71121
71122   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71123
71124   assert( pSorter->iWriteOff>iStart );
71125   assert( pIter->aAlloc==0 );
71126   assert( pIter->aBuffer==0 );
71127   pIter->pFile = pSorter->pTemp1;
71128   pIter->iReadOff = iStart;
71129   pIter->nAlloc = 128;
71130   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
71131   pIter->nBuffer = nBuf;
71132   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71133
71134   if( !pIter->aBuffer ){
71135     rc = SQLITE_NOMEM;
71136   }else{
71137     int iBuf;
71138
71139     iBuf = iStart % nBuf;
71140     if( iBuf ){
71141       int nRead = nBuf - iBuf;
71142       if( (iStart + nRead) > pSorter->iWriteOff ){
71143         nRead = (int)(pSorter->iWriteOff - iStart);
71144       }
71145       rc = sqlite3OsRead(
71146           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
71147       );
71148       assert( rc!=SQLITE_IOERR_SHORT_READ );
71149     }
71150
71151     if( rc==SQLITE_OK ){
71152       u64 nByte;                       /* Size of PMA in bytes */
71153       pIter->iEof = pSorter->iWriteOff;
71154       rc = vdbeSorterIterVarint(db, pIter, &nByte);
71155       pIter->iEof = pIter->iReadOff + nByte;
71156       *pnByte += nByte;
71157     }
71158   }
71159
71160   if( rc==SQLITE_OK ){
71161     rc = vdbeSorterIterNext(db, pIter);
71162   }
71163   return rc;
71164 }
71165
71166
71167 /*
71168 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
71169 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71170 ** used by the comparison. If an error occurs, return an SQLite error code.
71171 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
71172 ** value, depending on whether key1 is smaller, equal to or larger than key2.
71173 **
71174 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71175 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71176 ** is true and key1 contains even a single NULL value, it is considered to
71177 ** be less than key2. Even if key2 also contains NULL values.
71178 **
71179 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71180 ** has been allocated and contains an unpacked record that is used as key2.
71181 */
71182 static void vdbeSorterCompare(
71183   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
71184   int bOmitRowid,                 /* Ignore rowid field at end of keys */
71185   const void *pKey1, int nKey1,   /* Left side of comparison */
71186   const void *pKey2, int nKey2,   /* Right side of comparison */
71187   int *pRes                       /* OUT: Result of comparison */
71188 ){
71189   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71190   VdbeSorter *pSorter = pCsr->pSorter;
71191   UnpackedRecord *r2 = pSorter->pUnpacked;
71192   int i;
71193
71194   if( pKey2 ){
71195     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71196   }
71197
71198   if( bOmitRowid ){
71199     r2->nField = pKeyInfo->nField;
71200     assert( r2->nField>0 );
71201     for(i=0; i<r2->nField; i++){
71202       if( r2->aMem[i].flags & MEM_Null ){
71203         *pRes = -1;
71204         return;
71205       }
71206     }
71207     r2->flags |= UNPACKED_PREFIX_MATCH;
71208   }
71209
71210   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
71211 }
71212
71213 /*
71214 ** This function is called to compare two iterator keys when merging 
71215 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
71216 ** value to recalculate.
71217 */
71218 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
71219   VdbeSorter *pSorter = pCsr->pSorter;
71220   int i1;
71221   int i2;
71222   int iRes;
71223   VdbeSorterIter *p1;
71224   VdbeSorterIter *p2;
71225
71226   assert( iOut<pSorter->nTree && iOut>0 );
71227
71228   if( iOut>=(pSorter->nTree/2) ){
71229     i1 = (iOut - pSorter->nTree/2) * 2;
71230     i2 = i1 + 1;
71231   }else{
71232     i1 = pSorter->aTree[iOut*2];
71233     i2 = pSorter->aTree[iOut*2+1];
71234   }
71235
71236   p1 = &pSorter->aIter[i1];
71237   p2 = &pSorter->aIter[i2];
71238
71239   if( p1->pFile==0 ){
71240     iRes = i2;
71241   }else if( p2->pFile==0 ){
71242     iRes = i1;
71243   }else{
71244     int res;
71245     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
71246     vdbeSorterCompare(
71247         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
71248     );
71249     if( res<=0 ){
71250       iRes = i1;
71251     }else{
71252       iRes = i2;
71253     }
71254   }
71255
71256   pSorter->aTree[iOut] = iRes;
71257   return SQLITE_OK;
71258 }
71259
71260 /*
71261 ** Initialize the temporary index cursor just opened as a sorter cursor.
71262 */
71263 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
71264   int pgsz;                       /* Page size of main database */
71265   int mxCache;                    /* Cache size */
71266   VdbeSorter *pSorter;            /* The new sorter */
71267   char *d;                        /* Dummy */
71268
71269   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
71270   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
71271   if( pSorter==0 ){
71272     return SQLITE_NOMEM;
71273   }
71274   
71275   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
71276   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
71277   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
71278
71279   if( !sqlite3TempInMemory(db) ){
71280     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71281     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
71282     mxCache = db->aDb[0].pSchema->cache_size;
71283     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
71284     pSorter->mxPmaSize = mxCache * pgsz;
71285   }
71286
71287   return SQLITE_OK;
71288 }
71289
71290 /*
71291 ** Free the list of sorted records starting at pRecord.
71292 */
71293 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
71294   SorterRecord *p;
71295   SorterRecord *pNext;
71296   for(p=pRecord; p; p=pNext){
71297     pNext = p->pNext;
71298     sqlite3DbFree(db, p);
71299   }
71300 }
71301
71302 /*
71303 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
71304 */
71305 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
71306   VdbeSorter *pSorter = pCsr->pSorter;
71307   if( pSorter ){
71308     if( pSorter->aIter ){
71309       int i;
71310       for(i=0; i<pSorter->nTree; i++){
71311         vdbeSorterIterZero(db, &pSorter->aIter[i]);
71312       }
71313       sqlite3DbFree(db, pSorter->aIter);
71314     }
71315     if( pSorter->pTemp1 ){
71316       sqlite3OsCloseFree(pSorter->pTemp1);
71317     }
71318     vdbeSorterRecordFree(db, pSorter->pRecord);
71319     sqlite3DbFree(db, pSorter->pUnpacked);
71320     sqlite3DbFree(db, pSorter);
71321     pCsr->pSorter = 0;
71322   }
71323 }
71324
71325 /*
71326 ** Allocate space for a file-handle and open a temporary file. If successful,
71327 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
71328 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
71329 */
71330 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
71331   int dummy;
71332   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
71333       SQLITE_OPEN_TEMP_JOURNAL |
71334       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
71335       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
71336   );
71337 }
71338
71339 /*
71340 ** Merge the two sorted lists p1 and p2 into a single list.
71341 ** Set *ppOut to the head of the new list.
71342 */
71343 static void vdbeSorterMerge(
71344   const VdbeCursor *pCsr,         /* For pKeyInfo */
71345   SorterRecord *p1,               /* First list to merge */
71346   SorterRecord *p2,               /* Second list to merge */
71347   SorterRecord **ppOut            /* OUT: Head of merged list */
71348 ){
71349   SorterRecord *pFinal = 0;
71350   SorterRecord **pp = &pFinal;
71351   void *pVal2 = p2 ? p2->pVal : 0;
71352
71353   while( p1 && p2 ){
71354     int res;
71355     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
71356     if( res<=0 ){
71357       *pp = p1;
71358       pp = &p1->pNext;
71359       p1 = p1->pNext;
71360       pVal2 = 0;
71361     }else{
71362       *pp = p2;
71363        pp = &p2->pNext;
71364       p2 = p2->pNext;
71365       if( p2==0 ) break;
71366       pVal2 = p2->pVal;
71367     }
71368   }
71369   *pp = p1 ? p1 : p2;
71370   *ppOut = pFinal;
71371 }
71372
71373 /*
71374 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
71375 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
71376 ** occurs.
71377 */
71378 static int vdbeSorterSort(const VdbeCursor *pCsr){
71379   int i;
71380   SorterRecord **aSlot;
71381   SorterRecord *p;
71382   VdbeSorter *pSorter = pCsr->pSorter;
71383
71384   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
71385   if( !aSlot ){
71386     return SQLITE_NOMEM;
71387   }
71388
71389   p = pSorter->pRecord;
71390   while( p ){
71391     SorterRecord *pNext = p->pNext;
71392     p->pNext = 0;
71393     for(i=0; aSlot[i]; i++){
71394       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71395       aSlot[i] = 0;
71396     }
71397     aSlot[i] = p;
71398     p = pNext;
71399   }
71400
71401   p = 0;
71402   for(i=0; i<64; i++){
71403     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71404   }
71405   pSorter->pRecord = p;
71406
71407   sqlite3_free(aSlot);
71408   return SQLITE_OK;
71409 }
71410
71411 /*
71412 ** Initialize a file-writer object.
71413 */
71414 static void fileWriterInit(
71415   sqlite3 *db,                    /* Database (for malloc) */
71416   sqlite3_file *pFile,            /* File to write to */
71417   FileWriter *p,                  /* Object to populate */
71418   i64 iStart                      /* Offset of pFile to begin writing at */
71419 ){
71420   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71421
71422   memset(p, 0, sizeof(FileWriter));
71423   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71424   if( !p->aBuffer ){
71425     p->eFWErr = SQLITE_NOMEM;
71426   }else{
71427     p->iBufEnd = p->iBufStart = (iStart % nBuf);
71428     p->iWriteOff = iStart - p->iBufStart;
71429     p->nBuffer = nBuf;
71430     p->pFile = pFile;
71431   }
71432 }
71433
71434 /*
71435 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
71436 ** if successful, or an SQLite error code if an error occurs.
71437 */
71438 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
71439   int nRem = nData;
71440   while( nRem>0 && p->eFWErr==0 ){
71441     int nCopy = nRem;
71442     if( nCopy>(p->nBuffer - p->iBufEnd) ){
71443       nCopy = p->nBuffer - p->iBufEnd;
71444     }
71445
71446     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
71447     p->iBufEnd += nCopy;
71448     if( p->iBufEnd==p->nBuffer ){
71449       p->eFWErr = sqlite3OsWrite(p->pFile, 
71450           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
71451           p->iWriteOff + p->iBufStart
71452       );
71453       p->iBufStart = p->iBufEnd = 0;
71454       p->iWriteOff += p->nBuffer;
71455     }
71456     assert( p->iBufEnd<p->nBuffer );
71457
71458     nRem -= nCopy;
71459   }
71460 }
71461
71462 /*
71463 ** Flush any buffered data to disk and clean up the file-writer object.
71464 ** The results of using the file-writer after this call are undefined.
71465 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
71466 ** required. Otherwise, return an SQLite error code.
71467 **
71468 ** Before returning, set *piEof to the offset immediately following the
71469 ** last byte written to the file.
71470 */
71471 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
71472   int rc;
71473   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
71474     p->eFWErr = sqlite3OsWrite(p->pFile, 
71475         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
71476         p->iWriteOff + p->iBufStart
71477     );
71478   }
71479   *piEof = (p->iWriteOff + p->iBufEnd);
71480   sqlite3DbFree(db, p->aBuffer);
71481   rc = p->eFWErr;
71482   memset(p, 0, sizeof(FileWriter));
71483   return rc;
71484 }
71485
71486 /*
71487 ** Write value iVal encoded as a varint to the file-write object. Return 
71488 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
71489 */
71490 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
71491   int nByte; 
71492   u8 aByte[10];
71493   nByte = sqlite3PutVarint(aByte, iVal);
71494   fileWriterWrite(p, aByte, nByte);
71495 }
71496
71497 /*
71498 ** Write the current contents of the in-memory linked-list to a PMA. Return
71499 ** SQLITE_OK if successful, or an SQLite error code otherwise.
71500 **
71501 ** The format of a PMA is:
71502 **
71503 **     * A varint. This varint contains the total number of bytes of content
71504 **       in the PMA (not including the varint itself).
71505 **
71506 **     * One or more records packed end-to-end in order of ascending keys. 
71507 **       Each record consists of a varint followed by a blob of data (the 
71508 **       key). The varint is the number of bytes in the blob of data.
71509 */
71510 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
71511   int rc = SQLITE_OK;             /* Return code */
71512   VdbeSorter *pSorter = pCsr->pSorter;
71513   FileWriter writer;
71514
71515   memset(&writer, 0, sizeof(FileWriter));
71516
71517   if( pSorter->nInMemory==0 ){
71518     assert( pSorter->pRecord==0 );
71519     return rc;
71520   }
71521
71522   rc = vdbeSorterSort(pCsr);
71523
71524   /* If the first temporary PMA file has not been opened, open it now. */
71525   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
71526     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
71527     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
71528     assert( pSorter->iWriteOff==0 );
71529     assert( pSorter->nPMA==0 );
71530   }
71531
71532   if( rc==SQLITE_OK ){
71533     SorterRecord *p;
71534     SorterRecord *pNext = 0;
71535
71536     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
71537     pSorter->nPMA++;
71538     fileWriterWriteVarint(&writer, pSorter->nInMemory);
71539     for(p=pSorter->pRecord; p; p=pNext){
71540       pNext = p->pNext;
71541       fileWriterWriteVarint(&writer, p->nVal);
71542       fileWriterWrite(&writer, p->pVal, p->nVal);
71543       sqlite3DbFree(db, p);
71544     }
71545     pSorter->pRecord = p;
71546     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
71547   }
71548
71549   return rc;
71550 }
71551
71552 /*
71553 ** Add a record to the sorter.
71554 */
71555 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
71556   sqlite3 *db,                    /* Database handle */
71557   const VdbeCursor *pCsr,               /* Sorter cursor */
71558   Mem *pVal                       /* Memory cell containing record */
71559 ){
71560   VdbeSorter *pSorter = pCsr->pSorter;
71561   int rc = SQLITE_OK;             /* Return Code */
71562   SorterRecord *pNew;             /* New list element */
71563
71564   assert( pSorter );
71565   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
71566
71567   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
71568   if( pNew==0 ){
71569     rc = SQLITE_NOMEM;
71570   }else{
71571     pNew->pVal = (void *)&pNew[1];
71572     memcpy(pNew->pVal, pVal->z, pVal->n);
71573     pNew->nVal = pVal->n;
71574     pNew->pNext = pSorter->pRecord;
71575     pSorter->pRecord = pNew;
71576   }
71577
71578   /* See if the contents of the sorter should now be written out. They
71579   ** are written out when either of the following are true:
71580   **
71581   **   * The total memory allocated for the in-memory list is greater 
71582   **     than (page-size * cache-size), or
71583   **
71584   **   * The total memory allocated for the in-memory list is greater 
71585   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
71586   */
71587   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
71588         (pSorter->nInMemory>pSorter->mxPmaSize)
71589      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
71590   )){
71591 #ifdef SQLITE_DEBUG
71592     i64 nExpect = pSorter->iWriteOff
71593                 + sqlite3VarintLen(pSorter->nInMemory)
71594                 + pSorter->nInMemory;
71595 #endif
71596     rc = vdbeSorterListToPMA(db, pCsr);
71597     pSorter->nInMemory = 0;
71598     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
71599   }
71600
71601   return rc;
71602 }
71603
71604 /*
71605 ** Helper function for sqlite3VdbeSorterRewind(). 
71606 */
71607 static int vdbeSorterInitMerge(
71608   sqlite3 *db,                    /* Database handle */
71609   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
71610   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
71611 ){
71612   VdbeSorter *pSorter = pCsr->pSorter;
71613   int rc = SQLITE_OK;             /* Return code */
71614   int i;                          /* Used to iterator through aIter[] */
71615   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
71616
71617   /* Initialize the iterators. */
71618   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
71619     VdbeSorterIter *pIter = &pSorter->aIter[i];
71620     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
71621     pSorter->iReadOff = pIter->iEof;
71622     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
71623     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
71624   }
71625
71626   /* Initialize the aTree[] array. */
71627   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
71628     rc = vdbeSorterDoCompare(pCsr, i);
71629   }
71630
71631   *pnByte = nByte;
71632   return rc;
71633 }
71634
71635 /*
71636 ** Once the sorter has been populated, this function is called to prepare
71637 ** for iterating through its contents in sorted order.
71638 */
71639 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71640   VdbeSorter *pSorter = pCsr->pSorter;
71641   int rc;                         /* Return code */
71642   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
71643   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
71644   int nIter;                      /* Number of iterators used */
71645   int nByte;                      /* Bytes of space required for aIter/aTree */
71646   int N = 2;                      /* Power of 2 >= nIter */
71647
71648   assert( pSorter );
71649
71650   /* If no data has been written to disk, then do not do so now. Instead,
71651   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
71652   ** from the in-memory list.  */
71653   if( pSorter->nPMA==0 ){
71654     *pbEof = !pSorter->pRecord;
71655     assert( pSorter->aTree==0 );
71656     return vdbeSorterSort(pCsr);
71657   }
71658
71659   /* Write the current in-memory list to a PMA. */
71660   rc = vdbeSorterListToPMA(db, pCsr);
71661   if( rc!=SQLITE_OK ) return rc;
71662
71663   /* Allocate space for aIter[] and aTree[]. */
71664   nIter = pSorter->nPMA;
71665   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
71666   assert( nIter>0 );
71667   while( N<nIter ) N += N;
71668   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
71669   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
71670   if( !pSorter->aIter ) return SQLITE_NOMEM;
71671   pSorter->aTree = (int *)&pSorter->aIter[N];
71672   pSorter->nTree = N;
71673
71674   do {
71675     int iNew;                     /* Index of new, merged, PMA */
71676
71677     for(iNew=0; 
71678         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
71679         iNew++
71680     ){
71681       int rc2;                    /* Return code from fileWriterFinish() */
71682       FileWriter writer;          /* Object used to write to disk */
71683       i64 nWrite;                 /* Number of bytes in new PMA */
71684
71685       memset(&writer, 0, sizeof(FileWriter));
71686
71687       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
71688       ** initialize an iterator for each of them and break out of the loop.
71689       ** These iterators will be incrementally merged as the VDBE layer calls
71690       ** sqlite3VdbeSorterNext().
71691       **
71692       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
71693       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
71694       ** are merged into a single PMA that is written to file pTemp2.
71695       */
71696       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
71697       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
71698       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71699         break;
71700       }
71701
71702       /* Open the second temp file, if it is not already open. */
71703       if( pTemp2==0 ){
71704         assert( iWrite2==0 );
71705         rc = vdbeSorterOpenTempFile(db, &pTemp2);
71706       }
71707
71708       if( rc==SQLITE_OK ){
71709         int bEof = 0;
71710         fileWriterInit(db, pTemp2, &writer, iWrite2);
71711         fileWriterWriteVarint(&writer, nWrite);
71712         while( rc==SQLITE_OK && bEof==0 ){
71713           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71714           assert( pIter->pFile );
71715
71716           fileWriterWriteVarint(&writer, pIter->nKey);
71717           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
71718           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
71719         }
71720         rc2 = fileWriterFinish(db, &writer, &iWrite2);
71721         if( rc==SQLITE_OK ) rc = rc2;
71722       }
71723     }
71724
71725     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71726       break;
71727     }else{
71728       sqlite3_file *pTmp = pSorter->pTemp1;
71729       pSorter->nPMA = iNew;
71730       pSorter->pTemp1 = pTemp2;
71731       pTemp2 = pTmp;
71732       pSorter->iWriteOff = iWrite2;
71733       pSorter->iReadOff = 0;
71734       iWrite2 = 0;
71735     }
71736   }while( rc==SQLITE_OK );
71737
71738   if( pTemp2 ){
71739     sqlite3OsCloseFree(pTemp2);
71740   }
71741   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71742   return rc;
71743 }
71744
71745 /*
71746 ** Advance to the next element in the sorter.
71747 */
71748 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71749   VdbeSorter *pSorter = pCsr->pSorter;
71750   int rc;                         /* Return code */
71751
71752   if( pSorter->aTree ){
71753     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
71754     int i;                        /* Index of aTree[] to recalculate */
71755
71756     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
71757     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
71758       rc = vdbeSorterDoCompare(pCsr, i);
71759     }
71760
71761     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71762   }else{
71763     SorterRecord *pFree = pSorter->pRecord;
71764     pSorter->pRecord = pFree->pNext;
71765     pFree->pNext = 0;
71766     vdbeSorterRecordFree(db, pFree);
71767     *pbEof = !pSorter->pRecord;
71768     rc = SQLITE_OK;
71769   }
71770   return rc;
71771 }
71772
71773 /*
71774 ** Return a pointer to a buffer owned by the sorter that contains the 
71775 ** current key.
71776 */
71777 static void *vdbeSorterRowkey(
71778   const VdbeSorter *pSorter,      /* Sorter object */
71779   int *pnKey                      /* OUT: Size of current key in bytes */
71780 ){
71781   void *pKey;
71782   if( pSorter->aTree ){
71783     VdbeSorterIter *pIter;
71784     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71785     *pnKey = pIter->nKey;
71786     pKey = pIter->aKey;
71787   }else{
71788     *pnKey = pSorter->pRecord->nVal;
71789     pKey = pSorter->pRecord->pVal;
71790   }
71791   return pKey;
71792 }
71793
71794 /*
71795 ** Copy the current sorter key into the memory cell pOut.
71796 */
71797 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
71798   VdbeSorter *pSorter = pCsr->pSorter;
71799   void *pKey; int nKey;           /* Sorter key to copy into pOut */
71800
71801   pKey = vdbeSorterRowkey(pSorter, &nKey);
71802   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71803     return SQLITE_NOMEM;
71804   }
71805   pOut->n = nKey;
71806   MemSetTypeFlag(pOut, MEM_Blob);
71807   memcpy(pOut->z, pKey, nKey);
71808
71809   return SQLITE_OK;
71810 }
71811
71812 /*
71813 ** Compare the key in memory cell pVal with the key that the sorter cursor
71814 ** passed as the first argument currently points to. For the purposes of
71815 ** the comparison, ignore the rowid field at the end of each record.
71816 **
71817 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71818 ** Otherwise, set *pRes to a negative, zero or positive value if the
71819 ** key in pVal is smaller than, equal to or larger than the current sorter
71820 ** key.
71821 */
71822 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71823   const VdbeCursor *pCsr,         /* Sorter cursor */
71824   Mem *pVal,                      /* Value to compare to current sorter key */
71825   int *pRes                       /* OUT: Result of comparison */
71826 ){
71827   VdbeSorter *pSorter = pCsr->pSorter;
71828   void *pKey; int nKey;           /* Sorter key to compare pVal with */
71829
71830   pKey = vdbeSorterRowkey(pSorter, &nKey);
71831   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71832   return SQLITE_OK;
71833 }
71834
71835 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
71836
71837 /************** End of vdbesort.c ********************************************/
71838 /************** Begin file journal.c *****************************************/
71839 /*
71840 ** 2007 August 22
71841 **
71842 ** The author disclaims copyright to this source code.  In place of
71843 ** a legal notice, here is a blessing:
71844 **
71845 **    May you do good and not evil.
71846 **    May you find forgiveness for yourself and forgive others.
71847 **    May you share freely, never taking more than you give.
71848 **
71849 *************************************************************************
71850 **
71851 ** This file implements a special kind of sqlite3_file object used
71852 ** by SQLite to create journal files if the atomic-write optimization
71853 ** is enabled.
71854 **
71855 ** The distinctive characteristic of this sqlite3_file is that the
71856 ** actual on disk file is created lazily. When the file is created,
71857 ** the caller specifies a buffer size for an in-memory buffer to
71858 ** be used to service read() and write() requests. The actual file
71859 ** on disk is not created or populated until either:
71860 **
71861 **   1) The in-memory representation grows too large for the allocated 
71862 **      buffer, or
71863 **   2) The sqlite3JournalCreate() function is called.
71864 */
71865 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
71866
71867
71868 /*
71869 ** A JournalFile object is a subclass of sqlite3_file used by
71870 ** as an open file handle for journal files.
71871 */
71872 struct JournalFile {
71873   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
71874   int nBuf;                       /* Size of zBuf[] in bytes */
71875   char *zBuf;                     /* Space to buffer journal writes */
71876   int iSize;                      /* Amount of zBuf[] currently used */
71877   int flags;                      /* xOpen flags */
71878   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
71879   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
71880   const char *zJournal;           /* Name of the journal file */
71881 };
71882 typedef struct JournalFile JournalFile;
71883
71884 /*
71885 ** If it does not already exists, create and populate the on-disk file 
71886 ** for JournalFile p.
71887 */
71888 static int createFile(JournalFile *p){
71889   int rc = SQLITE_OK;
71890   if( !p->pReal ){
71891     sqlite3_file *pReal = (sqlite3_file *)&p[1];
71892     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
71893     if( rc==SQLITE_OK ){
71894       p->pReal = pReal;
71895       if( p->iSize>0 ){
71896         assert(p->iSize<=p->nBuf);
71897         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
71898       }
71899     }
71900   }
71901   return rc;
71902 }
71903
71904 /*
71905 ** Close the file.
71906 */
71907 static int jrnlClose(sqlite3_file *pJfd){
71908   JournalFile *p = (JournalFile *)pJfd;
71909   if( p->pReal ){
71910     sqlite3OsClose(p->pReal);
71911   }
71912   sqlite3_free(p->zBuf);
71913   return SQLITE_OK;
71914 }
71915
71916 /*
71917 ** Read data from the file.
71918 */
71919 static int jrnlRead(
71920   sqlite3_file *pJfd,    /* The journal file from which to read */
71921   void *zBuf,            /* Put the results here */
71922   int iAmt,              /* Number of bytes to read */
71923   sqlite_int64 iOfst     /* Begin reading at this offset */
71924 ){
71925   int rc = SQLITE_OK;
71926   JournalFile *p = (JournalFile *)pJfd;
71927   if( p->pReal ){
71928     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
71929   }else if( (iAmt+iOfst)>p->iSize ){
71930     rc = SQLITE_IOERR_SHORT_READ;
71931   }else{
71932     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
71933   }
71934   return rc;
71935 }
71936
71937 /*
71938 ** Write data to the file.
71939 */
71940 static int jrnlWrite(
71941   sqlite3_file *pJfd,    /* The journal file into which to write */
71942   const void *zBuf,      /* Take data to be written from here */
71943   int iAmt,              /* Number of bytes to write */
71944   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
71945 ){
71946   int rc = SQLITE_OK;
71947   JournalFile *p = (JournalFile *)pJfd;
71948   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
71949     rc = createFile(p);
71950   }
71951   if( rc==SQLITE_OK ){
71952     if( p->pReal ){
71953       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
71954     }else{
71955       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
71956       if( p->iSize<(iOfst+iAmt) ){
71957         p->iSize = (iOfst+iAmt);
71958       }
71959     }
71960   }
71961   return rc;
71962 }
71963
71964 /*
71965 ** Truncate the file.
71966 */
71967 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71968   int rc = SQLITE_OK;
71969   JournalFile *p = (JournalFile *)pJfd;
71970   if( p->pReal ){
71971     rc = sqlite3OsTruncate(p->pReal, size);
71972   }else if( size<p->iSize ){
71973     p->iSize = size;
71974   }
71975   return rc;
71976 }
71977
71978 /*
71979 ** Sync the file.
71980 */
71981 static int jrnlSync(sqlite3_file *pJfd, int flags){
71982   int rc;
71983   JournalFile *p = (JournalFile *)pJfd;
71984   if( p->pReal ){
71985     rc = sqlite3OsSync(p->pReal, flags);
71986   }else{
71987     rc = SQLITE_OK;
71988   }
71989   return rc;
71990 }
71991
71992 /*
71993 ** Query the size of the file in bytes.
71994 */
71995 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71996   int rc = SQLITE_OK;
71997   JournalFile *p = (JournalFile *)pJfd;
71998   if( p->pReal ){
71999     rc = sqlite3OsFileSize(p->pReal, pSize);
72000   }else{
72001     *pSize = (sqlite_int64) p->iSize;
72002   }
72003   return rc;
72004 }
72005
72006 /*
72007 ** Table of methods for JournalFile sqlite3_file object.
72008 */
72009 static struct sqlite3_io_methods JournalFileMethods = {
72010   1,             /* iVersion */
72011   jrnlClose,     /* xClose */
72012   jrnlRead,      /* xRead */
72013   jrnlWrite,     /* xWrite */
72014   jrnlTruncate,  /* xTruncate */
72015   jrnlSync,      /* xSync */
72016   jrnlFileSize,  /* xFileSize */
72017   0,             /* xLock */
72018   0,             /* xUnlock */
72019   0,             /* xCheckReservedLock */
72020   0,             /* xFileControl */
72021   0,             /* xSectorSize */
72022   0,             /* xDeviceCharacteristics */
72023   0,             /* xShmMap */
72024   0,             /* xShmLock */
72025   0,             /* xShmBarrier */
72026   0              /* xShmUnmap */
72027 };
72028
72029 /* 
72030 ** Open a journal file.
72031 */
72032 SQLITE_PRIVATE int sqlite3JournalOpen(
72033   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72034   const char *zName,         /* Name of the journal file */
72035   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
72036   int flags,                 /* Opening flags */
72037   int nBuf                   /* Bytes buffered before opening the file */
72038 ){
72039   JournalFile *p = (JournalFile *)pJfd;
72040   memset(p, 0, sqlite3JournalSize(pVfs));
72041   if( nBuf>0 ){
72042     p->zBuf = sqlite3MallocZero(nBuf);
72043     if( !p->zBuf ){
72044       return SQLITE_NOMEM;
72045     }
72046   }else{
72047     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
72048   }
72049   p->pMethod = &JournalFileMethods;
72050   p->nBuf = nBuf;
72051   p->flags = flags;
72052   p->zJournal = zName;
72053   p->pVfs = pVfs;
72054   return SQLITE_OK;
72055 }
72056
72057 /*
72058 ** If the argument p points to a JournalFile structure, and the underlying
72059 ** file has not yet been created, create it now.
72060 */
72061 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
72062   if( p->pMethods!=&JournalFileMethods ){
72063     return SQLITE_OK;
72064   }
72065   return createFile((JournalFile *)p);
72066 }
72067
72068 /*
72069 ** The file-handle passed as the only argument is guaranteed to be an open
72070 ** file. It may or may not be of class JournalFile. If the file is a
72071 ** JournalFile, and the underlying file on disk has not yet been opened,
72072 ** return 0. Otherwise, return 1.
72073 */
72074 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
72075   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
72076 }
72077
72078 /* 
72079 ** Return the number of bytes required to store a JournalFile that uses vfs
72080 ** pVfs to create the underlying on-disk files.
72081 */
72082 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
72083   return (pVfs->szOsFile+sizeof(JournalFile));
72084 }
72085 #endif
72086
72087 /************** End of journal.c *********************************************/
72088 /************** Begin file memjournal.c **************************************/
72089 /*
72090 ** 2008 October 7
72091 **
72092 ** The author disclaims copyright to this source code.  In place of
72093 ** a legal notice, here is a blessing:
72094 **
72095 **    May you do good and not evil.
72096 **    May you find forgiveness for yourself and forgive others.
72097 **    May you share freely, never taking more than you give.
72098 **
72099 *************************************************************************
72100 **
72101 ** This file contains code use to implement an in-memory rollback journal.
72102 ** The in-memory rollback journal is used to journal transactions for
72103 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72104 */
72105
72106 /* Forward references to internal structures */
72107 typedef struct MemJournal MemJournal;
72108 typedef struct FilePoint FilePoint;
72109 typedef struct FileChunk FileChunk;
72110
72111 /* Space to hold the rollback journal is allocated in increments of
72112 ** this many bytes.
72113 **
72114 ** The size chosen is a little less than a power of two.  That way,
72115 ** the FileChunk object will have a size that almost exactly fills
72116 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72117 ** memory allocators.
72118 */
72119 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72120
72121 /* Macro to find the minimum of two numeric values.
72122 */
72123 #ifndef MIN
72124 # define MIN(x,y) ((x)<(y)?(x):(y))
72125 #endif
72126
72127 /*
72128 ** The rollback journal is composed of a linked list of these structures.
72129 */
72130 struct FileChunk {
72131   FileChunk *pNext;               /* Next chunk in the journal */
72132   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72133 };
72134
72135 /*
72136 ** An instance of this object serves as a cursor into the rollback journal.
72137 ** The cursor can be either for reading or writing.
72138 */
72139 struct FilePoint {
72140   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
72141   FileChunk *pChunk;              /* Specific chunk into which cursor points */
72142 };
72143
72144 /*
72145 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
72146 ** is an instance of this class.
72147 */
72148 struct MemJournal {
72149   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72150   FileChunk *pFirst;              /* Head of in-memory chunk-list */
72151   FilePoint endpoint;             /* Pointer to the end of the file */
72152   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72153 };
72154
72155 /*
72156 ** Read data from the in-memory journal file.  This is the implementation
72157 ** of the sqlite3_vfs.xRead method.
72158 */
72159 static int memjrnlRead(
72160   sqlite3_file *pJfd,    /* The journal file from which to read */
72161   void *zBuf,            /* Put the results here */
72162   int iAmt,              /* Number of bytes to read */
72163   sqlite_int64 iOfst     /* Begin reading at this offset */
72164 ){
72165   MemJournal *p = (MemJournal *)pJfd;
72166   u8 *zOut = zBuf;
72167   int nRead = iAmt;
72168   int iChunkOffset;
72169   FileChunk *pChunk;
72170
72171   /* SQLite never tries to read past the end of a rollback journal file */
72172   assert( iOfst+iAmt<=p->endpoint.iOffset );
72173
72174   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72175     sqlite3_int64 iOff = 0;
72176     for(pChunk=p->pFirst; 
72177         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72178         pChunk=pChunk->pNext
72179     ){
72180       iOff += JOURNAL_CHUNKSIZE;
72181     }
72182   }else{
72183     pChunk = p->readpoint.pChunk;
72184   }
72185
72186   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72187   do {
72188     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72189     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72190     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72191     zOut += nCopy;
72192     nRead -= iSpace;
72193     iChunkOffset = 0;
72194   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72195   p->readpoint.iOffset = iOfst+iAmt;
72196   p->readpoint.pChunk = pChunk;
72197
72198   return SQLITE_OK;
72199 }
72200
72201 /*
72202 ** Write data to the file.
72203 */
72204 static int memjrnlWrite(
72205   sqlite3_file *pJfd,    /* The journal file into which to write */
72206   const void *zBuf,      /* Take data to be written from here */
72207   int iAmt,              /* Number of bytes to write */
72208   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72209 ){
72210   MemJournal *p = (MemJournal *)pJfd;
72211   int nWrite = iAmt;
72212   u8 *zWrite = (u8 *)zBuf;
72213
72214   /* An in-memory journal file should only ever be appended to. Random
72215   ** access writes are not required by sqlite.
72216   */
72217   assert( iOfst==p->endpoint.iOffset );
72218   UNUSED_PARAMETER(iOfst);
72219
72220   while( nWrite>0 ){
72221     FileChunk *pChunk = p->endpoint.pChunk;
72222     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72223     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72224
72225     if( iChunkOffset==0 ){
72226       /* New chunk is required to extend the file. */
72227       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
72228       if( !pNew ){
72229         return SQLITE_IOERR_NOMEM;
72230       }
72231       pNew->pNext = 0;
72232       if( pChunk ){
72233         assert( p->pFirst );
72234         pChunk->pNext = pNew;
72235       }else{
72236         assert( !p->pFirst );
72237         p->pFirst = pNew;
72238       }
72239       p->endpoint.pChunk = pNew;
72240     }
72241
72242     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72243     zWrite += iSpace;
72244     nWrite -= iSpace;
72245     p->endpoint.iOffset += iSpace;
72246   }
72247
72248   return SQLITE_OK;
72249 }
72250
72251 /*
72252 ** Truncate the file.
72253 */
72254 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72255   MemJournal *p = (MemJournal *)pJfd;
72256   FileChunk *pChunk;
72257   assert(size==0);
72258   UNUSED_PARAMETER(size);
72259   pChunk = p->pFirst;
72260   while( pChunk ){
72261     FileChunk *pTmp = pChunk;
72262     pChunk = pChunk->pNext;
72263     sqlite3_free(pTmp);
72264   }
72265   sqlite3MemJournalOpen(pJfd);
72266   return SQLITE_OK;
72267 }
72268
72269 /*
72270 ** Close the file.
72271 */
72272 static int memjrnlClose(sqlite3_file *pJfd){
72273   memjrnlTruncate(pJfd, 0);
72274   return SQLITE_OK;
72275 }
72276
72277
72278 /*
72279 ** Sync the file.
72280 **
72281 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72282 ** is never called in a working implementation.  This implementation
72283 ** exists purely as a contingency, in case some malfunction in some other
72284 ** part of SQLite causes Sync to be called by mistake.
72285 */
72286 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
72287   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72288   return SQLITE_OK;
72289 }
72290
72291 /*
72292 ** Query the size of the file in bytes.
72293 */
72294 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72295   MemJournal *p = (MemJournal *)pJfd;
72296   *pSize = (sqlite_int64) p->endpoint.iOffset;
72297   return SQLITE_OK;
72298 }
72299
72300 /*
72301 ** Table of methods for MemJournal sqlite3_file object.
72302 */
72303 static const struct sqlite3_io_methods MemJournalMethods = {
72304   1,                /* iVersion */
72305   memjrnlClose,     /* xClose */
72306   memjrnlRead,      /* xRead */
72307   memjrnlWrite,     /* xWrite */
72308   memjrnlTruncate,  /* xTruncate */
72309   memjrnlSync,      /* xSync */
72310   memjrnlFileSize,  /* xFileSize */
72311   0,                /* xLock */
72312   0,                /* xUnlock */
72313   0,                /* xCheckReservedLock */
72314   0,                /* xFileControl */
72315   0,                /* xSectorSize */
72316   0,                /* xDeviceCharacteristics */
72317   0,                /* xShmMap */
72318   0,                /* xShmLock */
72319   0,                /* xShmBarrier */
72320   0                 /* xShmUnlock */
72321 };
72322
72323 /* 
72324 ** Open a journal file.
72325 */
72326 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
72327   MemJournal *p = (MemJournal *)pJfd;
72328   assert( EIGHT_BYTE_ALIGNMENT(p) );
72329   memset(p, 0, sqlite3MemJournalSize());
72330   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
72331 }
72332
72333 /*
72334 ** Return true if the file-handle passed as an argument is 
72335 ** an in-memory journal 
72336 */
72337 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
72338   return pJfd->pMethods==&MemJournalMethods;
72339 }
72340
72341 /* 
72342 ** Return the number of bytes required to store a MemJournal file descriptor.
72343 */
72344 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
72345   return sizeof(MemJournal);
72346 }
72347
72348 /************** End of memjournal.c ******************************************/
72349 /************** Begin file walker.c ******************************************/
72350 /*
72351 ** 2008 August 16
72352 **
72353 ** The author disclaims copyright to this source code.  In place of
72354 ** a legal notice, here is a blessing:
72355 **
72356 **    May you do good and not evil.
72357 **    May you find forgiveness for yourself and forgive others.
72358 **    May you share freely, never taking more than you give.
72359 **
72360 *************************************************************************
72361 ** This file contains routines used for walking the parser tree for
72362 ** an SQL statement.
72363 */
72364 /* #include <stdlib.h> */
72365 /* #include <string.h> */
72366
72367
72368 /*
72369 ** Walk an expression tree.  Invoke the callback once for each node
72370 ** of the expression, while decending.  (In other words, the callback
72371 ** is invoked before visiting children.)
72372 **
72373 ** The return value from the callback should be one of the WRC_*
72374 ** constants to specify how to proceed with the walk.
72375 **
72376 **    WRC_Continue      Continue descending down the tree.
72377 **
72378 **    WRC_Prune         Do not descend into child nodes.  But allow
72379 **                      the walk to continue with sibling nodes.
72380 **
72381 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
72382 **                      return the top-level walk call.
72383 **
72384 ** The return value from this routine is WRC_Abort to abandon the tree walk
72385 ** and WRC_Continue to continue.
72386 */
72387 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
72388   int rc;
72389   if( pExpr==0 ) return WRC_Continue;
72390   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
72391   testcase( ExprHasProperty(pExpr, EP_Reduced) );
72392   rc = pWalker->xExprCallback(pWalker, pExpr);
72393   if( rc==WRC_Continue
72394               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
72395     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
72396     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
72397     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72398       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
72399     }else{
72400       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
72401     }
72402   }
72403   return rc & WRC_Abort;
72404 }
72405
72406 /*
72407 ** Call sqlite3WalkExpr() for every expression in list p or until
72408 ** an abort request is seen.
72409 */
72410 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
72411   int i;
72412   struct ExprList_item *pItem;
72413   if( p ){
72414     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
72415       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
72416     }
72417   }
72418   return WRC_Continue;
72419 }
72420
72421 /*
72422 ** Walk all expressions associated with SELECT statement p.  Do
72423 ** not invoke the SELECT callback on p, but do (of course) invoke
72424 ** any expr callbacks and SELECT callbacks that come from subqueries.
72425 ** Return WRC_Abort or WRC_Continue.
72426 */
72427 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
72428   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
72429   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
72430   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
72431   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
72432   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
72433   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
72434   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
72435   return WRC_Continue;
72436 }
72437
72438 /*
72439 ** Walk the parse trees associated with all subqueries in the
72440 ** FROM clause of SELECT statement p.  Do not invoke the select
72441 ** callback on p, but do invoke it on each FROM clause subquery
72442 ** and on any subqueries further down in the tree.  Return 
72443 ** WRC_Abort or WRC_Continue;
72444 */
72445 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
72446   SrcList *pSrc;
72447   int i;
72448   struct SrcList_item *pItem;
72449
72450   pSrc = p->pSrc;
72451   if( ALWAYS(pSrc) ){
72452     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
72453       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
72454         return WRC_Abort;
72455       }
72456     }
72457   }
72458   return WRC_Continue;
72459
72460
72461 /*
72462 ** Call sqlite3WalkExpr() for every expression in Select statement p.
72463 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
72464 ** on the compound select chain, p->pPrior.
72465 **
72466 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
72467 ** there is an abort request.
72468 **
72469 ** If the Walker does not have an xSelectCallback() then this routine
72470 ** is a no-op returning WRC_Continue.
72471 */
72472 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
72473   int rc;
72474   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
72475   rc = WRC_Continue;
72476   pWalker->walkerDepth++;
72477   while( p ){
72478     rc = pWalker->xSelectCallback(pWalker, p);
72479     if( rc ) break;
72480     if( sqlite3WalkSelectExpr(pWalker, p)
72481      || sqlite3WalkSelectFrom(pWalker, p)
72482     ){
72483       pWalker->walkerDepth--;
72484       return WRC_Abort;
72485     }
72486     p = p->pPrior;
72487   }
72488   pWalker->walkerDepth--;
72489   return rc & WRC_Abort;
72490 }
72491
72492 /************** End of walker.c **********************************************/
72493 /************** Begin file resolve.c *****************************************/
72494 /*
72495 ** 2008 August 18
72496 **
72497 ** The author disclaims copyright to this source code.  In place of
72498 ** a legal notice, here is a blessing:
72499 **
72500 **    May you do good and not evil.
72501 **    May you find forgiveness for yourself and forgive others.
72502 **    May you share freely, never taking more than you give.
72503 **
72504 *************************************************************************
72505 **
72506 ** This file contains routines used for walking the parser tree and
72507 ** resolve all identifiers by associating them with a particular
72508 ** table and column.
72509 */
72510 /* #include <stdlib.h> */
72511 /* #include <string.h> */
72512
72513 /*
72514 ** Walk the expression tree pExpr and increase the aggregate function
72515 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
72516 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
72517 ** outer query into an inner subquery.
72518 **
72519 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
72520 ** is a helper function - a callback for the tree walker.
72521 */
72522 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
72523   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
72524   return WRC_Continue;
72525 }
72526 static void incrAggFunctionDepth(Expr *pExpr, int N){
72527   if( N>0 ){
72528     Walker w;
72529     memset(&w, 0, sizeof(w));
72530     w.xExprCallback = incrAggDepth;
72531     w.u.i = N;
72532     sqlite3WalkExpr(&w, pExpr);
72533   }
72534 }
72535
72536 /*
72537 ** Turn the pExpr expression into an alias for the iCol-th column of the
72538 ** result set in pEList.
72539 **
72540 ** If the result set column is a simple column reference, then this routine
72541 ** makes an exact copy.  But for any other kind of expression, this
72542 ** routine make a copy of the result set column as the argument to the
72543 ** TK_AS operator.  The TK_AS operator causes the expression to be
72544 ** evaluated just once and then reused for each alias.
72545 **
72546 ** The reason for suppressing the TK_AS term when the expression is a simple
72547 ** column reference is so that the column reference will be recognized as
72548 ** usable by indices within the WHERE clause processing logic. 
72549 **
72550 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
72551 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
72552 **
72553 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
72554 **
72555 ** Is equivalent to:
72556 **
72557 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
72558 **
72559 ** The result of random()%5 in the GROUP BY clause is probably different
72560 ** from the result in the result-set.  We might fix this someday.  Or
72561 ** then again, we might not...
72562 **
72563 ** If the reference is followed by a COLLATE operator, then make sure
72564 ** the COLLATE operator is preserved.  For example:
72565 **
72566 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
72567 **
72568 ** Should be transformed into:
72569 **
72570 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
72571 **
72572 ** The nSubquery parameter specifies how many levels of subquery the
72573 ** alias is removed from the original expression.  The usually value is
72574 ** zero but it might be more if the alias is contained within a subquery
72575 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
72576 ** structures must be increased by the nSubquery amount.
72577 */
72578 static void resolveAlias(
72579   Parse *pParse,         /* Parsing context */
72580   ExprList *pEList,      /* A result set */
72581   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
72582   Expr *pExpr,           /* Transform this into an alias to the result set */
72583   const char *zType,     /* "GROUP" or "ORDER" or "" */
72584   int nSubquery          /* Number of subqueries that the label is moving */
72585 ){
72586   Expr *pOrig;           /* The iCol-th column of the result set */
72587   Expr *pDup;            /* Copy of pOrig */
72588   sqlite3 *db;           /* The database connection */
72589
72590   assert( iCol>=0 && iCol<pEList->nExpr );
72591   pOrig = pEList->a[iCol].pExpr;
72592   assert( pOrig!=0 );
72593   assert( pOrig->flags & EP_Resolved );
72594   db = pParse->db;
72595   pDup = sqlite3ExprDup(db, pOrig, 0);
72596   if( pDup==0 ) return;
72597   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
72598     incrAggFunctionDepth(pDup, nSubquery);
72599     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
72600     if( pDup==0 ) return;
72601     if( pEList->a[iCol].iAlias==0 ){
72602       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
72603     }
72604     pDup->iTable = pEList->a[iCol].iAlias;
72605   }
72606   if( pExpr->op==TK_COLLATE ){
72607     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
72608   }
72609
72610   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
72611   ** prevents ExprDelete() from deleting the Expr structure itself,
72612   ** allowing it to be repopulated by the memcpy() on the following line.
72613   ** The pExpr->u.zToken might point into memory that will be freed by the
72614   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
72615   ** make a copy of the token before doing the sqlite3DbFree().
72616   */
72617   ExprSetProperty(pExpr, EP_Static);
72618   sqlite3ExprDelete(db, pExpr);
72619   memcpy(pExpr, pDup, sizeof(*pExpr));
72620   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
72621     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
72622     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
72623     pExpr->flags2 |= EP2_MallocedToken;
72624   }
72625   sqlite3DbFree(db, pDup);
72626 }
72627
72628
72629 /*
72630 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
72631 **
72632 ** Return FALSE if the USING clause is NULL or if it does not contain
72633 ** zCol.
72634 */
72635 static int nameInUsingClause(IdList *pUsing, const char *zCol){
72636   if( pUsing ){
72637     int k;
72638     for(k=0; k<pUsing->nId; k++){
72639       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
72640     }
72641   }
72642   return 0;
72643 }
72644
72645
72646 /*
72647 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
72648 ** that name in the set of source tables in pSrcList and make the pExpr 
72649 ** expression node refer back to that source column.  The following changes
72650 ** are made to pExpr:
72651 **
72652 **    pExpr->iDb           Set the index in db->aDb[] of the database X
72653 **                         (even if X is implied).
72654 **    pExpr->iTable        Set to the cursor number for the table obtained
72655 **                         from pSrcList.
72656 **    pExpr->pTab          Points to the Table structure of X.Y (even if
72657 **                         X and/or Y are implied.)
72658 **    pExpr->iColumn       Set to the column number within the table.
72659 **    pExpr->op            Set to TK_COLUMN.
72660 **    pExpr->pLeft         Any expression this points to is deleted
72661 **    pExpr->pRight        Any expression this points to is deleted.
72662 **
72663 ** The zDb variable is the name of the database (the "X").  This value may be
72664 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
72665 ** can be used.  The zTable variable is the name of the table (the "Y").  This
72666 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
72667 ** means that the form of the name is Z and that columns from any table
72668 ** can be used.
72669 **
72670 ** If the name cannot be resolved unambiguously, leave an error message
72671 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
72672 */
72673 static int lookupName(
72674   Parse *pParse,       /* The parsing context */
72675   const char *zDb,     /* Name of the database containing table, or NULL */
72676   const char *zTab,    /* Name of table containing column, or NULL */
72677   const char *zCol,    /* Name of the column. */
72678   NameContext *pNC,    /* The name context used to resolve the name */
72679   Expr *pExpr          /* Make this EXPR node point to the selected column */
72680 ){
72681   int i, j;                         /* Loop counters */
72682   int cnt = 0;                      /* Number of matching column names */
72683   int cntTab = 0;                   /* Number of matching table names */
72684   int nSubquery = 0;                /* How many levels of subquery */
72685   sqlite3 *db = pParse->db;         /* The database connection */
72686   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
72687   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
72688   NameContext *pTopNC = pNC;        /* First namecontext in the list */
72689   Schema *pSchema = 0;              /* Schema of the expression */
72690   int isTrigger = 0;
72691
72692   assert( pNC );     /* the name context cannot be NULL. */
72693   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
72694   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72695
72696   /* Initialize the node to no-match */
72697   pExpr->iTable = -1;
72698   pExpr->pTab = 0;
72699   ExprSetIrreducible(pExpr);
72700
72701   /* Start at the inner-most context and move outward until a match is found */
72702   while( pNC && cnt==0 ){
72703     ExprList *pEList;
72704     SrcList *pSrcList = pNC->pSrcList;
72705
72706     if( pSrcList ){
72707       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
72708         Table *pTab;
72709         int iDb;
72710         Column *pCol;
72711   
72712         pTab = pItem->pTab;
72713         assert( pTab!=0 && pTab->zName!=0 );
72714         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72715         assert( pTab->nCol>0 );
72716         if( zTab ){
72717           if( pItem->zAlias ){
72718             char *zTabName = pItem->zAlias;
72719             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
72720           }else{
72721             char *zTabName = pTab->zName;
72722             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
72723               continue;
72724             }
72725             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
72726               continue;
72727             }
72728           }
72729         }
72730         if( 0==(cntTab++) ){
72731           pExpr->iTable = pItem->iCursor;
72732           pExpr->pTab = pTab;
72733           pSchema = pTab->pSchema;
72734           pMatch = pItem;
72735         }
72736         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
72737           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72738             /* If there has been exactly one prior match and this match
72739             ** is for the right-hand table of a NATURAL JOIN or is in a 
72740             ** USING clause, then skip this match.
72741             */
72742             if( cnt==1 ){
72743               if( pItem->jointype & JT_NATURAL ) continue;
72744               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
72745             }
72746             cnt++;
72747             pExpr->iTable = pItem->iCursor;
72748             pExpr->pTab = pTab;
72749             pMatch = pItem;
72750             pSchema = pTab->pSchema;
72751             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
72752             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
72753             break;
72754           }
72755         }
72756       }
72757     }
72758
72759 #ifndef SQLITE_OMIT_TRIGGER
72760     /* If we have not already resolved the name, then maybe 
72761     ** it is a new.* or old.* trigger argument reference
72762     */
72763     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
72764       int op = pParse->eTriggerOp;
72765       Table *pTab = 0;
72766       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
72767       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
72768         pExpr->iTable = 1;
72769         pTab = pParse->pTriggerTab;
72770       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
72771         pExpr->iTable = 0;
72772         pTab = pParse->pTriggerTab;
72773       }
72774
72775       if( pTab ){ 
72776         int iCol;
72777         pSchema = pTab->pSchema;
72778         cntTab++;
72779         for(iCol=0; iCol<pTab->nCol; iCol++){
72780           Column *pCol = &pTab->aCol[iCol];
72781           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72782             if( iCol==pTab->iPKey ){
72783               iCol = -1;
72784             }
72785             break;
72786           }
72787         }
72788         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
72789           iCol = -1;        /* IMP: R-44911-55124 */
72790         }
72791         if( iCol<pTab->nCol ){
72792           cnt++;
72793           if( iCol<0 ){
72794             pExpr->affinity = SQLITE_AFF_INTEGER;
72795           }else if( pExpr->iTable==0 ){
72796             testcase( iCol==31 );
72797             testcase( iCol==32 );
72798             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72799           }else{
72800             testcase( iCol==31 );
72801             testcase( iCol==32 );
72802             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72803           }
72804           pExpr->iColumn = (i16)iCol;
72805           pExpr->pTab = pTab;
72806           isTrigger = 1;
72807         }
72808       }
72809     }
72810 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
72811
72812     /*
72813     ** Perhaps the name is a reference to the ROWID
72814     */
72815     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
72816       cnt = 1;
72817       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
72818       pExpr->affinity = SQLITE_AFF_INTEGER;
72819     }
72820
72821     /*
72822     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
72823     ** might refer to an result-set alias.  This happens, for example, when
72824     ** we are resolving names in the WHERE clause of the following command:
72825     **
72826     **     SELECT a+b AS x FROM table WHERE x<10;
72827     **
72828     ** In cases like this, replace pExpr with a copy of the expression that
72829     ** forms the result set entry ("a+b" in the example) and return immediately.
72830     ** Note that the expression in the result set should have already been
72831     ** resolved by the time the WHERE clause is resolved.
72832     */
72833     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
72834       for(j=0; j<pEList->nExpr; j++){
72835         char *zAs = pEList->a[j].zName;
72836         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72837           Expr *pOrig;
72838           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
72839           assert( pExpr->x.pList==0 );
72840           assert( pExpr->x.pSelect==0 );
72841           pOrig = pEList->a[j].pExpr;
72842           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
72843             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
72844             return WRC_Abort;
72845           }
72846           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
72847           cnt = 1;
72848           pMatch = 0;
72849           assert( zTab==0 && zDb==0 );
72850           goto lookupname_end;
72851         }
72852       } 
72853     }
72854
72855     /* Advance to the next name context.  The loop will exit when either
72856     ** we have a match (cnt>0) or when we run out of name contexts.
72857     */
72858     if( cnt==0 ){
72859       pNC = pNC->pNext;
72860       nSubquery++;
72861     }
72862   }
72863
72864   /*
72865   ** If X and Y are NULL (in other words if only the column name Z is
72866   ** supplied) and the value of Z is enclosed in double-quotes, then
72867   ** Z is a string literal if it doesn't match any column names.  In that
72868   ** case, we need to return right away and not make any changes to
72869   ** pExpr.
72870   **
72871   ** Because no reference was made to outer contexts, the pNC->nRef
72872   ** fields are not changed in any context.
72873   */
72874   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
72875     pExpr->op = TK_STRING;
72876     pExpr->pTab = 0;
72877     return WRC_Prune;
72878   }
72879
72880   /*
72881   ** cnt==0 means there was not match.  cnt>1 means there were two or
72882   ** more matches.  Either way, we have an error.
72883   */
72884   if( cnt!=1 ){
72885     const char *zErr;
72886     zErr = cnt==0 ? "no such column" : "ambiguous column name";
72887     if( zDb ){
72888       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
72889     }else if( zTab ){
72890       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
72891     }else{
72892       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
72893     }
72894     pParse->checkSchema = 1;
72895     pTopNC->nErr++;
72896   }
72897
72898   /* If a column from a table in pSrcList is referenced, then record
72899   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
72900   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
72901   ** column number is greater than the number of bits in the bitmask
72902   ** then set the high-order bit of the bitmask.
72903   */
72904   if( pExpr->iColumn>=0 && pMatch!=0 ){
72905     int n = pExpr->iColumn;
72906     testcase( n==BMS-1 );
72907     if( n>=BMS ){
72908       n = BMS-1;
72909     }
72910     assert( pMatch->iCursor==pExpr->iTable );
72911     pMatch->colUsed |= ((Bitmask)1)<<n;
72912   }
72913
72914   /* Clean up and return
72915   */
72916   sqlite3ExprDelete(db, pExpr->pLeft);
72917   pExpr->pLeft = 0;
72918   sqlite3ExprDelete(db, pExpr->pRight);
72919   pExpr->pRight = 0;
72920   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
72921 lookupname_end:
72922   if( cnt==1 ){
72923     assert( pNC!=0 );
72924     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
72925     /* Increment the nRef value on all name contexts from TopNC up to
72926     ** the point where the name matched. */
72927     for(;;){
72928       assert( pTopNC!=0 );
72929       pTopNC->nRef++;
72930       if( pTopNC==pNC ) break;
72931       pTopNC = pTopNC->pNext;
72932     }
72933     return WRC_Prune;
72934   } else {
72935     return WRC_Abort;
72936   }
72937 }
72938
72939 /*
72940 ** Allocate and return a pointer to an expression to load the column iCol
72941 ** from datasource iSrc in SrcList pSrc.
72942 */
72943 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
72944   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
72945   if( p ){
72946     struct SrcList_item *pItem = &pSrc->a[iSrc];
72947     p->pTab = pItem->pTab;
72948     p->iTable = pItem->iCursor;
72949     if( p->pTab->iPKey==iCol ){
72950       p->iColumn = -1;
72951     }else{
72952       p->iColumn = (ynVar)iCol;
72953       testcase( iCol==BMS );
72954       testcase( iCol==BMS-1 );
72955       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
72956     }
72957     ExprSetProperty(p, EP_Resolved);
72958   }
72959   return p;
72960 }
72961
72962 /*
72963 ** This routine is callback for sqlite3WalkExpr().
72964 **
72965 ** Resolve symbolic names into TK_COLUMN operators for the current
72966 ** node in the expression tree.  Return 0 to continue the search down
72967 ** the tree or 2 to abort the tree walk.
72968 **
72969 ** This routine also does error checking and name resolution for
72970 ** function names.  The operator for aggregate functions is changed
72971 ** to TK_AGG_FUNCTION.
72972 */
72973 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
72974   NameContext *pNC;
72975   Parse *pParse;
72976
72977   pNC = pWalker->u.pNC;
72978   assert( pNC!=0 );
72979   pParse = pNC->pParse;
72980   assert( pParse==pWalker->pParse );
72981
72982   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
72983   ExprSetProperty(pExpr, EP_Resolved);
72984 #ifndef NDEBUG
72985   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
72986     SrcList *pSrcList = pNC->pSrcList;
72987     int i;
72988     for(i=0; i<pNC->pSrcList->nSrc; i++){
72989       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
72990     }
72991   }
72992 #endif
72993   switch( pExpr->op ){
72994
72995 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
72996     /* The special operator TK_ROW means use the rowid for the first
72997     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
72998     ** clause processing on UPDATE and DELETE statements.
72999     */
73000     case TK_ROW: {
73001       SrcList *pSrcList = pNC->pSrcList;
73002       struct SrcList_item *pItem;
73003       assert( pSrcList && pSrcList->nSrc==1 );
73004       pItem = pSrcList->a; 
73005       pExpr->op = TK_COLUMN;
73006       pExpr->pTab = pItem->pTab;
73007       pExpr->iTable = pItem->iCursor;
73008       pExpr->iColumn = -1;
73009       pExpr->affinity = SQLITE_AFF_INTEGER;
73010       break;
73011     }
73012 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
73013
73014     /* A lone identifier is the name of a column.
73015     */
73016     case TK_ID: {
73017       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73018     }
73019   
73020     /* A table name and column name:     ID.ID
73021     ** Or a database, table and column:  ID.ID.ID
73022     */
73023     case TK_DOT: {
73024       const char *zColumn;
73025       const char *zTable;
73026       const char *zDb;
73027       Expr *pRight;
73028
73029       /* if( pSrcList==0 ) break; */
73030       pRight = pExpr->pRight;
73031       if( pRight->op==TK_ID ){
73032         zDb = 0;
73033         zTable = pExpr->pLeft->u.zToken;
73034         zColumn = pRight->u.zToken;
73035       }else{
73036         assert( pRight->op==TK_DOT );
73037         zDb = pExpr->pLeft->u.zToken;
73038         zTable = pRight->pLeft->u.zToken;
73039         zColumn = pRight->pRight->u.zToken;
73040       }
73041       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73042     }
73043
73044     /* Resolve function names
73045     */
73046     case TK_CONST_FUNC:
73047     case TK_FUNCTION: {
73048       ExprList *pList = pExpr->x.pList;    /* The argument list */
73049       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73050       int no_such_func = 0;       /* True if no such function exists */
73051       int wrong_num_args = 0;     /* True if wrong number of arguments */
73052       int is_agg = 0;             /* True if is an aggregate function */
73053       int auth;                   /* Authorization to use the function */
73054       int nId;                    /* Number of characters in function name */
73055       const char *zId;            /* The function name. */
73056       FuncDef *pDef;              /* Information about the function */
73057       u8 enc = ENC(pParse->db);   /* The database encoding */
73058
73059       testcase( pExpr->op==TK_CONST_FUNC );
73060       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73061       zId = pExpr->u.zToken;
73062       nId = sqlite3Strlen30(zId);
73063       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
73064       if( pDef==0 ){
73065         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
73066         if( pDef==0 ){
73067           no_such_func = 1;
73068         }else{
73069           wrong_num_args = 1;
73070         }
73071       }else{
73072         is_agg = pDef->xFunc==0;
73073       }
73074 #ifndef SQLITE_OMIT_AUTHORIZATION
73075       if( pDef ){
73076         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
73077         if( auth!=SQLITE_OK ){
73078           if( auth==SQLITE_DENY ){
73079             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
73080                                     pDef->zName);
73081             pNC->nErr++;
73082           }
73083           pExpr->op = TK_NULL;
73084           return WRC_Prune;
73085         }
73086       }
73087 #endif
73088       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
73089         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73090         pNC->nErr++;
73091         is_agg = 0;
73092       }else if( no_such_func ){
73093         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73094         pNC->nErr++;
73095       }else if( wrong_num_args ){
73096         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73097              nId, zId);
73098         pNC->nErr++;
73099       }
73100       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
73101       sqlite3WalkExprList(pWalker, pList);
73102       if( is_agg ){
73103         NameContext *pNC2 = pNC;
73104         pExpr->op = TK_AGG_FUNCTION;
73105         pExpr->op2 = 0;
73106         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
73107           pExpr->op2++;
73108           pNC2 = pNC2->pNext;
73109         }
73110         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
73111         pNC->ncFlags |= NC_AllowAgg;
73112       }
73113       /* FIX ME:  Compute pExpr->affinity based on the expected return
73114       ** type of the function 
73115       */
73116       return WRC_Prune;
73117     }
73118 #ifndef SQLITE_OMIT_SUBQUERY
73119     case TK_SELECT:
73120     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73121 #endif
73122     case TK_IN: {
73123       testcase( pExpr->op==TK_IN );
73124       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73125         int nRef = pNC->nRef;
73126 #ifndef SQLITE_OMIT_CHECK
73127         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73128           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73129         }
73130 #endif
73131         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
73132         assert( pNC->nRef>=nRef );
73133         if( nRef!=pNC->nRef ){
73134           ExprSetProperty(pExpr, EP_VarSelect);
73135         }
73136       }
73137       break;
73138     }
73139 #ifndef SQLITE_OMIT_CHECK
73140     case TK_VARIABLE: {
73141       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73142         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73143       }
73144       break;
73145     }
73146 #endif
73147   }
73148   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73149 }
73150
73151 /*
73152 ** pEList is a list of expressions which are really the result set of the
73153 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73154 ** This routine checks to see if pE is a simple identifier which corresponds
73155 ** to the AS-name of one of the terms of the expression list.  If it is,
73156 ** this routine return an integer between 1 and N where N is the number of
73157 ** elements in pEList, corresponding to the matching entry.  If there is
73158 ** no match, or if pE is not a simple identifier, then this routine
73159 ** return 0.
73160 **
73161 ** pEList has been resolved.  pE has not.
73162 */
73163 static int resolveAsName(
73164   Parse *pParse,     /* Parsing context for error messages */
73165   ExprList *pEList,  /* List of expressions to scan */
73166   Expr *pE           /* Expression we are trying to match */
73167 ){
73168   int i;             /* Loop counter */
73169
73170   UNUSED_PARAMETER(pParse);
73171
73172   if( pE->op==TK_ID ){
73173     char *zCol = pE->u.zToken;
73174     for(i=0; i<pEList->nExpr; i++){
73175       char *zAs = pEList->a[i].zName;
73176       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73177         return i+1;
73178       }
73179     }
73180   }
73181   return 0;
73182 }
73183
73184 /*
73185 ** pE is a pointer to an expression which is a single term in the
73186 ** ORDER BY of a compound SELECT.  The expression has not been
73187 ** name resolved.
73188 **
73189 ** At the point this routine is called, we already know that the
73190 ** ORDER BY term is not an integer index into the result set.  That
73191 ** case is handled by the calling routine.
73192 **
73193 ** Attempt to match pE against result set columns in the left-most
73194 ** SELECT statement.  Return the index i of the matching column,
73195 ** as an indication to the caller that it should sort by the i-th column.
73196 ** The left-most column is 1.  In other words, the value returned is the
73197 ** same integer value that would be used in the SQL statement to indicate
73198 ** the column.
73199 **
73200 ** If there is no match, return 0.  Return -1 if an error occurs.
73201 */
73202 static int resolveOrderByTermToExprList(
73203   Parse *pParse,     /* Parsing context for error messages */
73204   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73205   Expr *pE           /* The specific ORDER BY term */
73206 ){
73207   int i;             /* Loop counter */
73208   ExprList *pEList;  /* The columns of the result set */
73209   NameContext nc;    /* Name context for resolving pE */
73210   sqlite3 *db;       /* Database connection */
73211   int rc;            /* Return code from subprocedures */
73212   u8 savedSuppErr;   /* Saved value of db->suppressErr */
73213
73214   assert( sqlite3ExprIsInteger(pE, &i)==0 );
73215   pEList = pSelect->pEList;
73216
73217   /* Resolve all names in the ORDER BY term expression
73218   */
73219   memset(&nc, 0, sizeof(nc));
73220   nc.pParse = pParse;
73221   nc.pSrcList = pSelect->pSrc;
73222   nc.pEList = pEList;
73223   nc.ncFlags = NC_AllowAgg;
73224   nc.nErr = 0;
73225   db = pParse->db;
73226   savedSuppErr = db->suppressErr;
73227   db->suppressErr = 1;
73228   rc = sqlite3ResolveExprNames(&nc, pE);
73229   db->suppressErr = savedSuppErr;
73230   if( rc ) return 0;
73231
73232   /* Try to match the ORDER BY expression against an expression
73233   ** in the result set.  Return an 1-based index of the matching
73234   ** result-set entry.
73235   */
73236   for(i=0; i<pEList->nExpr; i++){
73237     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73238       return i+1;
73239     }
73240   }
73241
73242   /* If no match, return 0. */
73243   return 0;
73244 }
73245
73246 /*
73247 ** Generate an ORDER BY or GROUP BY term out-of-range error.
73248 */
73249 static void resolveOutOfRangeError(
73250   Parse *pParse,         /* The error context into which to write the error */
73251   const char *zType,     /* "ORDER" or "GROUP" */
73252   int i,                 /* The index (1-based) of the term out of range */
73253   int mx                 /* Largest permissible value of i */
73254 ){
73255   sqlite3ErrorMsg(pParse, 
73256     "%r %s BY term out of range - should be "
73257     "between 1 and %d", i, zType, mx);
73258 }
73259
73260 /*
73261 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73262 ** each term of the ORDER BY clause is a constant integer between 1
73263 ** and N where N is the number of columns in the compound SELECT.
73264 **
73265 ** ORDER BY terms that are already an integer between 1 and N are
73266 ** unmodified.  ORDER BY terms that are integers outside the range of
73267 ** 1 through N generate an error.  ORDER BY terms that are expressions
73268 ** are matched against result set expressions of compound SELECT
73269 ** beginning with the left-most SELECT and working toward the right.
73270 ** At the first match, the ORDER BY expression is transformed into
73271 ** the integer column number.
73272 **
73273 ** Return the number of errors seen.
73274 */
73275 static int resolveCompoundOrderBy(
73276   Parse *pParse,        /* Parsing context.  Leave error messages here */
73277   Select *pSelect       /* The SELECT statement containing the ORDER BY */
73278 ){
73279   int i;
73280   ExprList *pOrderBy;
73281   ExprList *pEList;
73282   sqlite3 *db;
73283   int moreToDo = 1;
73284
73285   pOrderBy = pSelect->pOrderBy;
73286   if( pOrderBy==0 ) return 0;
73287   db = pParse->db;
73288 #if SQLITE_MAX_COLUMN
73289   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73290     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73291     return 1;
73292   }
73293 #endif
73294   for(i=0; i<pOrderBy->nExpr; i++){
73295     pOrderBy->a[i].done = 0;
73296   }
73297   pSelect->pNext = 0;
73298   while( pSelect->pPrior ){
73299     pSelect->pPrior->pNext = pSelect;
73300     pSelect = pSelect->pPrior;
73301   }
73302   while( pSelect && moreToDo ){
73303     struct ExprList_item *pItem;
73304     moreToDo = 0;
73305     pEList = pSelect->pEList;
73306     assert( pEList!=0 );
73307     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73308       int iCol = -1;
73309       Expr *pE, *pDup;
73310       if( pItem->done ) continue;
73311       pE = sqlite3ExprSkipCollate(pItem->pExpr);
73312       if( sqlite3ExprIsInteger(pE, &iCol) ){
73313         if( iCol<=0 || iCol>pEList->nExpr ){
73314           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73315           return 1;
73316         }
73317       }else{
73318         iCol = resolveAsName(pParse, pEList, pE);
73319         if( iCol==0 ){
73320           pDup = sqlite3ExprDup(db, pE, 0);
73321           if( !db->mallocFailed ){
73322             assert(pDup);
73323             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73324           }
73325           sqlite3ExprDelete(db, pDup);
73326         }
73327       }
73328       if( iCol>0 ){
73329         /* Convert the ORDER BY term into an integer column number iCol,
73330         ** taking care to preserve the COLLATE clause if it exists */
73331         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
73332         if( pNew==0 ) return 1;
73333         pNew->flags |= EP_IntValue;
73334         pNew->u.iValue = iCol;
73335         if( pItem->pExpr==pE ){
73336           pItem->pExpr = pNew;
73337         }else{
73338           assert( pItem->pExpr->op==TK_COLLATE );
73339           assert( pItem->pExpr->pLeft==pE );
73340           pItem->pExpr->pLeft = pNew;
73341         }
73342         sqlite3ExprDelete(db, pE);
73343         pItem->iOrderByCol = (u16)iCol;
73344         pItem->done = 1;
73345       }else{
73346         moreToDo = 1;
73347       }
73348     }
73349     pSelect = pSelect->pNext;
73350   }
73351   for(i=0; i<pOrderBy->nExpr; i++){
73352     if( pOrderBy->a[i].done==0 ){
73353       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73354             "column in the result set", i+1);
73355       return 1;
73356     }
73357   }
73358   return 0;
73359 }
73360
73361 /*
73362 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73363 ** the SELECT statement pSelect.  If any term is reference to a
73364 ** result set expression (as determined by the ExprList.a.iCol field)
73365 ** then convert that term into a copy of the corresponding result set
73366 ** column.
73367 **
73368 ** If any errors are detected, add an error message to pParse and
73369 ** return non-zero.  Return zero if no errors are seen.
73370 */
73371 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
73372   Parse *pParse,        /* Parsing context.  Leave error messages here */
73373   Select *pSelect,      /* The SELECT statement containing the clause */
73374   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
73375   const char *zType     /* "ORDER" or "GROUP" */
73376 ){
73377   int i;
73378   sqlite3 *db = pParse->db;
73379   ExprList *pEList;
73380   struct ExprList_item *pItem;
73381
73382   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
73383 #if SQLITE_MAX_COLUMN
73384   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73385     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
73386     return 1;
73387   }
73388 #endif
73389   pEList = pSelect->pEList;
73390   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
73391   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73392     if( pItem->iOrderByCol ){
73393       if( pItem->iOrderByCol>pEList->nExpr ){
73394         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
73395         return 1;
73396       }
73397       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
73398     }
73399   }
73400   return 0;
73401 }
73402
73403 /*
73404 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
73405 ** The Name context of the SELECT statement is pNC.  zType is either
73406 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
73407 **
73408 ** This routine resolves each term of the clause into an expression.
73409 ** If the order-by term is an integer I between 1 and N (where N is the
73410 ** number of columns in the result set of the SELECT) then the expression
73411 ** in the resolution is a copy of the I-th result-set expression.  If
73412 ** the order-by term is an identify that corresponds to the AS-name of
73413 ** a result-set expression, then the term resolves to a copy of the
73414 ** result-set expression.  Otherwise, the expression is resolved in
73415 ** the usual way - using sqlite3ResolveExprNames().
73416 **
73417 ** This routine returns the number of errors.  If errors occur, then
73418 ** an appropriate error message might be left in pParse.  (OOM errors
73419 ** excepted.)
73420 */
73421 static int resolveOrderGroupBy(
73422   NameContext *pNC,     /* The name context of the SELECT statement */
73423   Select *pSelect,      /* The SELECT statement holding pOrderBy */
73424   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
73425   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
73426 ){
73427   int i, j;                      /* Loop counters */
73428   int iCol;                      /* Column number */
73429   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
73430   Parse *pParse;                 /* Parsing context */
73431   int nResult;                   /* Number of terms in the result set */
73432
73433   if( pOrderBy==0 ) return 0;
73434   nResult = pSelect->pEList->nExpr;
73435   pParse = pNC->pParse;
73436   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73437     Expr *pE = pItem->pExpr;
73438     iCol = resolveAsName(pParse, pSelect->pEList, pE);
73439     if( iCol>0 ){
73440       /* If an AS-name match is found, mark this ORDER BY column as being
73441       ** a copy of the iCol-th result-set column.  The subsequent call to
73442       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
73443       ** copy of the iCol-th result-set expression. */
73444       pItem->iOrderByCol = (u16)iCol;
73445       continue;
73446     }
73447     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
73448       /* The ORDER BY term is an integer constant.  Again, set the column
73449       ** number so that sqlite3ResolveOrderGroupBy() will convert the
73450       ** order-by term to a copy of the result-set expression */
73451       if( iCol<1 || iCol>0xffff ){
73452         resolveOutOfRangeError(pParse, zType, i+1, nResult);
73453         return 1;
73454       }
73455       pItem->iOrderByCol = (u16)iCol;
73456       continue;
73457     }
73458
73459     /* Otherwise, treat the ORDER BY term as an ordinary expression */
73460     pItem->iOrderByCol = 0;
73461     if( sqlite3ResolveExprNames(pNC, pE) ){
73462       return 1;
73463     }
73464     for(j=0; j<pSelect->pEList->nExpr; j++){
73465       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
73466         pItem->iOrderByCol = j+1;
73467       }
73468     }
73469   }
73470   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
73471 }
73472
73473 /*
73474 ** Resolve names in the SELECT statement p and all of its descendents.
73475 */
73476 static int resolveSelectStep(Walker *pWalker, Select *p){
73477   NameContext *pOuterNC;  /* Context that contains this SELECT */
73478   NameContext sNC;        /* Name context of this SELECT */
73479   int isCompound;         /* True if p is a compound select */
73480   int nCompound;          /* Number of compound terms processed so far */
73481   Parse *pParse;          /* Parsing context */
73482   ExprList *pEList;       /* Result set expression list */
73483   int i;                  /* Loop counter */
73484   ExprList *pGroupBy;     /* The GROUP BY clause */
73485   Select *pLeftmost;      /* Left-most of SELECT of a compound */
73486   sqlite3 *db;            /* Database connection */
73487   
73488
73489   assert( p!=0 );
73490   if( p->selFlags & SF_Resolved ){
73491     return WRC_Prune;
73492   }
73493   pOuterNC = pWalker->u.pNC;
73494   pParse = pWalker->pParse;
73495   db = pParse->db;
73496
73497   /* Normally sqlite3SelectExpand() will be called first and will have
73498   ** already expanded this SELECT.  However, if this is a subquery within
73499   ** an expression, sqlite3ResolveExprNames() will be called without a
73500   ** prior call to sqlite3SelectExpand().  When that happens, let
73501   ** sqlite3SelectPrep() do all of the processing for this SELECT.
73502   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
73503   ** this routine in the correct order.
73504   */
73505   if( (p->selFlags & SF_Expanded)==0 ){
73506     sqlite3SelectPrep(pParse, p, pOuterNC);
73507     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
73508   }
73509
73510   isCompound = p->pPrior!=0;
73511   nCompound = 0;
73512   pLeftmost = p;
73513   while( p ){
73514     assert( (p->selFlags & SF_Expanded)!=0 );
73515     assert( (p->selFlags & SF_Resolved)==0 );
73516     p->selFlags |= SF_Resolved;
73517
73518     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
73519     ** are not allowed to refer to any names, so pass an empty NameContext.
73520     */
73521     memset(&sNC, 0, sizeof(sNC));
73522     sNC.pParse = pParse;
73523     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
73524         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
73525       return WRC_Abort;
73526     }
73527   
73528     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
73529     ** resolve the result-set expression list.
73530     */
73531     sNC.ncFlags = NC_AllowAgg;
73532     sNC.pSrcList = p->pSrc;
73533     sNC.pNext = pOuterNC;
73534   
73535     /* Resolve names in the result set. */
73536     pEList = p->pEList;
73537     assert( pEList!=0 );
73538     for(i=0; i<pEList->nExpr; i++){
73539       Expr *pX = pEList->a[i].pExpr;
73540       if( sqlite3ResolveExprNames(&sNC, pX) ){
73541         return WRC_Abort;
73542       }
73543     }
73544   
73545     /* Recursively resolve names in all subqueries
73546     */
73547     for(i=0; i<p->pSrc->nSrc; i++){
73548       struct SrcList_item *pItem = &p->pSrc->a[i];
73549       if( pItem->pSelect ){
73550         NameContext *pNC;         /* Used to iterate name contexts */
73551         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
73552         const char *zSavedContext = pParse->zAuthContext;
73553
73554         /* Count the total number of references to pOuterNC and all of its
73555         ** parent contexts. After resolving references to expressions in
73556         ** pItem->pSelect, check if this value has changed. If so, then
73557         ** SELECT statement pItem->pSelect must be correlated. Set the
73558         ** pItem->isCorrelated flag if this is the case. */
73559         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
73560
73561         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
73562         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
73563         pParse->zAuthContext = zSavedContext;
73564         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
73565
73566         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
73567         assert( pItem->isCorrelated==0 && nRef<=0 );
73568         pItem->isCorrelated = (nRef!=0);
73569       }
73570     }
73571   
73572     /* If there are no aggregate functions in the result-set, and no GROUP BY 
73573     ** expression, do not allow aggregates in any of the other expressions.
73574     */
73575     assert( (p->selFlags & SF_Aggregate)==0 );
73576     pGroupBy = p->pGroupBy;
73577     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
73578       p->selFlags |= SF_Aggregate;
73579     }else{
73580       sNC.ncFlags &= ~NC_AllowAgg;
73581     }
73582   
73583     /* If a HAVING clause is present, then there must be a GROUP BY clause.
73584     */
73585     if( p->pHaving && !pGroupBy ){
73586       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
73587       return WRC_Abort;
73588     }
73589   
73590     /* Add the expression list to the name-context before parsing the
73591     ** other expressions in the SELECT statement. This is so that
73592     ** expressions in the WHERE clause (etc.) can refer to expressions by
73593     ** aliases in the result set.
73594     **
73595     ** Minor point: If this is the case, then the expression will be
73596     ** re-evaluated for each reference to it.
73597     */
73598     sNC.pEList = p->pEList;
73599     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
73600        sqlite3ResolveExprNames(&sNC, p->pHaving)
73601     ){
73602       return WRC_Abort;
73603     }
73604
73605     /* The ORDER BY and GROUP BY clauses may not refer to terms in
73606     ** outer queries 
73607     */
73608     sNC.pNext = 0;
73609     sNC.ncFlags |= NC_AllowAgg;
73610
73611     /* Process the ORDER BY clause for singleton SELECT statements.
73612     ** The ORDER BY clause for compounds SELECT statements is handled
73613     ** below, after all of the result-sets for all of the elements of
73614     ** the compound have been resolved.
73615     */
73616     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
73617       return WRC_Abort;
73618     }
73619     if( db->mallocFailed ){
73620       return WRC_Abort;
73621     }
73622   
73623     /* Resolve the GROUP BY clause.  At the same time, make sure 
73624     ** the GROUP BY clause does not contain aggregate functions.
73625     */
73626     if( pGroupBy ){
73627       struct ExprList_item *pItem;
73628     
73629       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
73630         return WRC_Abort;
73631       }
73632       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
73633         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
73634           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
73635               "the GROUP BY clause");
73636           return WRC_Abort;
73637         }
73638       }
73639     }
73640
73641     /* Advance to the next term of the compound
73642     */
73643     p = p->pPrior;
73644     nCompound++;
73645   }
73646
73647   /* Resolve the ORDER BY on a compound SELECT after all terms of
73648   ** the compound have been resolved.
73649   */
73650   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
73651     return WRC_Abort;
73652   }
73653
73654   return WRC_Prune;
73655 }
73656
73657 /*
73658 ** This routine walks an expression tree and resolves references to
73659 ** table columns and result-set columns.  At the same time, do error
73660 ** checking on function usage and set a flag if any aggregate functions
73661 ** are seen.
73662 **
73663 ** To resolve table columns references we look for nodes (or subtrees) of the 
73664 ** form X.Y.Z or Y.Z or just Z where
73665 **
73666 **      X:   The name of a database.  Ex:  "main" or "temp" or
73667 **           the symbolic name assigned to an ATTACH-ed database.
73668 **
73669 **      Y:   The name of a table in a FROM clause.  Or in a trigger
73670 **           one of the special names "old" or "new".
73671 **
73672 **      Z:   The name of a column in table Y.
73673 **
73674 ** The node at the root of the subtree is modified as follows:
73675 **
73676 **    Expr.op        Changed to TK_COLUMN
73677 **    Expr.pTab      Points to the Table object for X.Y
73678 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
73679 **    Expr.iTable    The VDBE cursor number for X.Y
73680 **
73681 **
73682 ** To resolve result-set references, look for expression nodes of the
73683 ** form Z (with no X and Y prefix) where the Z matches the right-hand
73684 ** size of an AS clause in the result-set of a SELECT.  The Z expression
73685 ** is replaced by a copy of the left-hand side of the result-set expression.
73686 ** Table-name and function resolution occurs on the substituted expression
73687 ** tree.  For example, in:
73688 **
73689 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
73690 **
73691 ** The "x" term of the order by is replaced by "a+b" to render:
73692 **
73693 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
73694 **
73695 ** Function calls are checked to make sure that the function is 
73696 ** defined and that the correct number of arguments are specified.
73697 ** If the function is an aggregate function, then the NC_HasAgg flag is
73698 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
73699 ** If an expression contains aggregate functions then the EP_Agg
73700 ** property on the expression is set.
73701 **
73702 ** An error message is left in pParse if anything is amiss.  The number
73703 ** if errors is returned.
73704 */
73705 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
73706   NameContext *pNC,       /* Namespace to resolve expressions in. */
73707   Expr *pExpr             /* The expression to be analyzed. */
73708 ){
73709   u8 savedHasAgg;
73710   Walker w;
73711
73712   if( pExpr==0 ) return 0;
73713 #if SQLITE_MAX_EXPR_DEPTH>0
73714   {
73715     Parse *pParse = pNC->pParse;
73716     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
73717       return 1;
73718     }
73719     pParse->nHeight += pExpr->nHeight;
73720   }
73721 #endif
73722   savedHasAgg = pNC->ncFlags & NC_HasAgg;
73723   pNC->ncFlags &= ~NC_HasAgg;
73724   w.xExprCallback = resolveExprStep;
73725   w.xSelectCallback = resolveSelectStep;
73726   w.pParse = pNC->pParse;
73727   w.u.pNC = pNC;
73728   sqlite3WalkExpr(&w, pExpr);
73729 #if SQLITE_MAX_EXPR_DEPTH>0
73730   pNC->pParse->nHeight -= pExpr->nHeight;
73731 #endif
73732   if( pNC->nErr>0 || w.pParse->nErr>0 ){
73733     ExprSetProperty(pExpr, EP_Error);
73734   }
73735   if( pNC->ncFlags & NC_HasAgg ){
73736     ExprSetProperty(pExpr, EP_Agg);
73737   }else if( savedHasAgg ){
73738     pNC->ncFlags |= NC_HasAgg;
73739   }
73740   return ExprHasProperty(pExpr, EP_Error);
73741 }
73742
73743
73744 /*
73745 ** Resolve all names in all expressions of a SELECT and in all
73746 ** decendents of the SELECT, including compounds off of p->pPrior,
73747 ** subqueries in expressions, and subqueries used as FROM clause
73748 ** terms.
73749 **
73750 ** See sqlite3ResolveExprNames() for a description of the kinds of
73751 ** transformations that occur.
73752 **
73753 ** All SELECT statements should have been expanded using
73754 ** sqlite3SelectExpand() prior to invoking this routine.
73755 */
73756 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
73757   Parse *pParse,         /* The parser context */
73758   Select *p,             /* The SELECT statement being coded. */
73759   NameContext *pOuterNC  /* Name context for parent SELECT statement */
73760 ){
73761   Walker w;
73762
73763   assert( p!=0 );
73764   w.xExprCallback = resolveExprStep;
73765   w.xSelectCallback = resolveSelectStep;
73766   w.pParse = pParse;
73767   w.u.pNC = pOuterNC;
73768   sqlite3WalkSelect(&w, p);
73769 }
73770
73771 /************** End of resolve.c *********************************************/
73772 /************** Begin file expr.c ********************************************/
73773 /*
73774 ** 2001 September 15
73775 **
73776 ** The author disclaims copyright to this source code.  In place of
73777 ** a legal notice, here is a blessing:
73778 **
73779 **    May you do good and not evil.
73780 **    May you find forgiveness for yourself and forgive others.
73781 **    May you share freely, never taking more than you give.
73782 **
73783 *************************************************************************
73784 ** This file contains routines used for analyzing expressions and
73785 ** for generating VDBE code that evaluates expressions in SQLite.
73786 */
73787
73788 /*
73789 ** Return the 'affinity' of the expression pExpr if any.
73790 **
73791 ** If pExpr is a column, a reference to a column via an 'AS' alias,
73792 ** or a sub-select with a column as the return value, then the 
73793 ** affinity of that column is returned. Otherwise, 0x00 is returned,
73794 ** indicating no affinity for the expression.
73795 **
73796 ** i.e. the WHERE clause expresssions in the following statements all
73797 ** have an affinity:
73798 **
73799 ** CREATE TABLE t1(a);
73800 ** SELECT * FROM t1 WHERE a;
73801 ** SELECT a AS b FROM t1 WHERE b;
73802 ** SELECT * FROM t1 WHERE (select a from t1);
73803 */
73804 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
73805   int op;
73806   pExpr = sqlite3ExprSkipCollate(pExpr);
73807   op = pExpr->op;
73808   if( op==TK_SELECT ){
73809     assert( pExpr->flags&EP_xIsSelect );
73810     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
73811   }
73812 #ifndef SQLITE_OMIT_CAST
73813   if( op==TK_CAST ){
73814     assert( !ExprHasProperty(pExpr, EP_IntValue) );
73815     return sqlite3AffinityType(pExpr->u.zToken);
73816   }
73817 #endif
73818   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
73819    && pExpr->pTab!=0
73820   ){
73821     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
73822     ** a TK_COLUMN but was previously evaluated and cached in a register */
73823     int j = pExpr->iColumn;
73824     if( j<0 ) return SQLITE_AFF_INTEGER;
73825     assert( pExpr->pTab && j<pExpr->pTab->nCol );
73826     return pExpr->pTab->aCol[j].affinity;
73827   }
73828   return pExpr->affinity;
73829 }
73830
73831 /*
73832 ** Set the collating sequence for expression pExpr to be the collating
73833 ** sequence named by pToken.   Return a pointer to a new Expr node that
73834 ** implements the COLLATE operator.
73835 **
73836 ** If a memory allocation error occurs, that fact is recorded in pParse->db
73837 ** and the pExpr parameter is returned unchanged.
73838 */
73839 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
73840   if( pCollName->n>0 ){
73841     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
73842     if( pNew ){
73843       pNew->pLeft = pExpr;
73844       pNew->flags |= EP_Collate;
73845       pExpr = pNew;
73846     }
73847   }
73848   return pExpr;
73849 }
73850 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
73851   Token s;
73852   assert( zC!=0 );
73853   s.z = zC;
73854   s.n = sqlite3Strlen30(s.z);
73855   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
73856 }
73857
73858 /*
73859 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
73860 ** an expression.
73861 */
73862 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
73863   while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
73864     pExpr = pExpr->pLeft;
73865   }
73866   return pExpr;
73867 }
73868
73869 /*
73870 ** Return the collation sequence for the expression pExpr. If
73871 ** there is no defined collating sequence, return NULL.
73872 **
73873 ** The collating sequence might be determined by a COLLATE operator
73874 ** or by the presence of a column with a defined collating sequence.
73875 ** COLLATE operators take first precedence.  Left operands take
73876 ** precedence over right operands.
73877 */
73878 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
73879   sqlite3 *db = pParse->db;
73880   CollSeq *pColl = 0;
73881   Expr *p = pExpr;
73882   while( p ){
73883     int op = p->op;
73884     if( op==TK_CAST || op==TK_UPLUS ){
73885       p = p->pLeft;
73886       continue;
73887     }
73888     assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
73889     if( op==TK_COLLATE ){
73890       if( db->init.busy ){
73891         /* Do not report errors when parsing while the schema */
73892         pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
73893       }else{
73894         pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
73895       }
73896       break;
73897     }
73898     if( p->pTab!=0
73899      && (op==TK_AGG_COLUMN || op==TK_COLUMN
73900           || op==TK_REGISTER || op==TK_TRIGGER)
73901     ){
73902       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
73903       ** a TK_COLUMN but was previously evaluated and cached in a register */
73904       int j = p->iColumn;
73905       if( j>=0 ){
73906         const char *zColl = p->pTab->aCol[j].zColl;
73907         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
73908       }
73909       break;
73910     }
73911     if( p->flags & EP_Collate ){
73912       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
73913         p = p->pLeft;
73914       }else{
73915         p = p->pRight;
73916       }
73917     }else{
73918       break;
73919     }
73920   }
73921   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
73922     pColl = 0;
73923   }
73924   return pColl;
73925 }
73926
73927 /*
73928 ** pExpr is an operand of a comparison operator.  aff2 is the
73929 ** type affinity of the other operand.  This routine returns the
73930 ** type affinity that should be used for the comparison operator.
73931 */
73932 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
73933   char aff1 = sqlite3ExprAffinity(pExpr);
73934   if( aff1 && aff2 ){
73935     /* Both sides of the comparison are columns. If one has numeric
73936     ** affinity, use that. Otherwise use no affinity.
73937     */
73938     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
73939       return SQLITE_AFF_NUMERIC;
73940     }else{
73941       return SQLITE_AFF_NONE;
73942     }
73943   }else if( !aff1 && !aff2 ){
73944     /* Neither side of the comparison is a column.  Compare the
73945     ** results directly.
73946     */
73947     return SQLITE_AFF_NONE;
73948   }else{
73949     /* One side is a column, the other is not. Use the columns affinity. */
73950     assert( aff1==0 || aff2==0 );
73951     return (aff1 + aff2);
73952   }
73953 }
73954
73955 /*
73956 ** pExpr is a comparison operator.  Return the type affinity that should
73957 ** be applied to both operands prior to doing the comparison.
73958 */
73959 static char comparisonAffinity(Expr *pExpr){
73960   char aff;
73961   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
73962           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
73963           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
73964   assert( pExpr->pLeft );
73965   aff = sqlite3ExprAffinity(pExpr->pLeft);
73966   if( pExpr->pRight ){
73967     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
73968   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73969     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
73970   }else if( !aff ){
73971     aff = SQLITE_AFF_NONE;
73972   }
73973   return aff;
73974 }
73975
73976 /*
73977 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
73978 ** idx_affinity is the affinity of an indexed column. Return true
73979 ** if the index with affinity idx_affinity may be used to implement
73980 ** the comparison in pExpr.
73981 */
73982 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
73983   char aff = comparisonAffinity(pExpr);
73984   switch( aff ){
73985     case SQLITE_AFF_NONE:
73986       return 1;
73987     case SQLITE_AFF_TEXT:
73988       return idx_affinity==SQLITE_AFF_TEXT;
73989     default:
73990       return sqlite3IsNumericAffinity(idx_affinity);
73991   }
73992 }
73993
73994 /*
73995 ** Return the P5 value that should be used for a binary comparison
73996 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
73997 */
73998 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
73999   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
74000   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74001   return aff;
74002 }
74003
74004 /*
74005 ** Return a pointer to the collation sequence that should be used by
74006 ** a binary comparison operator comparing pLeft and pRight.
74007 **
74008 ** If the left hand expression has a collating sequence type, then it is
74009 ** used. Otherwise the collation sequence for the right hand expression
74010 ** is used, or the default (BINARY) if neither expression has a collating
74011 ** type.
74012 **
74013 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
74014 ** it is not considered.
74015 */
74016 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
74017   Parse *pParse, 
74018   Expr *pLeft, 
74019   Expr *pRight
74020 ){
74021   CollSeq *pColl;
74022   assert( pLeft );
74023   if( pLeft->flags & EP_Collate ){
74024     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74025   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
74026     pColl = sqlite3ExprCollSeq(pParse, pRight);
74027   }else{
74028     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74029     if( !pColl ){
74030       pColl = sqlite3ExprCollSeq(pParse, pRight);
74031     }
74032   }
74033   return pColl;
74034 }
74035
74036 /*
74037 ** Generate code for a comparison operator.
74038 */
74039 static int codeCompare(
74040   Parse *pParse,    /* The parsing (and code generating) context */
74041   Expr *pLeft,      /* The left operand */
74042   Expr *pRight,     /* The right operand */
74043   int opcode,       /* The comparison opcode */
74044   int in1, int in2, /* Register holding operands */
74045   int dest,         /* Jump here if true.  */
74046   int jumpIfNull    /* If true, jump if either operand is NULL */
74047 ){
74048   int p5;
74049   int addr;
74050   CollSeq *p4;
74051
74052   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
74053   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74054   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74055                            (void*)p4, P4_COLLSEQ);
74056   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74057   return addr;
74058 }
74059
74060 #if SQLITE_MAX_EXPR_DEPTH>0
74061 /*
74062 ** Check that argument nHeight is less than or equal to the maximum
74063 ** expression depth allowed. If it is not, leave an error message in
74064 ** pParse.
74065 */
74066 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
74067   int rc = SQLITE_OK;
74068   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
74069   if( nHeight>mxHeight ){
74070     sqlite3ErrorMsg(pParse, 
74071        "Expression tree is too large (maximum depth %d)", mxHeight
74072     );
74073     rc = SQLITE_ERROR;
74074   }
74075   return rc;
74076 }
74077
74078 /* The following three functions, heightOfExpr(), heightOfExprList()
74079 ** and heightOfSelect(), are used to determine the maximum height
74080 ** of any expression tree referenced by the structure passed as the
74081 ** first argument.
74082 **
74083 ** If this maximum height is greater than the current value pointed
74084 ** to by pnHeight, the second parameter, then set *pnHeight to that
74085 ** value.
74086 */
74087 static void heightOfExpr(Expr *p, int *pnHeight){
74088   if( p ){
74089     if( p->nHeight>*pnHeight ){
74090       *pnHeight = p->nHeight;
74091     }
74092   }
74093 }
74094 static void heightOfExprList(ExprList *p, int *pnHeight){
74095   if( p ){
74096     int i;
74097     for(i=0; i<p->nExpr; i++){
74098       heightOfExpr(p->a[i].pExpr, pnHeight);
74099     }
74100   }
74101 }
74102 static void heightOfSelect(Select *p, int *pnHeight){
74103   if( p ){
74104     heightOfExpr(p->pWhere, pnHeight);
74105     heightOfExpr(p->pHaving, pnHeight);
74106     heightOfExpr(p->pLimit, pnHeight);
74107     heightOfExpr(p->pOffset, pnHeight);
74108     heightOfExprList(p->pEList, pnHeight);
74109     heightOfExprList(p->pGroupBy, pnHeight);
74110     heightOfExprList(p->pOrderBy, pnHeight);
74111     heightOfSelect(p->pPrior, pnHeight);
74112   }
74113 }
74114
74115 /*
74116 ** Set the Expr.nHeight variable in the structure passed as an 
74117 ** argument. An expression with no children, Expr.pList or 
74118 ** Expr.pSelect member has a height of 1. Any other expression
74119 ** has a height equal to the maximum height of any other 
74120 ** referenced Expr plus one.
74121 */
74122 static void exprSetHeight(Expr *p){
74123   int nHeight = 0;
74124   heightOfExpr(p->pLeft, &nHeight);
74125   heightOfExpr(p->pRight, &nHeight);
74126   if( ExprHasProperty(p, EP_xIsSelect) ){
74127     heightOfSelect(p->x.pSelect, &nHeight);
74128   }else{
74129     heightOfExprList(p->x.pList, &nHeight);
74130   }
74131   p->nHeight = nHeight + 1;
74132 }
74133
74134 /*
74135 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
74136 ** the height is greater than the maximum allowed expression depth,
74137 ** leave an error in pParse.
74138 */
74139 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
74140   exprSetHeight(p);
74141   sqlite3ExprCheckHeight(pParse, p->nHeight);
74142 }
74143
74144 /*
74145 ** Return the maximum height of any expression tree referenced
74146 ** by the select statement passed as an argument.
74147 */
74148 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
74149   int nHeight = 0;
74150   heightOfSelect(p, &nHeight);
74151   return nHeight;
74152 }
74153 #else
74154   #define exprSetHeight(y)
74155 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
74156
74157 /*
74158 ** This routine is the core allocator for Expr nodes.
74159 **
74160 ** Construct a new expression node and return a pointer to it.  Memory
74161 ** for this node and for the pToken argument is a single allocation
74162 ** obtained from sqlite3DbMalloc().  The calling function
74163 ** is responsible for making sure the node eventually gets freed.
74164 **
74165 ** If dequote is true, then the token (if it exists) is dequoted.
74166 ** If dequote is false, no dequoting is performance.  The deQuote
74167 ** parameter is ignored if pToken is NULL or if the token does not
74168 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74169 ** then the EP_DblQuoted flag is set on the expression node.
74170 **
74171 ** Special case:  If op==TK_INTEGER and pToken points to a string that
74172 ** can be translated into a 32-bit integer, then the token is not
74173 ** stored in u.zToken.  Instead, the integer values is written
74174 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
74175 ** is allocated to hold the integer text and the dequote flag is ignored.
74176 */
74177 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
74178   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74179   int op,                 /* Expression opcode */
74180   const Token *pToken,    /* Token argument.  Might be NULL */
74181   int dequote             /* True to dequote */
74182 ){
74183   Expr *pNew;
74184   int nExtra = 0;
74185   int iValue = 0;
74186
74187   if( pToken ){
74188     if( op!=TK_INTEGER || pToken->z==0
74189           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
74190       nExtra = pToken->n+1;
74191       assert( iValue>=0 );
74192     }
74193   }
74194   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
74195   if( pNew ){
74196     pNew->op = (u8)op;
74197     pNew->iAgg = -1;
74198     if( pToken ){
74199       if( nExtra==0 ){
74200         pNew->flags |= EP_IntValue;
74201         pNew->u.iValue = iValue;
74202       }else{
74203         int c;
74204         pNew->u.zToken = (char*)&pNew[1];
74205         assert( pToken->z!=0 || pToken->n==0 );
74206         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74207         pNew->u.zToken[pToken->n] = 0;
74208         if( dequote && nExtra>=3 
74209              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74210           sqlite3Dequote(pNew->u.zToken);
74211           if( c=='"' ) pNew->flags |= EP_DblQuoted;
74212         }
74213       }
74214     }
74215 #if SQLITE_MAX_EXPR_DEPTH>0
74216     pNew->nHeight = 1;
74217 #endif  
74218   }
74219   return pNew;
74220 }
74221
74222 /*
74223 ** Allocate a new expression node from a zero-terminated token that has
74224 ** already been dequoted.
74225 */
74226 SQLITE_PRIVATE Expr *sqlite3Expr(
74227   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74228   int op,                 /* Expression opcode */
74229   const char *zToken      /* Token argument.  Might be NULL */
74230 ){
74231   Token x;
74232   x.z = zToken;
74233   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
74234   return sqlite3ExprAlloc(db, op, &x, 0);
74235 }
74236
74237 /*
74238 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
74239 **
74240 ** If pRoot==NULL that means that a memory allocation error has occurred.
74241 ** In that case, delete the subtrees pLeft and pRight.
74242 */
74243 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
74244   sqlite3 *db,
74245   Expr *pRoot,
74246   Expr *pLeft,
74247   Expr *pRight
74248 ){
74249   if( pRoot==0 ){
74250     assert( db->mallocFailed );
74251     sqlite3ExprDelete(db, pLeft);
74252     sqlite3ExprDelete(db, pRight);
74253   }else{
74254     if( pRight ){
74255       pRoot->pRight = pRight;
74256       pRoot->flags |= EP_Collate & pRight->flags;
74257     }
74258     if( pLeft ){
74259       pRoot->pLeft = pLeft;
74260       pRoot->flags |= EP_Collate & pLeft->flags;
74261     }
74262     exprSetHeight(pRoot);
74263   }
74264 }
74265
74266 /*
74267 ** Allocate a Expr node which joins as many as two subtrees.
74268 **
74269 ** One or both of the subtrees can be NULL.  Return a pointer to the new
74270 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74271 ** free the subtrees and return NULL.
74272 */
74273 SQLITE_PRIVATE Expr *sqlite3PExpr(
74274   Parse *pParse,          /* Parsing context */
74275   int op,                 /* Expression opcode */
74276   Expr *pLeft,            /* Left operand */
74277   Expr *pRight,           /* Right operand */
74278   const Token *pToken     /* Argument token */
74279 ){
74280   Expr *p;
74281   if( op==TK_AND && pLeft && pRight ){
74282     /* Take advantage of short-circuit false optimization for AND */
74283     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
74284   }else{
74285     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
74286     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74287   }
74288   if( p ) {
74289     sqlite3ExprCheckHeight(pParse, p->nHeight);
74290   }
74291   return p;
74292 }
74293
74294 /*
74295 ** Return 1 if an expression must be FALSE in all cases and 0 if the
74296 ** expression might be true.  This is an optimization.  If is OK to
74297 ** return 0 here even if the expression really is always false (a 
74298 ** false negative).  But it is a bug to return 1 if the expression
74299 ** might be true in some rare circumstances (a false positive.)
74300 **
74301 ** Note that if the expression is part of conditional for a
74302 ** LEFT JOIN, then we cannot determine at compile-time whether or not
74303 ** is it true or false, so always return 0.
74304 */
74305 static int exprAlwaysFalse(Expr *p){
74306   int v = 0;
74307   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
74308   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
74309   return v==0;
74310 }
74311
74312 /*
74313 ** Join two expressions using an AND operator.  If either expression is
74314 ** NULL, then just return the other expression.
74315 **
74316 ** If one side or the other of the AND is known to be false, then instead
74317 ** of returning an AND expression, just return a constant expression with
74318 ** a value of false.
74319 */
74320 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
74321   if( pLeft==0 ){
74322     return pRight;
74323   }else if( pRight==0 ){
74324     return pLeft;
74325   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
74326     sqlite3ExprDelete(db, pLeft);
74327     sqlite3ExprDelete(db, pRight);
74328     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
74329   }else{
74330     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
74331     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74332     return pNew;
74333   }
74334 }
74335
74336 /*
74337 ** Construct a new expression node for a function with multiple
74338 ** arguments.
74339 */
74340 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74341   Expr *pNew;
74342   sqlite3 *db = pParse->db;
74343   assert( pToken );
74344   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74345   if( pNew==0 ){
74346     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74347     return 0;
74348   }
74349   pNew->x.pList = pList;
74350   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74351   sqlite3ExprSetHeight(pParse, pNew);
74352   return pNew;
74353 }
74354
74355 /*
74356 ** Assign a variable number to an expression that encodes a wildcard
74357 ** in the original SQL statement.  
74358 **
74359 ** Wildcards consisting of a single "?" are assigned the next sequential
74360 ** variable number.
74361 **
74362 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74363 ** sure "nnn" is not too be to avoid a denial of service attack when
74364 ** the SQL statement comes from an external source.
74365 **
74366 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74367 ** as the previous instance of the same wildcard.  Or if this is the first
74368 ** instance of the wildcard, the next sequenial variable number is
74369 ** assigned.
74370 */
74371 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74372   sqlite3 *db = pParse->db;
74373   const char *z;
74374
74375   if( pExpr==0 ) return;
74376   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74377   z = pExpr->u.zToken;
74378   assert( z!=0 );
74379   assert( z[0]!=0 );
74380   if( z[1]==0 ){
74381     /* Wildcard of the form "?".  Assign the next variable number */
74382     assert( z[0]=='?' );
74383     pExpr->iColumn = (ynVar)(++pParse->nVar);
74384   }else{
74385     ynVar x = 0;
74386     u32 n = sqlite3Strlen30(z);
74387     if( z[0]=='?' ){
74388       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74389       ** use it as the variable number */
74390       i64 i;
74391       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
74392       pExpr->iColumn = x = (ynVar)i;
74393       testcase( i==0 );
74394       testcase( i==1 );
74395       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
74396       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
74397       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74398         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74399             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
74400         x = 0;
74401       }
74402       if( i>pParse->nVar ){
74403         pParse->nVar = (int)i;
74404       }
74405     }else{
74406       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74407       ** number as the prior appearance of the same name, or if the name
74408       ** has never appeared before, reuse the same variable number
74409       */
74410       ynVar i;
74411       for(i=0; i<pParse->nzVar; i++){
74412         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
74413           pExpr->iColumn = x = (ynVar)i+1;
74414           break;
74415         }
74416       }
74417       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74418     }
74419     if( x>0 ){
74420       if( x>pParse->nzVar ){
74421         char **a;
74422         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74423         if( a==0 ) return;  /* Error reported through db->mallocFailed */
74424         pParse->azVar = a;
74425         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74426         pParse->nzVar = x;
74427       }
74428       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74429         sqlite3DbFree(db, pParse->azVar[x-1]);
74430         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
74431       }
74432     }
74433   } 
74434   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74435     sqlite3ErrorMsg(pParse, "too many SQL variables");
74436   }
74437 }
74438
74439 /*
74440 ** Recursively delete an expression tree.
74441 */
74442 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
74443   if( p==0 ) return;
74444   /* Sanity check: Assert that the IntValue is non-negative if it exists */
74445   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
74446   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74447     sqlite3ExprDelete(db, p->pLeft);
74448     sqlite3ExprDelete(db, p->pRight);
74449     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
74450       sqlite3DbFree(db, p->u.zToken);
74451     }
74452     if( ExprHasProperty(p, EP_xIsSelect) ){
74453       sqlite3SelectDelete(db, p->x.pSelect);
74454     }else{
74455       sqlite3ExprListDelete(db, p->x.pList);
74456     }
74457   }
74458   if( !ExprHasProperty(p, EP_Static) ){
74459     sqlite3DbFree(db, p);
74460   }
74461 }
74462
74463 /*
74464 ** Return the number of bytes allocated for the expression structure 
74465 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
74466 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
74467 */
74468 static int exprStructSize(Expr *p){
74469   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
74470   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
74471   return EXPR_FULLSIZE;
74472 }
74473
74474 /*
74475 ** The dupedExpr*Size() routines each return the number of bytes required
74476 ** to store a copy of an expression or expression tree.  They differ in
74477 ** how much of the tree is measured.
74478 **
74479 **     dupedExprStructSize()     Size of only the Expr structure 
74480 **     dupedExprNodeSize()       Size of Expr + space for token
74481 **     dupedExprSize()           Expr + token + subtree components
74482 **
74483 ***************************************************************************
74484 **
74485 ** The dupedExprStructSize() function returns two values OR-ed together:  
74486 ** (1) the space required for a copy of the Expr structure only and 
74487 ** (2) the EP_xxx flags that indicate what the structure size should be.
74488 ** The return values is always one of:
74489 **
74490 **      EXPR_FULLSIZE
74491 **      EXPR_REDUCEDSIZE   | EP_Reduced
74492 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
74493 **
74494 ** The size of the structure can be found by masking the return value
74495 ** of this routine with 0xfff.  The flags can be found by masking the
74496 ** return value with EP_Reduced|EP_TokenOnly.
74497 **
74498 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
74499 ** (unreduced) Expr objects as they or originally constructed by the parser.
74500 ** During expression analysis, extra information is computed and moved into
74501 ** later parts of teh Expr object and that extra information might get chopped
74502 ** off if the expression is reduced.  Note also that it does not work to
74503 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
74504 ** to reduce a pristine expression tree from the parser.  The implementation
74505 ** of dupedExprStructSize() contain multiple assert() statements that attempt
74506 ** to enforce this constraint.
74507 */
74508 static int dupedExprStructSize(Expr *p, int flags){
74509   int nSize;
74510   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
74511   if( 0==(flags&EXPRDUP_REDUCE) ){
74512     nSize = EXPR_FULLSIZE;
74513   }else{
74514     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
74515     assert( !ExprHasProperty(p, EP_FromJoin) ); 
74516     assert( (p->flags2 & EP2_MallocedToken)==0 );
74517     assert( (p->flags2 & EP2_Irreducible)==0 );
74518     if( p->pLeft || p->pRight || p->x.pList ){
74519       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
74520     }else{
74521       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
74522     }
74523   }
74524   return nSize;
74525 }
74526
74527 /*
74528 ** This function returns the space in bytes required to store the copy 
74529 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
74530 ** string is defined.)
74531 */
74532 static int dupedExprNodeSize(Expr *p, int flags){
74533   int nByte = dupedExprStructSize(p, flags) & 0xfff;
74534   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74535     nByte += sqlite3Strlen30(p->u.zToken)+1;
74536   }
74537   return ROUND8(nByte);
74538 }
74539
74540 /*
74541 ** Return the number of bytes required to create a duplicate of the 
74542 ** expression passed as the first argument. The second argument is a
74543 ** mask containing EXPRDUP_XXX flags.
74544 **
74545 ** The value returned includes space to create a copy of the Expr struct
74546 ** itself and the buffer referred to by Expr.u.zToken, if any.
74547 **
74548 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
74549 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
74550 ** and Expr.pRight variables (but not for any structures pointed to or 
74551 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
74552 */
74553 static int dupedExprSize(Expr *p, int flags){
74554   int nByte = 0;
74555   if( p ){
74556     nByte = dupedExprNodeSize(p, flags);
74557     if( flags&EXPRDUP_REDUCE ){
74558       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
74559     }
74560   }
74561   return nByte;
74562 }
74563
74564 /*
74565 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
74566 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
74567 ** to store the copy of expression p, the copies of p->u.zToken
74568 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
74569 ** if any. Before returning, *pzBuffer is set to the first byte passed the
74570 ** portion of the buffer copied into by this function.
74571 */
74572 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
74573   Expr *pNew = 0;                      /* Value to return */
74574   if( p ){
74575     const int isReduced = (flags&EXPRDUP_REDUCE);
74576     u8 *zAlloc;
74577     u32 staticFlag = 0;
74578
74579     assert( pzBuffer==0 || isReduced );
74580
74581     /* Figure out where to write the new Expr structure. */
74582     if( pzBuffer ){
74583       zAlloc = *pzBuffer;
74584       staticFlag = EP_Static;
74585     }else{
74586       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
74587     }
74588     pNew = (Expr *)zAlloc;
74589
74590     if( pNew ){
74591       /* Set nNewSize to the size allocated for the structure pointed to
74592       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
74593       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
74594       ** by the copy of the p->u.zToken string (if any).
74595       */
74596       const unsigned nStructSize = dupedExprStructSize(p, flags);
74597       const int nNewSize = nStructSize & 0xfff;
74598       int nToken;
74599       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74600         nToken = sqlite3Strlen30(p->u.zToken) + 1;
74601       }else{
74602         nToken = 0;
74603       }
74604       if( isReduced ){
74605         assert( ExprHasProperty(p, EP_Reduced)==0 );
74606         memcpy(zAlloc, p, nNewSize);
74607       }else{
74608         int nSize = exprStructSize(p);
74609         memcpy(zAlloc, p, nSize);
74610         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
74611       }
74612
74613       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
74614       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
74615       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
74616       pNew->flags |= staticFlag;
74617
74618       /* Copy the p->u.zToken string, if any. */
74619       if( nToken ){
74620         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
74621         memcpy(zToken, p->u.zToken, nToken);
74622       }
74623
74624       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
74625         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
74626         if( ExprHasProperty(p, EP_xIsSelect) ){
74627           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
74628         }else{
74629           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
74630         }
74631       }
74632
74633       /* Fill in pNew->pLeft and pNew->pRight. */
74634       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
74635         zAlloc += dupedExprNodeSize(p, flags);
74636         if( ExprHasProperty(pNew, EP_Reduced) ){
74637           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
74638           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
74639         }
74640         if( pzBuffer ){
74641           *pzBuffer = zAlloc;
74642         }
74643       }else{
74644         pNew->flags2 = 0;
74645         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74646           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
74647           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
74648         }
74649       }
74650
74651     }
74652   }
74653   return pNew;
74654 }
74655
74656 /*
74657 ** The following group of routines make deep copies of expressions,
74658 ** expression lists, ID lists, and select statements.  The copies can
74659 ** be deleted (by being passed to their respective ...Delete() routines)
74660 ** without effecting the originals.
74661 **
74662 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
74663 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
74664 ** by subsequent calls to sqlite*ListAppend() routines.
74665 **
74666 ** Any tables that the SrcList might point to are not duplicated.
74667 **
74668 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
74669 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
74670 ** truncated version of the usual Expr structure that will be stored as
74671 ** part of the in-memory representation of the database schema.
74672 */
74673 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
74674   return exprDup(db, p, flags, 0);
74675 }
74676 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
74677   ExprList *pNew;
74678   struct ExprList_item *pItem, *pOldItem;
74679   int i;
74680   if( p==0 ) return 0;
74681   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74682   if( pNew==0 ) return 0;
74683   pNew->iECursor = 0;
74684   pNew->nExpr = i = p->nExpr;
74685   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
74686   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
74687   if( pItem==0 ){
74688     sqlite3DbFree(db, pNew);
74689     return 0;
74690   } 
74691   pOldItem = p->a;
74692   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
74693     Expr *pOldExpr = pOldItem->pExpr;
74694     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
74695     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74696     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
74697     pItem->sortOrder = pOldItem->sortOrder;
74698     pItem->done = 0;
74699     pItem->iOrderByCol = pOldItem->iOrderByCol;
74700     pItem->iAlias = pOldItem->iAlias;
74701   }
74702   return pNew;
74703 }
74704
74705 /*
74706 ** If cursors, triggers, views and subqueries are all omitted from
74707 ** the build, then none of the following routines, except for 
74708 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
74709 ** called with a NULL argument.
74710 */
74711 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
74712  || !defined(SQLITE_OMIT_SUBQUERY)
74713 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
74714   SrcList *pNew;
74715   int i;
74716   int nByte;
74717   if( p==0 ) return 0;
74718   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
74719   pNew = sqlite3DbMallocRaw(db, nByte );
74720   if( pNew==0 ) return 0;
74721   pNew->nSrc = pNew->nAlloc = p->nSrc;
74722   for(i=0; i<p->nSrc; i++){
74723     struct SrcList_item *pNewItem = &pNew->a[i];
74724     struct SrcList_item *pOldItem = &p->a[i];
74725     Table *pTab;
74726     pNewItem->pSchema = pOldItem->pSchema;
74727     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
74728     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74729     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
74730     pNewItem->jointype = pOldItem->jointype;
74731     pNewItem->iCursor = pOldItem->iCursor;
74732     pNewItem->addrFillSub = pOldItem->addrFillSub;
74733     pNewItem->regReturn = pOldItem->regReturn;
74734     pNewItem->isCorrelated = pOldItem->isCorrelated;
74735     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
74736     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
74737     pNewItem->notIndexed = pOldItem->notIndexed;
74738     pNewItem->pIndex = pOldItem->pIndex;
74739     pTab = pNewItem->pTab = pOldItem->pTab;
74740     if( pTab ){
74741       pTab->nRef++;
74742     }
74743     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
74744     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
74745     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
74746     pNewItem->colUsed = pOldItem->colUsed;
74747   }
74748   return pNew;
74749 }
74750 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
74751   IdList *pNew;
74752   int i;
74753   if( p==0 ) return 0;
74754   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74755   if( pNew==0 ) return 0;
74756   pNew->nId = p->nId;
74757   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
74758   if( pNew->a==0 ){
74759     sqlite3DbFree(db, pNew);
74760     return 0;
74761   }
74762   /* Note that because the size of the allocation for p->a[] is not
74763   ** necessarily a power of two, sqlite3IdListAppend() may not be called
74764   ** on the duplicate created by this function. */
74765   for(i=0; i<p->nId; i++){
74766     struct IdList_item *pNewItem = &pNew->a[i];
74767     struct IdList_item *pOldItem = &p->a[i];
74768     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74769     pNewItem->idx = pOldItem->idx;
74770   }
74771   return pNew;
74772 }
74773 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74774   Select *pNew, *pPrior;
74775   if( p==0 ) return 0;
74776   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
74777   if( pNew==0 ) return 0;
74778   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
74779   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
74780   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
74781   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
74782   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
74783   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
74784   pNew->op = p->op;
74785   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
74786   if( pPrior ) pPrior->pNext = pNew;
74787   pNew->pNext = 0;
74788   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
74789   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
74790   pNew->iLimit = 0;
74791   pNew->iOffset = 0;
74792   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
74793   pNew->pRightmost = 0;
74794   pNew->addrOpenEphm[0] = -1;
74795   pNew->addrOpenEphm[1] = -1;
74796   pNew->addrOpenEphm[2] = -1;
74797   return pNew;
74798 }
74799 #else
74800 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74801   assert( p==0 );
74802   return 0;
74803 }
74804 #endif
74805
74806
74807 /*
74808 ** Add a new element to the end of an expression list.  If pList is
74809 ** initially NULL, then create a new expression list.
74810 **
74811 ** If a memory allocation error occurs, the entire list is freed and
74812 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
74813 ** that the new entry was successfully appended.
74814 */
74815 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
74816   Parse *pParse,          /* Parsing context */
74817   ExprList *pList,        /* List to which to append. Might be NULL */
74818   Expr *pExpr             /* Expression to be appended. Might be NULL */
74819 ){
74820   sqlite3 *db = pParse->db;
74821   if( pList==0 ){
74822     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
74823     if( pList==0 ){
74824       goto no_mem;
74825     }
74826     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
74827     if( pList->a==0 ) goto no_mem;
74828   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
74829     struct ExprList_item *a;
74830     assert( pList->nExpr>0 );
74831     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
74832     if( a==0 ){
74833       goto no_mem;
74834     }
74835     pList->a = a;
74836   }
74837   assert( pList->a!=0 );
74838   if( 1 ){
74839     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
74840     memset(pItem, 0, sizeof(*pItem));
74841     pItem->pExpr = pExpr;
74842   }
74843   return pList;
74844
74845 no_mem:     
74846   /* Avoid leaking memory if malloc has failed. */
74847   sqlite3ExprDelete(db, pExpr);
74848   sqlite3ExprListDelete(db, pList);
74849   return 0;
74850 }
74851
74852 /*
74853 ** Set the ExprList.a[].zName element of the most recently added item
74854 ** on the expression list.
74855 **
74856 ** pList might be NULL following an OOM error.  But pName should never be
74857 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74858 ** is set.
74859 */
74860 SQLITE_PRIVATE void sqlite3ExprListSetName(
74861   Parse *pParse,          /* Parsing context */
74862   ExprList *pList,        /* List to which to add the span. */
74863   Token *pName,           /* Name to be added */
74864   int dequote             /* True to cause the name to be dequoted */
74865 ){
74866   assert( pList!=0 || pParse->db->mallocFailed!=0 );
74867   if( pList ){
74868     struct ExprList_item *pItem;
74869     assert( pList->nExpr>0 );
74870     pItem = &pList->a[pList->nExpr-1];
74871     assert( pItem->zName==0 );
74872     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
74873     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
74874   }
74875 }
74876
74877 /*
74878 ** Set the ExprList.a[].zSpan element of the most recently added item
74879 ** on the expression list.
74880 **
74881 ** pList might be NULL following an OOM error.  But pSpan should never be
74882 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74883 ** is set.
74884 */
74885 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
74886   Parse *pParse,          /* Parsing context */
74887   ExprList *pList,        /* List to which to add the span. */
74888   ExprSpan *pSpan         /* The span to be added */
74889 ){
74890   sqlite3 *db = pParse->db;
74891   assert( pList!=0 || db->mallocFailed!=0 );
74892   if( pList ){
74893     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
74894     assert( pList->nExpr>0 );
74895     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
74896     sqlite3DbFree(db, pItem->zSpan);
74897     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
74898                                     (int)(pSpan->zEnd - pSpan->zStart));
74899   }
74900 }
74901
74902 /*
74903 ** If the expression list pEList contains more than iLimit elements,
74904 ** leave an error message in pParse.
74905 */
74906 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
74907   Parse *pParse,
74908   ExprList *pEList,
74909   const char *zObject
74910 ){
74911   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
74912   testcase( pEList && pEList->nExpr==mx );
74913   testcase( pEList && pEList->nExpr==mx+1 );
74914   if( pEList && pEList->nExpr>mx ){
74915     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
74916   }
74917 }
74918
74919 /*
74920 ** Delete an entire expression list.
74921 */
74922 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
74923   int i;
74924   struct ExprList_item *pItem;
74925   if( pList==0 ) return;
74926   assert( pList->a!=0 || pList->nExpr==0 );
74927   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74928     sqlite3ExprDelete(db, pItem->pExpr);
74929     sqlite3DbFree(db, pItem->zName);
74930     sqlite3DbFree(db, pItem->zSpan);
74931   }
74932   sqlite3DbFree(db, pList->a);
74933   sqlite3DbFree(db, pList);
74934 }
74935
74936 /*
74937 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
74938 ** to an integer.  These routines are checking an expression to see
74939 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
74940 ** not constant.
74941 **
74942 ** These callback routines are used to implement the following:
74943 **
74944 **     sqlite3ExprIsConstant()
74945 **     sqlite3ExprIsConstantNotJoin()
74946 **     sqlite3ExprIsConstantOrFunction()
74947 **
74948 */
74949 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
74950
74951   /* If pWalker->u.i is 3 then any term of the expression that comes from
74952   ** the ON or USING clauses of a join disqualifies the expression
74953   ** from being considered constant. */
74954   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
74955     pWalker->u.i = 0;
74956     return WRC_Abort;
74957   }
74958
74959   switch( pExpr->op ){
74960     /* Consider functions to be constant if all their arguments are constant
74961     ** and pWalker->u.i==2 */
74962     case TK_FUNCTION:
74963       if( pWalker->u.i==2 ) return 0;
74964       /* Fall through */
74965     case TK_ID:
74966     case TK_COLUMN:
74967     case TK_AGG_FUNCTION:
74968     case TK_AGG_COLUMN:
74969       testcase( pExpr->op==TK_ID );
74970       testcase( pExpr->op==TK_COLUMN );
74971       testcase( pExpr->op==TK_AGG_FUNCTION );
74972       testcase( pExpr->op==TK_AGG_COLUMN );
74973       pWalker->u.i = 0;
74974       return WRC_Abort;
74975     default:
74976       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
74977       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
74978       return WRC_Continue;
74979   }
74980 }
74981 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
74982   UNUSED_PARAMETER(NotUsed);
74983   pWalker->u.i = 0;
74984   return WRC_Abort;
74985 }
74986 static int exprIsConst(Expr *p, int initFlag){
74987   Walker w;
74988   w.u.i = initFlag;
74989   w.xExprCallback = exprNodeIsConstant;
74990   w.xSelectCallback = selectNodeIsConstant;
74991   sqlite3WalkExpr(&w, p);
74992   return w.u.i;
74993 }
74994
74995 /*
74996 ** Walk an expression tree.  Return 1 if the expression is constant
74997 ** and 0 if it involves variables or function calls.
74998 **
74999 ** For the purposes of this function, a double-quoted string (ex: "abc")
75000 ** is considered a variable but a single-quoted string (ex: 'abc') is
75001 ** a constant.
75002 */
75003 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
75004   return exprIsConst(p, 1);
75005 }
75006
75007 /*
75008 ** Walk an expression tree.  Return 1 if the expression is constant
75009 ** that does no originate from the ON or USING clauses of a join.
75010 ** Return 0 if it involves variables or function calls or terms from
75011 ** an ON or USING clause.
75012 */
75013 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
75014   return exprIsConst(p, 3);
75015 }
75016
75017 /*
75018 ** Walk an expression tree.  Return 1 if the expression is constant
75019 ** or a function call with constant arguments.  Return and 0 if there
75020 ** are any variables.
75021 **
75022 ** For the purposes of this function, a double-quoted string (ex: "abc")
75023 ** is considered a variable but a single-quoted string (ex: 'abc') is
75024 ** a constant.
75025 */
75026 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
75027   return exprIsConst(p, 2);
75028 }
75029
75030 /*
75031 ** If the expression p codes a constant integer that is small enough
75032 ** to fit in a 32-bit integer, return 1 and put the value of the integer
75033 ** in *pValue.  If the expression is not an integer or if it is too big
75034 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75035 */
75036 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
75037   int rc = 0;
75038
75039   /* If an expression is an integer literal that fits in a signed 32-bit
75040   ** integer, then the EP_IntValue flag will have already been set */
75041   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75042            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
75043
75044   if( p->flags & EP_IntValue ){
75045     *pValue = p->u.iValue;
75046     return 1;
75047   }
75048   switch( p->op ){
75049     case TK_UPLUS: {
75050       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
75051       break;
75052     }
75053     case TK_UMINUS: {
75054       int v;
75055       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
75056         *pValue = -v;
75057         rc = 1;
75058       }
75059       break;
75060     }
75061     default: break;
75062   }
75063   return rc;
75064 }
75065
75066 /*
75067 ** Return FALSE if there is no chance that the expression can be NULL.
75068 **
75069 ** If the expression might be NULL or if the expression is too complex
75070 ** to tell return TRUE.  
75071 **
75072 ** This routine is used as an optimization, to skip OP_IsNull opcodes
75073 ** when we know that a value cannot be NULL.  Hence, a false positive
75074 ** (returning TRUE when in fact the expression can never be NULL) might
75075 ** be a small performance hit but is otherwise harmless.  On the other
75076 ** hand, a false negative (returning FALSE when the result could be NULL)
75077 ** will likely result in an incorrect answer.  So when in doubt, return
75078 ** TRUE.
75079 */
75080 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
75081   u8 op;
75082   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75083   op = p->op;
75084   if( op==TK_REGISTER ) op = p->op2;
75085   switch( op ){
75086     case TK_INTEGER:
75087     case TK_STRING:
75088     case TK_FLOAT:
75089     case TK_BLOB:
75090       return 0;
75091     default:
75092       return 1;
75093   }
75094 }
75095
75096 /*
75097 ** Generate an OP_IsNull instruction that tests register iReg and jumps
75098 ** to location iDest if the value in iReg is NULL.  The value in iReg 
75099 ** was computed by pExpr.  If we can look at pExpr at compile-time and
75100 ** determine that it can never generate a NULL, then the OP_IsNull operation
75101 ** can be omitted.
75102 */
75103 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
75104   Vdbe *v,            /* The VDBE under construction */
75105   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75106   int iReg,           /* Test the value in this register for NULL */
75107   int iDest           /* Jump here if the value is null */
75108 ){
75109   if( sqlite3ExprCanBeNull(pExpr) ){
75110     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75111   }
75112 }
75113
75114 /*
75115 ** Return TRUE if the given expression is a constant which would be
75116 ** unchanged by OP_Affinity with the affinity given in the second
75117 ** argument.
75118 **
75119 ** This routine is used to determine if the OP_Affinity operation
75120 ** can be omitted.  When in doubt return FALSE.  A false negative
75121 ** is harmless.  A false positive, however, can result in the wrong
75122 ** answer.
75123 */
75124 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75125   u8 op;
75126   if( aff==SQLITE_AFF_NONE ) return 1;
75127   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75128   op = p->op;
75129   if( op==TK_REGISTER ) op = p->op2;
75130   switch( op ){
75131     case TK_INTEGER: {
75132       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
75133     }
75134     case TK_FLOAT: {
75135       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
75136     }
75137     case TK_STRING: {
75138       return aff==SQLITE_AFF_TEXT;
75139     }
75140     case TK_BLOB: {
75141       return 1;
75142     }
75143     case TK_COLUMN: {
75144       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75145       return p->iColumn<0
75146           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
75147     }
75148     default: {
75149       return 0;
75150     }
75151   }
75152 }
75153
75154 /*
75155 ** Return TRUE if the given string is a row-id column name.
75156 */
75157 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
75158   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
75159   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
75160   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
75161   return 0;
75162 }
75163
75164 /*
75165 ** Return true if we are able to the IN operator optimization on a
75166 ** query of the form
75167 **
75168 **       x IN (SELECT ...)
75169 **
75170 ** Where the SELECT... clause is as specified by the parameter to this
75171 ** routine.
75172 **
75173 ** The Select object passed in has already been preprocessed and no
75174 ** errors have been found.
75175 */
75176 #ifndef SQLITE_OMIT_SUBQUERY
75177 static int isCandidateForInOpt(Select *p){
75178   SrcList *pSrc;
75179   ExprList *pEList;
75180   Table *pTab;
75181   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75182   if( p->pPrior ) return 0;              /* Not a compound SELECT */
75183   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75184     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75185     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75186     return 0; /* No DISTINCT keyword and no aggregate functions */
75187   }
75188   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75189   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75190   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75191   if( p->pWhere ) return 0;              /* Has no WHERE clause */
75192   pSrc = p->pSrc;
75193   assert( pSrc!=0 );
75194   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75195   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75196   pTab = pSrc->a[0].pTab;
75197   if( NEVER(pTab==0) ) return 0;
75198   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75199   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75200   pEList = p->pEList;
75201   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75202   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75203   return 1;
75204 }
75205 #endif /* SQLITE_OMIT_SUBQUERY */
75206
75207 /*
75208 ** Code an OP_Once instruction and allocate space for its flag. Return the 
75209 ** address of the new instruction.
75210 */
75211 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
75212   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
75213   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
75214 }
75215
75216 /*
75217 ** This function is used by the implementation of the IN (...) operator.
75218 ** The pX parameter is the expression on the RHS of the IN operator, which
75219 ** might be either a list of expressions or a subquery.
75220 **
75221 ** The job of this routine is to find or create a b-tree object that can
75222 ** be used either to test for membership in the RHS set or to iterate through
75223 ** all members of the RHS set, skipping duplicates.
75224 **
75225 ** A cursor is opened on the b-tree object that the RHS of the IN operator
75226 ** and pX->iTable is set to the index of that cursor.
75227 **
75228 ** The returned value of this function indicates the b-tree type, as follows:
75229 **
75230 **   IN_INDEX_ROWID - The cursor was opened on a database table.
75231 **   IN_INDEX_INDEX - The cursor was opened on a database index.
75232 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
75233 **                    populated epheremal table.
75234 **
75235 ** An existing b-tree might be used if the RHS expression pX is a simple
75236 ** subquery such as:
75237 **
75238 **     SELECT <column> FROM <table>
75239 **
75240 ** If the RHS of the IN operator is a list or a more complex subquery, then
75241 ** an ephemeral table might need to be generated from the RHS and then
75242 ** pX->iTable made to point to the ephermeral table instead of an
75243 ** existing table.  
75244 **
75245 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75246 ** through the set members, skipping any duplicates. In this case an
75247 ** epheremal table must be used unless the selected <column> is guaranteed
75248 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
75249 ** has a UNIQUE constraint or UNIQUE index.
75250 **
75251 ** If the prNotFound parameter is not 0, then the b-tree will be used 
75252 ** for fast set membership tests. In this case an epheremal table must 
75253 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
75254 ** be found with <column> as its left-most column.
75255 **
75256 ** When the b-tree is being used for membership tests, the calling function
75257 ** needs to know whether or not the structure contains an SQL NULL 
75258 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75259 ** If there is any chance that the (...) might contain a NULL value at
75260 ** runtime, then a register is allocated and the register number written
75261 ** to *prNotFound. If there is no chance that the (...) contains a
75262 ** NULL value, then *prNotFound is left unchanged.
75263 **
75264 ** If a register is allocated and its location stored in *prNotFound, then
75265 ** its initial value is NULL.  If the (...) does not remain constant
75266 ** for the duration of the query (i.e. the SELECT within the (...)
75267 ** is a correlated subquery) then the value of the allocated register is
75268 ** reset to NULL each time the subquery is rerun. This allows the
75269 ** caller to use vdbe code equivalent to the following:
75270 **
75271 **   if( register==NULL ){
75272 **     has_null = <test if data structure contains null>
75273 **     register = 1
75274 **   }
75275 **
75276 ** in order to avoid running the <test if data structure contains null>
75277 ** test more often than is necessary.
75278 */
75279 #ifndef SQLITE_OMIT_SUBQUERY
75280 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75281   Select *p;                            /* SELECT to the right of IN operator */
75282   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75283   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75284   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75285   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
75286
75287   assert( pX->op==TK_IN );
75288
75289   /* Check to see if an existing table or index can be used to
75290   ** satisfy the query.  This is preferable to generating a new 
75291   ** ephemeral table.
75292   */
75293   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75294   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75295     sqlite3 *db = pParse->db;              /* Database connection */
75296     Table *pTab;                           /* Table <table>. */
75297     Expr *pExpr;                           /* Expression <column> */
75298     int iCol;                              /* Index of column <column> */
75299     int iDb;                               /* Database idx for pTab */
75300
75301     assert( p );                        /* Because of isCandidateForInOpt(p) */
75302     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75303     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75304     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75305     pTab = p->pSrc->a[0].pTab;
75306     pExpr = p->pEList->a[0].pExpr;
75307     iCol = pExpr->iColumn;
75308    
75309     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75310     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75311     sqlite3CodeVerifySchema(pParse, iDb);
75312     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75313
75314     /* This function is only called from two places. In both cases the vdbe
75315     ** has already been allocated. So assume sqlite3GetVdbe() is always
75316     ** successful here.
75317     */
75318     assert(v);
75319     if( iCol<0 ){
75320       int iAddr;
75321
75322       iAddr = sqlite3CodeOnce(pParse);
75323
75324       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75325       eType = IN_INDEX_ROWID;
75326
75327       sqlite3VdbeJumpHere(v, iAddr);
75328     }else{
75329       Index *pIdx;                         /* Iterator variable */
75330
75331       /* The collation sequence used by the comparison. If an index is to
75332       ** be used in place of a temp-table, it must be ordered according
75333       ** to this collation sequence.  */
75334       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75335
75336       /* Check that the affinity that will be used to perform the 
75337       ** comparison is the same as the affinity of the column. If
75338       ** it is not, it is not possible to use any index.
75339       */
75340       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
75341
75342       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75343         if( (pIdx->aiColumn[0]==iCol)
75344          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75345          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75346         ){
75347           int iAddr;
75348           char *pKey;
75349   
75350           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
75351           iAddr = sqlite3CodeOnce(pParse);
75352   
75353           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75354                                pKey,P4_KEYINFO_HANDOFF);
75355           VdbeComment((v, "%s", pIdx->zName));
75356           eType = IN_INDEX_INDEX;
75357
75358           sqlite3VdbeJumpHere(v, iAddr);
75359           if( prNotFound && !pTab->aCol[iCol].notNull ){
75360             *prNotFound = ++pParse->nMem;
75361             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75362           }
75363         }
75364       }
75365     }
75366   }
75367
75368   if( eType==0 ){
75369     /* Could not found an existing table or index to use as the RHS b-tree.
75370     ** We will have to generate an ephemeral table to do the job.
75371     */
75372     double savedNQueryLoop = pParse->nQueryLoop;
75373     int rMayHaveNull = 0;
75374     eType = IN_INDEX_EPH;
75375     if( prNotFound ){
75376       *prNotFound = rMayHaveNull = ++pParse->nMem;
75377       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75378     }else{
75379       testcase( pParse->nQueryLoop>(double)1 );
75380       pParse->nQueryLoop = (double)1;
75381       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75382         eType = IN_INDEX_ROWID;
75383       }
75384     }
75385     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75386     pParse->nQueryLoop = savedNQueryLoop;
75387   }else{
75388     pX->iTable = iTab;
75389   }
75390   return eType;
75391 }
75392 #endif
75393
75394 /*
75395 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75396 ** or IN operators.  Examples:
75397 **
75398 **     (SELECT a FROM b)          -- subquery
75399 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75400 **     x IN (4,5,11)              -- IN operator with list on right-hand side
75401 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75402 **
75403 ** The pExpr parameter describes the expression that contains the IN
75404 ** operator or subquery.
75405 **
75406 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75407 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75408 ** to some integer key column of a table B-Tree. In this case, use an
75409 ** intkey B-Tree to store the set of IN(...) values instead of the usual
75410 ** (slower) variable length keys B-Tree.
75411 **
75412 ** If rMayHaveNull is non-zero, that means that the operation is an IN
75413 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75414 ** Furthermore, the IN is in a WHERE clause and that we really want
75415 ** to iterate over the RHS of the IN operator in order to quickly locate
75416 ** all corresponding LHS elements.  All this routine does is initialize
75417 ** the register given by rMayHaveNull to NULL.  Calling routines will take
75418 ** care of changing this register value to non-NULL if the RHS is NULL-free.
75419 **
75420 ** If rMayHaveNull is zero, that means that the subquery is being used
75421 ** for membership testing only.  There is no need to initialize any
75422 ** registers to indicate the presense or absence of NULLs on the RHS.
75423 **
75424 ** For a SELECT or EXISTS operator, return the register that holds the
75425 ** result.  For IN operators or if an error occurs, the return value is 0.
75426 */
75427 #ifndef SQLITE_OMIT_SUBQUERY
75428 SQLITE_PRIVATE int sqlite3CodeSubselect(
75429   Parse *pParse,          /* Parsing context */
75430   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75431   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75432   int isRowid             /* If true, LHS of IN operator is a rowid */
75433 ){
75434   int testAddr = -1;                      /* One-time test address */
75435   int rReg = 0;                           /* Register storing resulting */
75436   Vdbe *v = sqlite3GetVdbe(pParse);
75437   if( NEVER(v==0) ) return 0;
75438   sqlite3ExprCachePush(pParse);
75439
75440   /* This code must be run in its entirety every time it is encountered
75441   ** if any of the following is true:
75442   **
75443   **    *  The right-hand side is a correlated subquery
75444   **    *  The right-hand side is an expression list containing variables
75445   **    *  We are inside a trigger
75446   **
75447   ** If all of the above are false, then we can run this code just once
75448   ** save the results, and reuse the same result on subsequent invocations.
75449   */
75450   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
75451     testAddr = sqlite3CodeOnce(pParse);
75452   }
75453
75454 #ifndef SQLITE_OMIT_EXPLAIN
75455   if( pParse->explain==2 ){
75456     char *zMsg = sqlite3MPrintf(
75457         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
75458         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
75459     );
75460     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
75461   }
75462 #endif
75463
75464   switch( pExpr->op ){
75465     case TK_IN: {
75466       char affinity;              /* Affinity of the LHS of the IN */
75467       KeyInfo keyInfo;            /* Keyinfo for the generated table */
75468       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
75469       int addr;                   /* Address of OP_OpenEphemeral instruction */
75470       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
75471
75472       if( rMayHaveNull ){
75473         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
75474       }
75475
75476       affinity = sqlite3ExprAffinity(pLeft);
75477
75478       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
75479       ** expression it is handled the same way.  An ephemeral table is 
75480       ** filled with single-field index keys representing the results
75481       ** from the SELECT or the <exprlist>.
75482       **
75483       ** If the 'x' expression is a column value, or the SELECT...
75484       ** statement returns a column value, then the affinity of that
75485       ** column is used to build the index keys. If both 'x' and the
75486       ** SELECT... statement are columns, then numeric affinity is used
75487       ** if either column has NUMERIC or INTEGER affinity. If neither
75488       ** 'x' nor the SELECT... statement are columns, then numeric affinity
75489       ** is used.
75490       */
75491       pExpr->iTable = pParse->nTab++;
75492       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
75493       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
75494       memset(&keyInfo, 0, sizeof(keyInfo));
75495       keyInfo.nField = 1;
75496       keyInfo.aSortOrder = &sortOrder;
75497
75498       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75499         /* Case 1:     expr IN (SELECT ...)
75500         **
75501         ** Generate code to write the results of the select into the temporary
75502         ** table allocated and opened above.
75503         */
75504         SelectDest dest;
75505         ExprList *pEList;
75506
75507         assert( !isRowid );
75508         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
75509         dest.affSdst = (u8)affinity;
75510         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
75511         pExpr->x.pSelect->iLimit = 0;
75512         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
75513           return 0;
75514         }
75515         pEList = pExpr->x.pSelect->pEList;
75516         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
75517           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
75518               pEList->a[0].pExpr);
75519         }
75520       }else if( ALWAYS(pExpr->x.pList!=0) ){
75521         /* Case 2:     expr IN (exprlist)
75522         **
75523         ** For each expression, build an index key from the evaluation and
75524         ** store it in the temporary table. If <expr> is a column, then use
75525         ** that columns affinity when building index keys. If <expr> is not
75526         ** a column, use numeric affinity.
75527         */
75528         int i;
75529         ExprList *pList = pExpr->x.pList;
75530         struct ExprList_item *pItem;
75531         int r1, r2, r3;
75532
75533         if( !affinity ){
75534           affinity = SQLITE_AFF_NONE;
75535         }
75536         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
75537         keyInfo.aSortOrder = &sortOrder;
75538
75539         /* Loop through each expression in <exprlist>. */
75540         r1 = sqlite3GetTempReg(pParse);
75541         r2 = sqlite3GetTempReg(pParse);
75542         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
75543         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
75544           Expr *pE2 = pItem->pExpr;
75545           int iValToIns;
75546
75547           /* If the expression is not constant then we will need to
75548           ** disable the test that was generated above that makes sure
75549           ** this code only executes once.  Because for a non-constant
75550           ** expression we need to rerun this code each time.
75551           */
75552           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
75553             sqlite3VdbeChangeToNoop(v, testAddr);
75554             testAddr = -1;
75555           }
75556
75557           /* Evaluate the expression and insert it into the temp table */
75558           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
75559             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
75560           }else{
75561             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
75562             if( isRowid ){
75563               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
75564                                 sqlite3VdbeCurrentAddr(v)+2);
75565               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
75566             }else{
75567               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
75568               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
75569               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
75570             }
75571           }
75572         }
75573         sqlite3ReleaseTempReg(pParse, r1);
75574         sqlite3ReleaseTempReg(pParse, r2);
75575       }
75576       if( !isRowid ){
75577         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
75578       }
75579       break;
75580     }
75581
75582     case TK_EXISTS:
75583     case TK_SELECT:
75584     default: {
75585       /* If this has to be a scalar SELECT.  Generate code to put the
75586       ** value of this select in a memory cell and record the number
75587       ** of the memory cell in iColumn.  If this is an EXISTS, write
75588       ** an integer 0 (not exists) or 1 (exists) into a memory cell
75589       ** and record that memory cell in iColumn.
75590       */
75591       Select *pSel;                         /* SELECT statement to encode */
75592       SelectDest dest;                      /* How to deal with SELECt result */
75593
75594       testcase( pExpr->op==TK_EXISTS );
75595       testcase( pExpr->op==TK_SELECT );
75596       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
75597
75598       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
75599       pSel = pExpr->x.pSelect;
75600       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
75601       if( pExpr->op==TK_SELECT ){
75602         dest.eDest = SRT_Mem;
75603         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
75604         VdbeComment((v, "Init subquery result"));
75605       }else{
75606         dest.eDest = SRT_Exists;
75607         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
75608         VdbeComment((v, "Init EXISTS result"));
75609       }
75610       sqlite3ExprDelete(pParse->db, pSel->pLimit);
75611       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
75612                                   &sqlite3IntTokens[1]);
75613       pSel->iLimit = 0;
75614       if( sqlite3Select(pParse, pSel, &dest) ){
75615         return 0;
75616       }
75617       rReg = dest.iSDParm;
75618       ExprSetIrreducible(pExpr);
75619       break;
75620     }
75621   }
75622
75623   if( testAddr>=0 ){
75624     sqlite3VdbeJumpHere(v, testAddr);
75625   }
75626   sqlite3ExprCachePop(pParse, 1);
75627
75628   return rReg;
75629 }
75630 #endif /* SQLITE_OMIT_SUBQUERY */
75631
75632 #ifndef SQLITE_OMIT_SUBQUERY
75633 /*
75634 ** Generate code for an IN expression.
75635 **
75636 **      x IN (SELECT ...)
75637 **      x IN (value, value, ...)
75638 **
75639 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
75640 ** is an array of zero or more values.  The expression is true if the LHS is
75641 ** contained within the RHS.  The value of the expression is unknown (NULL)
75642 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
75643 ** RHS contains one or more NULL values.
75644 **
75645 ** This routine generates code will jump to destIfFalse if the LHS is not 
75646 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
75647 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
75648 ** within the RHS then fall through.
75649 */
75650 static void sqlite3ExprCodeIN(
75651   Parse *pParse,        /* Parsing and code generating context */
75652   Expr *pExpr,          /* The IN expression */
75653   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
75654   int destIfNull        /* Jump here if the results are unknown due to NULLs */
75655 ){
75656   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
75657   char affinity;        /* Comparison affinity to use */
75658   int eType;            /* Type of the RHS */
75659   int r1;               /* Temporary use register */
75660   Vdbe *v;              /* Statement under construction */
75661
75662   /* Compute the RHS.   After this step, the table with cursor
75663   ** pExpr->iTable will contains the values that make up the RHS.
75664   */
75665   v = pParse->pVdbe;
75666   assert( v!=0 );       /* OOM detected prior to this routine */
75667   VdbeNoopComment((v, "begin IN expr"));
75668   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
75669
75670   /* Figure out the affinity to use to create a key from the results
75671   ** of the expression. affinityStr stores a static string suitable for
75672   ** P4 of OP_MakeRecord.
75673   */
75674   affinity = comparisonAffinity(pExpr);
75675
75676   /* Code the LHS, the <expr> from "<expr> IN (...)".
75677   */
75678   sqlite3ExprCachePush(pParse);
75679   r1 = sqlite3GetTempReg(pParse);
75680   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
75681
75682   /* If the LHS is NULL, then the result is either false or NULL depending
75683   ** on whether the RHS is empty or not, respectively.
75684   */
75685   if( destIfNull==destIfFalse ){
75686     /* Shortcut for the common case where the false and NULL outcomes are
75687     ** the same. */
75688     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
75689   }else{
75690     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
75691     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
75692     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
75693     sqlite3VdbeJumpHere(v, addr1);
75694   }
75695
75696   if( eType==IN_INDEX_ROWID ){
75697     /* In this case, the RHS is the ROWID of table b-tree
75698     */
75699     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
75700     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
75701   }else{
75702     /* In this case, the RHS is an index b-tree.
75703     */
75704     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
75705
75706     /* If the set membership test fails, then the result of the 
75707     ** "x IN (...)" expression must be either 0 or NULL. If the set
75708     ** contains no NULL values, then the result is 0. If the set 
75709     ** contains one or more NULL values, then the result of the
75710     ** expression is also NULL.
75711     */
75712     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
75713       /* This branch runs if it is known at compile time that the RHS
75714       ** cannot contain NULL values. This happens as the result
75715       ** of a "NOT NULL" constraint in the database schema.
75716       **
75717       ** Also run this branch if NULL is equivalent to FALSE
75718       ** for this particular IN operator.
75719       */
75720       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
75721
75722     }else{
75723       /* In this branch, the RHS of the IN might contain a NULL and
75724       ** the presence of a NULL on the RHS makes a difference in the
75725       ** outcome.
75726       */
75727       int j1, j2, j3;
75728
75729       /* First check to see if the LHS is contained in the RHS.  If so,
75730       ** then the presence of NULLs in the RHS does not matter, so jump
75731       ** over all of the code that follows.
75732       */
75733       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
75734
75735       /* Here we begin generating code that runs if the LHS is not
75736       ** contained within the RHS.  Generate additional code that
75737       ** tests the RHS for NULLs.  If the RHS contains a NULL then
75738       ** jump to destIfNull.  If there are no NULLs in the RHS then
75739       ** jump to destIfFalse.
75740       */
75741       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
75742       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
75743       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
75744       sqlite3VdbeJumpHere(v, j3);
75745       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
75746       sqlite3VdbeJumpHere(v, j2);
75747
75748       /* Jump to the appropriate target depending on whether or not
75749       ** the RHS contains a NULL
75750       */
75751       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
75752       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
75753
75754       /* The OP_Found at the top of this branch jumps here when true, 
75755       ** causing the overall IN expression evaluation to fall through.
75756       */
75757       sqlite3VdbeJumpHere(v, j1);
75758     }
75759   }
75760   sqlite3ReleaseTempReg(pParse, r1);
75761   sqlite3ExprCachePop(pParse, 1);
75762   VdbeComment((v, "end IN expr"));
75763 }
75764 #endif /* SQLITE_OMIT_SUBQUERY */
75765
75766 /*
75767 ** Duplicate an 8-byte value
75768 */
75769 static char *dup8bytes(Vdbe *v, const char *in){
75770   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
75771   if( out ){
75772     memcpy(out, in, 8);
75773   }
75774   return out;
75775 }
75776
75777 #ifndef SQLITE_OMIT_FLOATING_POINT
75778 /*
75779 ** Generate an instruction that will put the floating point
75780 ** value described by z[0..n-1] into register iMem.
75781 **
75782 ** The z[] string will probably not be zero-terminated.  But the 
75783 ** z[n] character is guaranteed to be something that does not look
75784 ** like the continuation of the number.
75785 */
75786 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
75787   if( ALWAYS(z!=0) ){
75788     double value;
75789     char *zV;
75790     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
75791     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
75792     if( negateFlag ) value = -value;
75793     zV = dup8bytes(v, (char*)&value);
75794     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
75795   }
75796 }
75797 #endif
75798
75799
75800 /*
75801 ** Generate an instruction that will put the integer describe by
75802 ** text z[0..n-1] into register iMem.
75803 **
75804 ** Expr.u.zToken is always UTF8 and zero-terminated.
75805 */
75806 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
75807   Vdbe *v = pParse->pVdbe;
75808   if( pExpr->flags & EP_IntValue ){
75809     int i = pExpr->u.iValue;
75810     assert( i>=0 );
75811     if( negFlag ) i = -i;
75812     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
75813   }else{
75814     int c;
75815     i64 value;
75816     const char *z = pExpr->u.zToken;
75817     assert( z!=0 );
75818     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
75819     if( c==0 || (c==2 && negFlag) ){
75820       char *zV;
75821       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
75822       zV = dup8bytes(v, (char*)&value);
75823       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
75824     }else{
75825 #ifdef SQLITE_OMIT_FLOATING_POINT
75826       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
75827 #else
75828       codeReal(v, z, negFlag, iMem);
75829 #endif
75830     }
75831   }
75832 }
75833
75834 /*
75835 ** Clear a cache entry.
75836 */
75837 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
75838   if( p->tempReg ){
75839     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
75840       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
75841     }
75842     p->tempReg = 0;
75843   }
75844 }
75845
75846
75847 /*
75848 ** Record in the column cache that a particular column from a
75849 ** particular table is stored in a particular register.
75850 */
75851 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
75852   int i;
75853   int minLru;
75854   int idxLru;
75855   struct yColCache *p;
75856
75857   assert( iReg>0 );  /* Register numbers are always positive */
75858   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
75859
75860   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
75861   ** for testing only - to verify that SQLite always gets the same answer
75862   ** with and without the column cache.
75863   */
75864   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
75865
75866   /* First replace any existing entry.
75867   **
75868   ** Actually, the way the column cache is currently used, we are guaranteed
75869   ** that the object will never already be in cache.  Verify this guarantee.
75870   */
75871 #ifndef NDEBUG
75872   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75873     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
75874   }
75875 #endif
75876
75877   /* Find an empty slot and replace it */
75878   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75879     if( p->iReg==0 ){
75880       p->iLevel = pParse->iCacheLevel;
75881       p->iTable = iTab;
75882       p->iColumn = iCol;
75883       p->iReg = iReg;
75884       p->tempReg = 0;
75885       p->lru = pParse->iCacheCnt++;
75886       return;
75887     }
75888   }
75889
75890   /* Replace the last recently used */
75891   minLru = 0x7fffffff;
75892   idxLru = -1;
75893   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75894     if( p->lru<minLru ){
75895       idxLru = i;
75896       minLru = p->lru;
75897     }
75898   }
75899   if( ALWAYS(idxLru>=0) ){
75900     p = &pParse->aColCache[idxLru];
75901     p->iLevel = pParse->iCacheLevel;
75902     p->iTable = iTab;
75903     p->iColumn = iCol;
75904     p->iReg = iReg;
75905     p->tempReg = 0;
75906     p->lru = pParse->iCacheCnt++;
75907     return;
75908   }
75909 }
75910
75911 /*
75912 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
75913 ** Purge the range of registers from the column cache.
75914 */
75915 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
75916   int i;
75917   int iLast = iReg + nReg - 1;
75918   struct yColCache *p;
75919   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75920     int r = p->iReg;
75921     if( r>=iReg && r<=iLast ){
75922       cacheEntryClear(pParse, p);
75923       p->iReg = 0;
75924     }
75925   }
75926 }
75927
75928 /*
75929 ** Remember the current column cache context.  Any new entries added
75930 ** added to the column cache after this call are removed when the
75931 ** corresponding pop occurs.
75932 */
75933 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
75934   pParse->iCacheLevel++;
75935 }
75936
75937 /*
75938 ** Remove from the column cache any entries that were added since the
75939 ** the previous N Push operations.  In other words, restore the cache
75940 ** to the state it was in N Pushes ago.
75941 */
75942 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
75943   int i;
75944   struct yColCache *p;
75945   assert( N>0 );
75946   assert( pParse->iCacheLevel>=N );
75947   pParse->iCacheLevel -= N;
75948   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75949     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
75950       cacheEntryClear(pParse, p);
75951       p->iReg = 0;
75952     }
75953   }
75954 }
75955
75956 /*
75957 ** When a cached column is reused, make sure that its register is
75958 ** no longer available as a temp register.  ticket #3879:  that same
75959 ** register might be in the cache in multiple places, so be sure to
75960 ** get them all.
75961 */
75962 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
75963   int i;
75964   struct yColCache *p;
75965   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75966     if( p->iReg==iReg ){
75967       p->tempReg = 0;
75968     }
75969   }
75970 }
75971
75972 /*
75973 ** Generate code to extract the value of the iCol-th column of a table.
75974 */
75975 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
75976   Vdbe *v,        /* The VDBE under construction */
75977   Table *pTab,    /* The table containing the value */
75978   int iTabCur,    /* The cursor for this table */
75979   int iCol,       /* Index of the column to extract */
75980   int regOut      /* Extract the valud into this register */
75981 ){
75982   if( iCol<0 || iCol==pTab->iPKey ){
75983     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
75984   }else{
75985     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
75986     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
75987   }
75988   if( iCol>=0 ){
75989     sqlite3ColumnDefault(v, pTab, iCol, regOut);
75990   }
75991 }
75992
75993 /*
75994 ** Generate code that will extract the iColumn-th column from
75995 ** table pTab and store the column value in a register.  An effort
75996 ** is made to store the column value in register iReg, but this is
75997 ** not guaranteed.  The location of the column value is returned.
75998 **
75999 ** There must be an open cursor to pTab in iTable when this routine
76000 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
76001 */
76002 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
76003   Parse *pParse,   /* Parsing and code generating context */
76004   Table *pTab,     /* Description of the table we are reading from */
76005   int iColumn,     /* Index of the table column */
76006   int iTable,      /* The cursor pointing to the table */
76007   int iReg,        /* Store results here */
76008   u8 p5            /* P5 value for OP_Column */
76009 ){
76010   Vdbe *v = pParse->pVdbe;
76011   int i;
76012   struct yColCache *p;
76013
76014   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76015     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76016       p->lru = pParse->iCacheCnt++;
76017       sqlite3ExprCachePinRegister(pParse, p->iReg);
76018       return p->iReg;
76019     }
76020   }  
76021   assert( v!=0 );
76022   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76023   if( p5 ){
76024     sqlite3VdbeChangeP5(v, p5);
76025   }else{   
76026     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
76027   }
76028   return iReg;
76029 }
76030
76031 /*
76032 ** Clear all column cache entries.
76033 */
76034 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
76035   int i;
76036   struct yColCache *p;
76037
76038   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76039     if( p->iReg ){
76040       cacheEntryClear(pParse, p);
76041       p->iReg = 0;
76042     }
76043   }
76044 }
76045
76046 /*
76047 ** Record the fact that an affinity change has occurred on iCount
76048 ** registers starting with iStart.
76049 */
76050 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76051   sqlite3ExprCacheRemove(pParse, iStart, iCount);
76052 }
76053
76054 /*
76055 ** Generate code to move content from registers iFrom...iFrom+nReg-1
76056 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76057 */
76058 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76059   int i;
76060   struct yColCache *p;
76061   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
76062   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
76063   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76064     int x = p->iReg;
76065     if( x>=iFrom && x<iFrom+nReg ){
76066       p->iReg += iTo-iFrom;
76067     }
76068   }
76069 }
76070
76071 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
76072 /*
76073 ** Return true if any register in the range iFrom..iTo (inclusive)
76074 ** is used as part of the column cache.
76075 **
76076 ** This routine is used within assert() and testcase() macros only
76077 ** and does not appear in a normal build.
76078 */
76079 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76080   int i;
76081   struct yColCache *p;
76082   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76083     int r = p->iReg;
76084     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76085   }
76086   return 0;
76087 }
76088 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
76089
76090 /*
76091 ** Generate code into the current Vdbe to evaluate the given
76092 ** expression.  Attempt to store the results in register "target".
76093 ** Return the register where results are stored.
76094 **
76095 ** With this routine, there is no guarantee that results will
76096 ** be stored in target.  The result might be stored in some other
76097 ** register if it is convenient to do so.  The calling function
76098 ** must check the return code and move the results to the desired
76099 ** register.
76100 */
76101 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76102   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76103   int op;                   /* The opcode being coded */
76104   int inReg = target;       /* Results stored in register inReg */
76105   int regFree1 = 0;         /* If non-zero free this temporary register */
76106   int regFree2 = 0;         /* If non-zero free this temporary register */
76107   int r1, r2, r3, r4;       /* Various register numbers */
76108   sqlite3 *db = pParse->db; /* The database connection */
76109
76110   assert( target>0 && target<=pParse->nMem );
76111   if( v==0 ){
76112     assert( pParse->db->mallocFailed );
76113     return 0;
76114   }
76115
76116   if( pExpr==0 ){
76117     op = TK_NULL;
76118   }else{
76119     op = pExpr->op;
76120   }
76121   switch( op ){
76122     case TK_AGG_COLUMN: {
76123       AggInfo *pAggInfo = pExpr->pAggInfo;
76124       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76125       if( !pAggInfo->directMode ){
76126         assert( pCol->iMem>0 );
76127         inReg = pCol->iMem;
76128         break;
76129       }else if( pAggInfo->useSortingIdx ){
76130         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76131                               pCol->iSorterColumn, target);
76132         break;
76133       }
76134       /* Otherwise, fall thru into the TK_COLUMN case */
76135     }
76136     case TK_COLUMN: {
76137       if( pExpr->iTable<0 ){
76138         /* This only happens when coding check constraints */
76139         assert( pParse->ckBase>0 );
76140         inReg = pExpr->iColumn + pParse->ckBase;
76141       }else{
76142         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
76143                                  pExpr->iColumn, pExpr->iTable, target,
76144                                  pExpr->op2);
76145       }
76146       break;
76147     }
76148     case TK_INTEGER: {
76149       codeInteger(pParse, pExpr, 0, target);
76150       break;
76151     }
76152 #ifndef SQLITE_OMIT_FLOATING_POINT
76153     case TK_FLOAT: {
76154       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76155       codeReal(v, pExpr->u.zToken, 0, target);
76156       break;
76157     }
76158 #endif
76159     case TK_STRING: {
76160       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76161       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76162       break;
76163     }
76164     case TK_NULL: {
76165       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76166       break;
76167     }
76168 #ifndef SQLITE_OMIT_BLOB_LITERAL
76169     case TK_BLOB: {
76170       int n;
76171       const char *z;
76172       char *zBlob;
76173       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76174       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76175       assert( pExpr->u.zToken[1]=='\'' );
76176       z = &pExpr->u.zToken[2];
76177       n = sqlite3Strlen30(z) - 1;
76178       assert( z[n]=='\'' );
76179       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
76180       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76181       break;
76182     }
76183 #endif
76184     case TK_VARIABLE: {
76185       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76186       assert( pExpr->u.zToken!=0 );
76187       assert( pExpr->u.zToken[0]!=0 );
76188       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76189       if( pExpr->u.zToken[1]!=0 ){
76190         assert( pExpr->u.zToken[0]=='?' 
76191              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76192         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76193       }
76194       break;
76195     }
76196     case TK_REGISTER: {
76197       inReg = pExpr->iTable;
76198       break;
76199     }
76200     case TK_AS: {
76201       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76202       break;
76203     }
76204 #ifndef SQLITE_OMIT_CAST
76205     case TK_CAST: {
76206       /* Expressions of the form:   CAST(pLeft AS token) */
76207       int aff, to_op;
76208       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76209       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76210       aff = sqlite3AffinityType(pExpr->u.zToken);
76211       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
76212       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
76213       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
76214       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
76215       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
76216       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
76217       testcase( to_op==OP_ToText );
76218       testcase( to_op==OP_ToBlob );
76219       testcase( to_op==OP_ToNumeric );
76220       testcase( to_op==OP_ToInt );
76221       testcase( to_op==OP_ToReal );
76222       if( inReg!=target ){
76223         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
76224         inReg = target;
76225       }
76226       sqlite3VdbeAddOp1(v, to_op, inReg);
76227       testcase( usedAsColumnCache(pParse, inReg, inReg) );
76228       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
76229       break;
76230     }
76231 #endif /* SQLITE_OMIT_CAST */
76232     case TK_LT:
76233     case TK_LE:
76234     case TK_GT:
76235     case TK_GE:
76236     case TK_NE:
76237     case TK_EQ: {
76238       assert( TK_LT==OP_Lt );
76239       assert( TK_LE==OP_Le );
76240       assert( TK_GT==OP_Gt );
76241       assert( TK_GE==OP_Ge );
76242       assert( TK_EQ==OP_Eq );
76243       assert( TK_NE==OP_Ne );
76244       testcase( op==TK_LT );
76245       testcase( op==TK_LE );
76246       testcase( op==TK_GT );
76247       testcase( op==TK_GE );
76248       testcase( op==TK_EQ );
76249       testcase( op==TK_NE );
76250       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76251       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76252       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76253                   r1, r2, inReg, SQLITE_STOREP2);
76254       testcase( regFree1==0 );
76255       testcase( regFree2==0 );
76256       break;
76257     }
76258     case TK_IS:
76259     case TK_ISNOT: {
76260       testcase( op==TK_IS );
76261       testcase( op==TK_ISNOT );
76262       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76263       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76264       op = (op==TK_IS) ? TK_EQ : TK_NE;
76265       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76266                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
76267       testcase( regFree1==0 );
76268       testcase( regFree2==0 );
76269       break;
76270     }
76271     case TK_AND:
76272     case TK_OR:
76273     case TK_PLUS:
76274     case TK_STAR:
76275     case TK_MINUS:
76276     case TK_REM:
76277     case TK_BITAND:
76278     case TK_BITOR:
76279     case TK_SLASH:
76280     case TK_LSHIFT:
76281     case TK_RSHIFT: 
76282     case TK_CONCAT: {
76283       assert( TK_AND==OP_And );
76284       assert( TK_OR==OP_Or );
76285       assert( TK_PLUS==OP_Add );
76286       assert( TK_MINUS==OP_Subtract );
76287       assert( TK_REM==OP_Remainder );
76288       assert( TK_BITAND==OP_BitAnd );
76289       assert( TK_BITOR==OP_BitOr );
76290       assert( TK_SLASH==OP_Divide );
76291       assert( TK_LSHIFT==OP_ShiftLeft );
76292       assert( TK_RSHIFT==OP_ShiftRight );
76293       assert( TK_CONCAT==OP_Concat );
76294       testcase( op==TK_AND );
76295       testcase( op==TK_OR );
76296       testcase( op==TK_PLUS );
76297       testcase( op==TK_MINUS );
76298       testcase( op==TK_REM );
76299       testcase( op==TK_BITAND );
76300       testcase( op==TK_BITOR );
76301       testcase( op==TK_SLASH );
76302       testcase( op==TK_LSHIFT );
76303       testcase( op==TK_RSHIFT );
76304       testcase( op==TK_CONCAT );
76305       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76306       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76307       sqlite3VdbeAddOp3(v, op, r2, r1, target);
76308       testcase( regFree1==0 );
76309       testcase( regFree2==0 );
76310       break;
76311     }
76312     case TK_UMINUS: {
76313       Expr *pLeft = pExpr->pLeft;
76314       assert( pLeft );
76315       if( pLeft->op==TK_INTEGER ){
76316         codeInteger(pParse, pLeft, 1, target);
76317 #ifndef SQLITE_OMIT_FLOATING_POINT
76318       }else if( pLeft->op==TK_FLOAT ){
76319         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76320         codeReal(v, pLeft->u.zToken, 1, target);
76321 #endif
76322       }else{
76323         regFree1 = r1 = sqlite3GetTempReg(pParse);
76324         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
76325         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76326         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76327         testcase( regFree2==0 );
76328       }
76329       inReg = target;
76330       break;
76331     }
76332     case TK_BITNOT:
76333     case TK_NOT: {
76334       assert( TK_BITNOT==OP_BitNot );
76335       assert( TK_NOT==OP_Not );
76336       testcase( op==TK_BITNOT );
76337       testcase( op==TK_NOT );
76338       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76339       testcase( regFree1==0 );
76340       inReg = target;
76341       sqlite3VdbeAddOp2(v, op, r1, inReg);
76342       break;
76343     }
76344     case TK_ISNULL:
76345     case TK_NOTNULL: {
76346       int addr;
76347       assert( TK_ISNULL==OP_IsNull );
76348       assert( TK_NOTNULL==OP_NotNull );
76349       testcase( op==TK_ISNULL );
76350       testcase( op==TK_NOTNULL );
76351       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76352       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76353       testcase( regFree1==0 );
76354       addr = sqlite3VdbeAddOp1(v, op, r1);
76355       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
76356       sqlite3VdbeJumpHere(v, addr);
76357       break;
76358     }
76359     case TK_AGG_FUNCTION: {
76360       AggInfo *pInfo = pExpr->pAggInfo;
76361       if( pInfo==0 ){
76362         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76363         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76364       }else{
76365         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76366       }
76367       break;
76368     }
76369     case TK_CONST_FUNC:
76370     case TK_FUNCTION: {
76371       ExprList *pFarg;       /* List of function arguments */
76372       int nFarg;             /* Number of function arguments */
76373       FuncDef *pDef;         /* The function definition object */
76374       int nId;               /* Length of the function name in bytes */
76375       const char *zId;       /* The function name */
76376       int constMask = 0;     /* Mask of function arguments that are constant */
76377       int i;                 /* Loop counter */
76378       u8 enc = ENC(db);      /* The text encoding used by this database */
76379       CollSeq *pColl = 0;    /* A collating sequence */
76380
76381       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76382       testcase( op==TK_CONST_FUNC );
76383       testcase( op==TK_FUNCTION );
76384       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76385         pFarg = 0;
76386       }else{
76387         pFarg = pExpr->x.pList;
76388       }
76389       nFarg = pFarg ? pFarg->nExpr : 0;
76390       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76391       zId = pExpr->u.zToken;
76392       nId = sqlite3Strlen30(zId);
76393       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
76394       if( pDef==0 ){
76395         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76396         break;
76397       }
76398
76399       /* Attempt a direct implementation of the built-in COALESCE() and
76400       ** IFNULL() functions.  This avoids unnecessary evalation of
76401       ** arguments past the first non-NULL argument.
76402       */
76403       if( pDef->flags & SQLITE_FUNC_COALESCE ){
76404         int endCoalesce = sqlite3VdbeMakeLabel(v);
76405         assert( nFarg>=2 );
76406         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
76407         for(i=1; i<nFarg; i++){
76408           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76409           sqlite3ExprCacheRemove(pParse, target, 1);
76410           sqlite3ExprCachePush(pParse);
76411           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
76412           sqlite3ExprCachePop(pParse, 1);
76413         }
76414         sqlite3VdbeResolveLabel(v, endCoalesce);
76415         break;
76416       }
76417
76418
76419       if( pFarg ){
76420         r1 = sqlite3GetTempRange(pParse, nFarg);
76421
76422         /* For length() and typeof() functions with a column argument,
76423         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
76424         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
76425         ** loading.
76426         */
76427         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
76428           u8 exprOp;
76429           assert( nFarg==1 );
76430           assert( pFarg->a[0].pExpr!=0 );
76431           exprOp = pFarg->a[0].pExpr->op;
76432           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
76433             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
76434             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
76435             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
76436             pFarg->a[0].pExpr->op2 = pDef->flags;
76437           }
76438         }
76439
76440         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76441         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
76442         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76443       }else{
76444         r1 = 0;
76445       }
76446 #ifndef SQLITE_OMIT_VIRTUALTABLE
76447       /* Possibly overload the function if the first argument is
76448       ** a virtual table column.
76449       **
76450       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
76451       ** second argument, not the first, as the argument to test to
76452       ** see if it is a column in a virtual table.  This is done because
76453       ** the left operand of infix functions (the operand we want to
76454       ** control overloading) ends up as the second argument to the
76455       ** function.  The expression "A glob B" is equivalent to 
76456       ** "glob(B,A).  We want to use the A in "A glob B" to test
76457       ** for function overloading.  But we use the B term in "glob(B,A)".
76458       */
76459       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
76460         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
76461       }else if( nFarg>0 ){
76462         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
76463       }
76464 #endif
76465       for(i=0; i<nFarg; i++){
76466         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
76467           constMask |= (1<<i);
76468         }
76469         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
76470           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
76471         }
76472       }
76473       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
76474         if( !pColl ) pColl = db->pDfltColl; 
76475         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
76476       }
76477       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
76478                         (char*)pDef, P4_FUNCDEF);
76479       sqlite3VdbeChangeP5(v, (u8)nFarg);
76480       if( nFarg ){
76481         sqlite3ReleaseTempRange(pParse, r1, nFarg);
76482       }
76483       break;
76484     }
76485 #ifndef SQLITE_OMIT_SUBQUERY
76486     case TK_EXISTS:
76487     case TK_SELECT: {
76488       testcase( op==TK_EXISTS );
76489       testcase( op==TK_SELECT );
76490       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
76491       break;
76492     }
76493     case TK_IN: {
76494       int destIfFalse = sqlite3VdbeMakeLabel(v);
76495       int destIfNull = sqlite3VdbeMakeLabel(v);
76496       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76497       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76498       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76499       sqlite3VdbeResolveLabel(v, destIfFalse);
76500       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
76501       sqlite3VdbeResolveLabel(v, destIfNull);
76502       break;
76503     }
76504 #endif /* SQLITE_OMIT_SUBQUERY */
76505
76506
76507     /*
76508     **    x BETWEEN y AND z
76509     **
76510     ** This is equivalent to
76511     **
76512     **    x>=y AND x<=z
76513     **
76514     ** X is stored in pExpr->pLeft.
76515     ** Y is stored in pExpr->pList->a[0].pExpr.
76516     ** Z is stored in pExpr->pList->a[1].pExpr.
76517     */
76518     case TK_BETWEEN: {
76519       Expr *pLeft = pExpr->pLeft;
76520       struct ExprList_item *pLItem = pExpr->x.pList->a;
76521       Expr *pRight = pLItem->pExpr;
76522
76523       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
76524       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76525       testcase( regFree1==0 );
76526       testcase( regFree2==0 );
76527       r3 = sqlite3GetTempReg(pParse);
76528       r4 = sqlite3GetTempReg(pParse);
76529       codeCompare(pParse, pLeft, pRight, OP_Ge,
76530                   r1, r2, r3, SQLITE_STOREP2);
76531       pLItem++;
76532       pRight = pLItem->pExpr;
76533       sqlite3ReleaseTempReg(pParse, regFree2);
76534       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76535       testcase( regFree2==0 );
76536       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
76537       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
76538       sqlite3ReleaseTempReg(pParse, r3);
76539       sqlite3ReleaseTempReg(pParse, r4);
76540       break;
76541     }
76542     case TK_COLLATE: 
76543     case TK_UPLUS: {
76544       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76545       break;
76546     }
76547
76548     case TK_TRIGGER: {
76549       /* If the opcode is TK_TRIGGER, then the expression is a reference
76550       ** to a column in the new.* or old.* pseudo-tables available to
76551       ** trigger programs. In this case Expr.iTable is set to 1 for the
76552       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
76553       ** is set to the column of the pseudo-table to read, or to -1 to
76554       ** read the rowid field.
76555       **
76556       ** The expression is implemented using an OP_Param opcode. The p1
76557       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
76558       ** to reference another column of the old.* pseudo-table, where 
76559       ** i is the index of the column. For a new.rowid reference, p1 is
76560       ** set to (n+1), where n is the number of columns in each pseudo-table.
76561       ** For a reference to any other column in the new.* pseudo-table, p1
76562       ** is set to (n+2+i), where n and i are as defined previously. For
76563       ** example, if the table on which triggers are being fired is
76564       ** declared as:
76565       **
76566       **   CREATE TABLE t1(a, b);
76567       **
76568       ** Then p1 is interpreted as follows:
76569       **
76570       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
76571       **   p1==1   ->    old.a         p1==4   ->    new.a
76572       **   p1==2   ->    old.b         p1==5   ->    new.b       
76573       */
76574       Table *pTab = pExpr->pTab;
76575       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
76576
76577       assert( pExpr->iTable==0 || pExpr->iTable==1 );
76578       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
76579       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
76580       assert( p1>=0 && p1<(pTab->nCol*2+2) );
76581
76582       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
76583       VdbeComment((v, "%s.%s -> $%d",
76584         (pExpr->iTable ? "new" : "old"),
76585         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
76586         target
76587       ));
76588
76589 #ifndef SQLITE_OMIT_FLOATING_POINT
76590       /* If the column has REAL affinity, it may currently be stored as an
76591       ** integer. Use OP_RealAffinity to make sure it is really real.  */
76592       if( pExpr->iColumn>=0 
76593        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
76594       ){
76595         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
76596       }
76597 #endif
76598       break;
76599     }
76600
76601
76602     /*
76603     ** Form A:
76604     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76605     **
76606     ** Form B:
76607     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76608     **
76609     ** Form A is can be transformed into the equivalent form B as follows:
76610     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
76611     **        WHEN x=eN THEN rN ELSE y END
76612     **
76613     ** X (if it exists) is in pExpr->pLeft.
76614     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
76615     ** ELSE clause and no other term matches, then the result of the
76616     ** exprssion is NULL.
76617     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
76618     **
76619     ** The result of the expression is the Ri for the first matching Ei,
76620     ** or if there is no matching Ei, the ELSE term Y, or if there is
76621     ** no ELSE term, NULL.
76622     */
76623     default: assert( op==TK_CASE ); {
76624       int endLabel;                     /* GOTO label for end of CASE stmt */
76625       int nextCase;                     /* GOTO label for next WHEN clause */
76626       int nExpr;                        /* 2x number of WHEN terms */
76627       int i;                            /* Loop counter */
76628       ExprList *pEList;                 /* List of WHEN terms */
76629       struct ExprList_item *aListelem;  /* Array of WHEN terms */
76630       Expr opCompare;                   /* The X==Ei expression */
76631       Expr cacheX;                      /* Cached expression X */
76632       Expr *pX;                         /* The X expression */
76633       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
76634       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
76635
76636       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
76637       assert((pExpr->x.pList->nExpr % 2) == 0);
76638       assert(pExpr->x.pList->nExpr > 0);
76639       pEList = pExpr->x.pList;
76640       aListelem = pEList->a;
76641       nExpr = pEList->nExpr;
76642       endLabel = sqlite3VdbeMakeLabel(v);
76643       if( (pX = pExpr->pLeft)!=0 ){
76644         cacheX = *pX;
76645         testcase( pX->op==TK_COLUMN );
76646         testcase( pX->op==TK_REGISTER );
76647         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
76648         testcase( regFree1==0 );
76649         cacheX.op = TK_REGISTER;
76650         opCompare.op = TK_EQ;
76651         opCompare.pLeft = &cacheX;
76652         pTest = &opCompare;
76653         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
76654         ** The value in regFree1 might get SCopy-ed into the file result.
76655         ** So make sure that the regFree1 register is not reused for other
76656         ** purposes and possibly overwritten.  */
76657         regFree1 = 0;
76658       }
76659       for(i=0; i<nExpr; i=i+2){
76660         sqlite3ExprCachePush(pParse);
76661         if( pX ){
76662           assert( pTest!=0 );
76663           opCompare.pRight = aListelem[i].pExpr;
76664         }else{
76665           pTest = aListelem[i].pExpr;
76666         }
76667         nextCase = sqlite3VdbeMakeLabel(v);
76668         testcase( pTest->op==TK_COLUMN );
76669         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
76670         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
76671         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
76672         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
76673         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
76674         sqlite3ExprCachePop(pParse, 1);
76675         sqlite3VdbeResolveLabel(v, nextCase);
76676       }
76677       if( pExpr->pRight ){
76678         sqlite3ExprCachePush(pParse);
76679         sqlite3ExprCode(pParse, pExpr->pRight, target);
76680         sqlite3ExprCachePop(pParse, 1);
76681       }else{
76682         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76683       }
76684       assert( db->mallocFailed || pParse->nErr>0 
76685            || pParse->iCacheLevel==iCacheLevel );
76686       sqlite3VdbeResolveLabel(v, endLabel);
76687       break;
76688     }
76689 #ifndef SQLITE_OMIT_TRIGGER
76690     case TK_RAISE: {
76691       assert( pExpr->affinity==OE_Rollback 
76692            || pExpr->affinity==OE_Abort
76693            || pExpr->affinity==OE_Fail
76694            || pExpr->affinity==OE_Ignore
76695       );
76696       if( !pParse->pTriggerTab ){
76697         sqlite3ErrorMsg(pParse,
76698                        "RAISE() may only be used within a trigger-program");
76699         return 0;
76700       }
76701       if( pExpr->affinity==OE_Abort ){
76702         sqlite3MayAbort(pParse);
76703       }
76704       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76705       if( pExpr->affinity==OE_Ignore ){
76706         sqlite3VdbeAddOp4(
76707             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
76708       }else{
76709         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
76710       }
76711
76712       break;
76713     }
76714 #endif
76715   }
76716   sqlite3ReleaseTempReg(pParse, regFree1);
76717   sqlite3ReleaseTempReg(pParse, regFree2);
76718   return inReg;
76719 }
76720
76721 /*
76722 ** Generate code to evaluate an expression and store the results
76723 ** into a register.  Return the register number where the results
76724 ** are stored.
76725 **
76726 ** If the register is a temporary register that can be deallocated,
76727 ** then write its number into *pReg.  If the result register is not
76728 ** a temporary, then set *pReg to zero.
76729 */
76730 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
76731   int r1 = sqlite3GetTempReg(pParse);
76732   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76733   if( r2==r1 ){
76734     *pReg = r1;
76735   }else{
76736     sqlite3ReleaseTempReg(pParse, r1);
76737     *pReg = 0;
76738   }
76739   return r2;
76740 }
76741
76742 /*
76743 ** Generate code that will evaluate expression pExpr and store the
76744 ** results in register target.  The results are guaranteed to appear
76745 ** in register target.
76746 */
76747 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
76748   int inReg;
76749
76750   assert( target>0 && target<=pParse->nMem );
76751   if( pExpr && pExpr->op==TK_REGISTER ){
76752     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
76753   }else{
76754     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
76755     assert( pParse->pVdbe || pParse->db->mallocFailed );
76756     if( inReg!=target && pParse->pVdbe ){
76757       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
76758     }
76759   }
76760   return target;
76761 }
76762
76763 /*
76764 ** Generate code that evalutes the given expression and puts the result
76765 ** in register target.
76766 **
76767 ** Also make a copy of the expression results into another "cache" register
76768 ** and modify the expression so that the next time it is evaluated,
76769 ** the result is a copy of the cache register.
76770 **
76771 ** This routine is used for expressions that are used multiple 
76772 ** times.  They are evaluated once and the results of the expression
76773 ** are reused.
76774 */
76775 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
76776   Vdbe *v = pParse->pVdbe;
76777   int inReg;
76778   inReg = sqlite3ExprCode(pParse, pExpr, target);
76779   assert( target>0 );
76780   /* This routine is called for terms to INSERT or UPDATE.  And the only
76781   ** other place where expressions can be converted into TK_REGISTER is
76782   ** in WHERE clause processing.  So as currently implemented, there is
76783   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
76784   ** keep the ALWAYS() in case the conditions above change with future
76785   ** modifications or enhancements. */
76786   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
76787     int iMem;
76788     iMem = ++pParse->nMem;
76789     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
76790     pExpr->iTable = iMem;
76791     pExpr->op2 = pExpr->op;
76792     pExpr->op = TK_REGISTER;
76793   }
76794   return inReg;
76795 }
76796
76797 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
76798 /*
76799 ** Generate a human-readable explanation of an expression tree.
76800 */
76801 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
76802   int op;                   /* The opcode being coded */
76803   const char *zBinOp = 0;   /* Binary operator */
76804   const char *zUniOp = 0;   /* Unary operator */
76805   if( pExpr==0 ){
76806     op = TK_NULL;
76807   }else{
76808     op = pExpr->op;
76809   }
76810   switch( op ){
76811     case TK_AGG_COLUMN: {
76812       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
76813             pExpr->iTable, pExpr->iColumn);
76814       break;
76815     }
76816     case TK_COLUMN: {
76817       if( pExpr->iTable<0 ){
76818         /* This only happens when coding check constraints */
76819         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
76820       }else{
76821         sqlite3ExplainPrintf(pOut, "{%d:%d}",
76822                              pExpr->iTable, pExpr->iColumn);
76823       }
76824       break;
76825     }
76826     case TK_INTEGER: {
76827       if( pExpr->flags & EP_IntValue ){
76828         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
76829       }else{
76830         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
76831       }
76832       break;
76833     }
76834 #ifndef SQLITE_OMIT_FLOATING_POINT
76835     case TK_FLOAT: {
76836       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
76837       break;
76838     }
76839 #endif
76840     case TK_STRING: {
76841       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
76842       break;
76843     }
76844     case TK_NULL: {
76845       sqlite3ExplainPrintf(pOut,"NULL");
76846       break;
76847     }
76848 #ifndef SQLITE_OMIT_BLOB_LITERAL
76849     case TK_BLOB: {
76850       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
76851       break;
76852     }
76853 #endif
76854     case TK_VARIABLE: {
76855       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
76856                            pExpr->u.zToken, pExpr->iColumn);
76857       break;
76858     }
76859     case TK_REGISTER: {
76860       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
76861       break;
76862     }
76863     case TK_AS: {
76864       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76865       break;
76866     }
76867 #ifndef SQLITE_OMIT_CAST
76868     case TK_CAST: {
76869       /* Expressions of the form:   CAST(pLeft AS token) */
76870       const char *zAff = "unk";
76871       switch( sqlite3AffinityType(pExpr->u.zToken) ){
76872         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
76873         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
76874         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
76875         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
76876         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
76877       }
76878       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
76879       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76880       sqlite3ExplainPrintf(pOut, ")");
76881       break;
76882     }
76883 #endif /* SQLITE_OMIT_CAST */
76884     case TK_LT:      zBinOp = "LT";     break;
76885     case TK_LE:      zBinOp = "LE";     break;
76886     case TK_GT:      zBinOp = "GT";     break;
76887     case TK_GE:      zBinOp = "GE";     break;
76888     case TK_NE:      zBinOp = "NE";     break;
76889     case TK_EQ:      zBinOp = "EQ";     break;
76890     case TK_IS:      zBinOp = "IS";     break;
76891     case TK_ISNOT:   zBinOp = "ISNOT";  break;
76892     case TK_AND:     zBinOp = "AND";    break;
76893     case TK_OR:      zBinOp = "OR";     break;
76894     case TK_PLUS:    zBinOp = "ADD";    break;
76895     case TK_STAR:    zBinOp = "MUL";    break;
76896     case TK_MINUS:   zBinOp = "SUB";    break;
76897     case TK_REM:     zBinOp = "REM";    break;
76898     case TK_BITAND:  zBinOp = "BITAND"; break;
76899     case TK_BITOR:   zBinOp = "BITOR";  break;
76900     case TK_SLASH:   zBinOp = "DIV";    break;
76901     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
76902     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
76903     case TK_CONCAT:  zBinOp = "CONCAT"; break;
76904
76905     case TK_UMINUS:  zUniOp = "UMINUS"; break;
76906     case TK_UPLUS:   zUniOp = "UPLUS";  break;
76907     case TK_BITNOT:  zUniOp = "BITNOT"; break;
76908     case TK_NOT:     zUniOp = "NOT";    break;
76909     case TK_ISNULL:  zUniOp = "ISNULL"; break;
76910     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
76911
76912     case TK_COLLATE: {
76913       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76914       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
76915       break;
76916     }
76917
76918     case TK_AGG_FUNCTION:
76919     case TK_CONST_FUNC:
76920     case TK_FUNCTION: {
76921       ExprList *pFarg;       /* List of function arguments */
76922       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76923         pFarg = 0;
76924       }else{
76925         pFarg = pExpr->x.pList;
76926       }
76927       if( op==TK_AGG_FUNCTION ){
76928         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
76929                              pExpr->op2, pExpr->u.zToken);
76930       }else{
76931         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
76932       }
76933       if( pFarg ){
76934         sqlite3ExplainExprList(pOut, pFarg);
76935       }
76936       sqlite3ExplainPrintf(pOut, ")");
76937       break;
76938     }
76939 #ifndef SQLITE_OMIT_SUBQUERY
76940     case TK_EXISTS: {
76941       sqlite3ExplainPrintf(pOut, "EXISTS(");
76942       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76943       sqlite3ExplainPrintf(pOut,")");
76944       break;
76945     }
76946     case TK_SELECT: {
76947       sqlite3ExplainPrintf(pOut, "(");
76948       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76949       sqlite3ExplainPrintf(pOut, ")");
76950       break;
76951     }
76952     case TK_IN: {
76953       sqlite3ExplainPrintf(pOut, "IN(");
76954       sqlite3ExplainExpr(pOut, pExpr->pLeft);
76955       sqlite3ExplainPrintf(pOut, ",");
76956       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76957         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
76958       }else{
76959         sqlite3ExplainExprList(pOut, pExpr->x.pList);
76960       }
76961       sqlite3ExplainPrintf(pOut, ")");
76962       break;
76963     }
76964 #endif /* SQLITE_OMIT_SUBQUERY */
76965
76966     /*
76967     **    x BETWEEN y AND z
76968     **
76969     ** This is equivalent to
76970     **
76971     **    x>=y AND x<=z
76972     **
76973     ** X is stored in pExpr->pLeft.
76974     ** Y is stored in pExpr->pList->a[0].pExpr.
76975     ** Z is stored in pExpr->pList->a[1].pExpr.
76976     */
76977     case TK_BETWEEN: {
76978       Expr *pX = pExpr->pLeft;
76979       Expr *pY = pExpr->x.pList->a[0].pExpr;
76980       Expr *pZ = pExpr->x.pList->a[1].pExpr;
76981       sqlite3ExplainPrintf(pOut, "BETWEEN(");
76982       sqlite3ExplainExpr(pOut, pX);
76983       sqlite3ExplainPrintf(pOut, ",");
76984       sqlite3ExplainExpr(pOut, pY);
76985       sqlite3ExplainPrintf(pOut, ",");
76986       sqlite3ExplainExpr(pOut, pZ);
76987       sqlite3ExplainPrintf(pOut, ")");
76988       break;
76989     }
76990     case TK_TRIGGER: {
76991       /* If the opcode is TK_TRIGGER, then the expression is a reference
76992       ** to a column in the new.* or old.* pseudo-tables available to
76993       ** trigger programs. In this case Expr.iTable is set to 1 for the
76994       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
76995       ** is set to the column of the pseudo-table to read, or to -1 to
76996       ** read the rowid field.
76997       */
76998       sqlite3ExplainPrintf(pOut, "%s(%d)", 
76999           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
77000       break;
77001     }
77002     case TK_CASE: {
77003       sqlite3ExplainPrintf(pOut, "CASE(");
77004       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77005       sqlite3ExplainPrintf(pOut, ",");
77006       sqlite3ExplainExprList(pOut, pExpr->x.pList);
77007       break;
77008     }
77009 #ifndef SQLITE_OMIT_TRIGGER
77010     case TK_RAISE: {
77011       const char *zType = "unk";
77012       switch( pExpr->affinity ){
77013         case OE_Rollback:   zType = "rollback";  break;
77014         case OE_Abort:      zType = "abort";     break;
77015         case OE_Fail:       zType = "fail";      break;
77016         case OE_Ignore:     zType = "ignore";    break;
77017       }
77018       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
77019       break;
77020     }
77021 #endif
77022   }
77023   if( zBinOp ){
77024     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
77025     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77026     sqlite3ExplainPrintf(pOut,",");
77027     sqlite3ExplainExpr(pOut, pExpr->pRight);
77028     sqlite3ExplainPrintf(pOut,")");
77029   }else if( zUniOp ){
77030     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
77031     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77032     sqlite3ExplainPrintf(pOut,")");
77033   }
77034 }
77035 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
77036
77037 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77038 /*
77039 ** Generate a human-readable explanation of an expression list.
77040 */
77041 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
77042   int i;
77043   if( pList==0 || pList->nExpr==0 ){
77044     sqlite3ExplainPrintf(pOut, "(empty-list)");
77045     return;
77046   }else if( pList->nExpr==1 ){
77047     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
77048   }else{
77049     sqlite3ExplainPush(pOut);
77050     for(i=0; i<pList->nExpr; i++){
77051       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
77052       sqlite3ExplainPush(pOut);
77053       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
77054       sqlite3ExplainPop(pOut);
77055       if( i<pList->nExpr-1 ){
77056         sqlite3ExplainNL(pOut);
77057       }
77058     }
77059     sqlite3ExplainPop(pOut);
77060   }
77061 }
77062 #endif /* SQLITE_DEBUG */
77063
77064 /*
77065 ** Return TRUE if pExpr is an constant expression that is appropriate
77066 ** for factoring out of a loop.  Appropriate expressions are:
77067 **
77068 **    *  Any expression that evaluates to two or more opcodes.
77069 **
77070 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
77071 **       or OP_Variable that does not need to be placed in a 
77072 **       specific register.
77073 **
77074 ** There is no point in factoring out single-instruction constant
77075 ** expressions that need to be placed in a particular register.  
77076 ** We could factor them out, but then we would end up adding an
77077 ** OP_SCopy instruction to move the value into the correct register
77078 ** later.  We might as well just use the original instruction and
77079 ** avoid the OP_SCopy.
77080 */
77081 static int isAppropriateForFactoring(Expr *p){
77082   if( !sqlite3ExprIsConstantNotJoin(p) ){
77083     return 0;  /* Only constant expressions are appropriate for factoring */
77084   }
77085   if( (p->flags & EP_FixedDest)==0 ){
77086     return 1;  /* Any constant without a fixed destination is appropriate */
77087   }
77088   while( p->op==TK_UPLUS ) p = p->pLeft;
77089   switch( p->op ){
77090 #ifndef SQLITE_OMIT_BLOB_LITERAL
77091     case TK_BLOB:
77092 #endif
77093     case TK_VARIABLE:
77094     case TK_INTEGER:
77095     case TK_FLOAT:
77096     case TK_NULL:
77097     case TK_STRING: {
77098       testcase( p->op==TK_BLOB );
77099       testcase( p->op==TK_VARIABLE );
77100       testcase( p->op==TK_INTEGER );
77101       testcase( p->op==TK_FLOAT );
77102       testcase( p->op==TK_NULL );
77103       testcase( p->op==TK_STRING );
77104       /* Single-instruction constants with a fixed destination are
77105       ** better done in-line.  If we factor them, they will just end
77106       ** up generating an OP_SCopy to move the value to the destination
77107       ** register. */
77108       return 0;
77109     }
77110     case TK_UMINUS: {
77111       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77112         return 0;
77113       }
77114       break;
77115     }
77116     default: {
77117       break;
77118     }
77119   }
77120   return 1;
77121 }
77122
77123 /*
77124 ** If pExpr is a constant expression that is appropriate for
77125 ** factoring out of a loop, then evaluate the expression
77126 ** into a register and convert the expression into a TK_REGISTER
77127 ** expression.
77128 */
77129 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77130   Parse *pParse = pWalker->pParse;
77131   switch( pExpr->op ){
77132     case TK_IN:
77133     case TK_REGISTER: {
77134       return WRC_Prune;
77135     }
77136     case TK_COLLATE: {
77137       return WRC_Continue;
77138     }
77139     case TK_FUNCTION:
77140     case TK_AGG_FUNCTION:
77141     case TK_CONST_FUNC: {
77142       /* The arguments to a function have a fixed destination.
77143       ** Mark them this way to avoid generated unneeded OP_SCopy
77144       ** instructions. 
77145       */
77146       ExprList *pList = pExpr->x.pList;
77147       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77148       if( pList ){
77149         int i = pList->nExpr;
77150         struct ExprList_item *pItem = pList->a;
77151         for(; i>0; i--, pItem++){
77152           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77153         }
77154       }
77155       break;
77156     }
77157   }
77158   if( isAppropriateForFactoring(pExpr) ){
77159     int r1 = ++pParse->nMem;
77160     int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77161     /* If r2!=r1, it means that register r1 is never used.  That is harmless
77162     ** but suboptimal, so we want to know about the situation to fix it.
77163     ** Hence the following assert: */
77164     assert( r2==r1 );
77165     pExpr->op2 = pExpr->op;
77166     pExpr->op = TK_REGISTER;
77167     pExpr->iTable = r2;
77168     return WRC_Prune;
77169   }
77170   return WRC_Continue;
77171 }
77172
77173 /*
77174 ** Preevaluate constant subexpressions within pExpr and store the
77175 ** results in registers.  Modify pExpr so that the constant subexpresions
77176 ** are TK_REGISTER opcodes that refer to the precomputed values.
77177 **
77178 ** This routine is a no-op if the jump to the cookie-check code has
77179 ** already occur.  Since the cookie-check jump is generated prior to
77180 ** any other serious processing, this check ensures that there is no
77181 ** way to accidently bypass the constant initializations.
77182 **
77183 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
77184 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
77185 ** interface.  This allows test logic to verify that the same answer is
77186 ** obtained for queries regardless of whether or not constants are
77187 ** precomputed into registers or if they are inserted in-line.
77188 */
77189 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77190   Walker w;
77191   if( pParse->cookieGoto ) return;
77192   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
77193   w.xExprCallback = evalConstExpr;
77194   w.xSelectCallback = 0;
77195   w.pParse = pParse;
77196   sqlite3WalkExpr(&w, pExpr);
77197 }
77198
77199
77200 /*
77201 ** Generate code that pushes the value of every element of the given
77202 ** expression list into a sequence of registers beginning at target.
77203 **
77204 ** Return the number of elements evaluated.
77205 */
77206 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
77207   Parse *pParse,     /* Parsing context */
77208   ExprList *pList,   /* The expression list to be coded */
77209   int target,        /* Where to write results */
77210   int doHardCopy     /* Make a hard copy of every element */
77211 ){
77212   struct ExprList_item *pItem;
77213   int i, n;
77214   assert( pList!=0 );
77215   assert( target>0 );
77216   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77217   n = pList->nExpr;
77218   for(pItem=pList->a, i=0; i<n; i++, pItem++){
77219     Expr *pExpr = pItem->pExpr;
77220     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
77221     if( inReg!=target+i ){
77222       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77223                         inReg, target+i);
77224     }
77225   }
77226   return n;
77227 }
77228
77229 /*
77230 ** Generate code for a BETWEEN operator.
77231 **
77232 **    x BETWEEN y AND z
77233 **
77234 ** The above is equivalent to 
77235 **
77236 **    x>=y AND x<=z
77237 **
77238 ** Code it as such, taking care to do the common subexpression
77239 ** elementation of x.
77240 */
77241 static void exprCodeBetween(
77242   Parse *pParse,    /* Parsing and code generating context */
77243   Expr *pExpr,      /* The BETWEEN expression */
77244   int dest,         /* Jump here if the jump is taken */
77245   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77246   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77247 ){
77248   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77249   Expr compLeft;    /* The  x>=y  term */
77250   Expr compRight;   /* The  x<=z  term */
77251   Expr exprX;       /* The  x  subexpression */
77252   int regFree1 = 0; /* Temporary use register */
77253
77254   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77255   exprX = *pExpr->pLeft;
77256   exprAnd.op = TK_AND;
77257   exprAnd.pLeft = &compLeft;
77258   exprAnd.pRight = &compRight;
77259   compLeft.op = TK_GE;
77260   compLeft.pLeft = &exprX;
77261   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77262   compRight.op = TK_LE;
77263   compRight.pLeft = &exprX;
77264   compRight.pRight = pExpr->x.pList->a[1].pExpr;
77265   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
77266   exprX.op = TK_REGISTER;
77267   if( jumpIfTrue ){
77268     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77269   }else{
77270     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77271   }
77272   sqlite3ReleaseTempReg(pParse, regFree1);
77273
77274   /* Ensure adequate test coverage */
77275   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77276   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77277   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77278   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77279   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77280   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77281   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77282   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77283 }
77284
77285 /*
77286 ** Generate code for a boolean expression such that a jump is made
77287 ** to the label "dest" if the expression is true but execution
77288 ** continues straight thru if the expression is false.
77289 **
77290 ** If the expression evaluates to NULL (neither true nor false), then
77291 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
77292 **
77293 ** This code depends on the fact that certain token values (ex: TK_EQ)
77294 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77295 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77296 ** the make process cause these values to align.  Assert()s in the code
77297 ** below verify that the numbers are aligned correctly.
77298 */
77299 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77300   Vdbe *v = pParse->pVdbe;
77301   int op = 0;
77302   int regFree1 = 0;
77303   int regFree2 = 0;
77304   int r1, r2;
77305
77306   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77307   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
77308   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77309   op = pExpr->op;
77310   switch( op ){
77311     case TK_AND: {
77312       int d2 = sqlite3VdbeMakeLabel(v);
77313       testcase( jumpIfNull==0 );
77314       sqlite3ExprCachePush(pParse);
77315       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
77316       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77317       sqlite3VdbeResolveLabel(v, d2);
77318       sqlite3ExprCachePop(pParse, 1);
77319       break;
77320     }
77321     case TK_OR: {
77322       testcase( jumpIfNull==0 );
77323       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77324       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77325       break;
77326     }
77327     case TK_NOT: {
77328       testcase( jumpIfNull==0 );
77329       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77330       break;
77331     }
77332     case TK_LT:
77333     case TK_LE:
77334     case TK_GT:
77335     case TK_GE:
77336     case TK_NE:
77337     case TK_EQ: {
77338       assert( TK_LT==OP_Lt );
77339       assert( TK_LE==OP_Le );
77340       assert( TK_GT==OP_Gt );
77341       assert( TK_GE==OP_Ge );
77342       assert( TK_EQ==OP_Eq );
77343       assert( TK_NE==OP_Ne );
77344       testcase( op==TK_LT );
77345       testcase( op==TK_LE );
77346       testcase( op==TK_GT );
77347       testcase( op==TK_GE );
77348       testcase( op==TK_EQ );
77349       testcase( op==TK_NE );
77350       testcase( jumpIfNull==0 );
77351       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77352       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77353       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77354                   r1, r2, dest, jumpIfNull);
77355       testcase( regFree1==0 );
77356       testcase( regFree2==0 );
77357       break;
77358     }
77359     case TK_IS:
77360     case TK_ISNOT: {
77361       testcase( op==TK_IS );
77362       testcase( op==TK_ISNOT );
77363       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77364       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77365       op = (op==TK_IS) ? TK_EQ : TK_NE;
77366       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77367                   r1, r2, dest, SQLITE_NULLEQ);
77368       testcase( regFree1==0 );
77369       testcase( regFree2==0 );
77370       break;
77371     }
77372     case TK_ISNULL:
77373     case TK_NOTNULL: {
77374       assert( TK_ISNULL==OP_IsNull );
77375       assert( TK_NOTNULL==OP_NotNull );
77376       testcase( op==TK_ISNULL );
77377       testcase( op==TK_NOTNULL );
77378       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77379       sqlite3VdbeAddOp2(v, op, r1, dest);
77380       testcase( regFree1==0 );
77381       break;
77382     }
77383     case TK_BETWEEN: {
77384       testcase( jumpIfNull==0 );
77385       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77386       break;
77387     }
77388 #ifndef SQLITE_OMIT_SUBQUERY
77389     case TK_IN: {
77390       int destIfFalse = sqlite3VdbeMakeLabel(v);
77391       int destIfNull = jumpIfNull ? dest : destIfFalse;
77392       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77393       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
77394       sqlite3VdbeResolveLabel(v, destIfFalse);
77395       break;
77396     }
77397 #endif
77398     default: {
77399       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77400       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77401       testcase( regFree1==0 );
77402       testcase( jumpIfNull==0 );
77403       break;
77404     }
77405   }
77406   sqlite3ReleaseTempReg(pParse, regFree1);
77407   sqlite3ReleaseTempReg(pParse, regFree2);  
77408 }
77409
77410 /*
77411 ** Generate code for a boolean expression such that a jump is made
77412 ** to the label "dest" if the expression is false but execution
77413 ** continues straight thru if the expression is true.
77414 **
77415 ** If the expression evaluates to NULL (neither true nor false) then
77416 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
77417 ** is 0.
77418 */
77419 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77420   Vdbe *v = pParse->pVdbe;
77421   int op = 0;
77422   int regFree1 = 0;
77423   int regFree2 = 0;
77424   int r1, r2;
77425
77426   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77427   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
77428   if( pExpr==0 )    return;
77429
77430   /* The value of pExpr->op and op are related as follows:
77431   **
77432   **       pExpr->op            op
77433   **       ---------          ----------
77434   **       TK_ISNULL          OP_NotNull
77435   **       TK_NOTNULL         OP_IsNull
77436   **       TK_NE              OP_Eq
77437   **       TK_EQ              OP_Ne
77438   **       TK_GT              OP_Le
77439   **       TK_LE              OP_Gt
77440   **       TK_GE              OP_Lt
77441   **       TK_LT              OP_Ge
77442   **
77443   ** For other values of pExpr->op, op is undefined and unused.
77444   ** The value of TK_ and OP_ constants are arranged such that we
77445   ** can compute the mapping above using the following expression.
77446   ** Assert()s verify that the computation is correct.
77447   */
77448   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77449
77450   /* Verify correct alignment of TK_ and OP_ constants
77451   */
77452   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77453   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77454   assert( pExpr->op!=TK_NE || op==OP_Eq );
77455   assert( pExpr->op!=TK_EQ || op==OP_Ne );
77456   assert( pExpr->op!=TK_LT || op==OP_Ge );
77457   assert( pExpr->op!=TK_LE || op==OP_Gt );
77458   assert( pExpr->op!=TK_GT || op==OP_Le );
77459   assert( pExpr->op!=TK_GE || op==OP_Lt );
77460
77461   switch( pExpr->op ){
77462     case TK_AND: {
77463       testcase( jumpIfNull==0 );
77464       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77465       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77466       break;
77467     }
77468     case TK_OR: {
77469       int d2 = sqlite3VdbeMakeLabel(v);
77470       testcase( jumpIfNull==0 );
77471       sqlite3ExprCachePush(pParse);
77472       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
77473       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77474       sqlite3VdbeResolveLabel(v, d2);
77475       sqlite3ExprCachePop(pParse, 1);
77476       break;
77477     }
77478     case TK_NOT: {
77479       testcase( jumpIfNull==0 );
77480       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77481       break;
77482     }
77483     case TK_LT:
77484     case TK_LE:
77485     case TK_GT:
77486     case TK_GE:
77487     case TK_NE:
77488     case TK_EQ: {
77489       testcase( op==TK_LT );
77490       testcase( op==TK_LE );
77491       testcase( op==TK_GT );
77492       testcase( op==TK_GE );
77493       testcase( op==TK_EQ );
77494       testcase( op==TK_NE );
77495       testcase( jumpIfNull==0 );
77496       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77497       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77498       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77499                   r1, r2, dest, jumpIfNull);
77500       testcase( regFree1==0 );
77501       testcase( regFree2==0 );
77502       break;
77503     }
77504     case TK_IS:
77505     case TK_ISNOT: {
77506       testcase( pExpr->op==TK_IS );
77507       testcase( pExpr->op==TK_ISNOT );
77508       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77509       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77510       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
77511       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77512                   r1, r2, dest, SQLITE_NULLEQ);
77513       testcase( regFree1==0 );
77514       testcase( regFree2==0 );
77515       break;
77516     }
77517     case TK_ISNULL:
77518     case TK_NOTNULL: {
77519       testcase( op==TK_ISNULL );
77520       testcase( op==TK_NOTNULL );
77521       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77522       sqlite3VdbeAddOp2(v, op, r1, dest);
77523       testcase( regFree1==0 );
77524       break;
77525     }
77526     case TK_BETWEEN: {
77527       testcase( jumpIfNull==0 );
77528       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
77529       break;
77530     }
77531 #ifndef SQLITE_OMIT_SUBQUERY
77532     case TK_IN: {
77533       if( jumpIfNull ){
77534         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
77535       }else{
77536         int destIfNull = sqlite3VdbeMakeLabel(v);
77537         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
77538         sqlite3VdbeResolveLabel(v, destIfNull);
77539       }
77540       break;
77541     }
77542 #endif
77543     default: {
77544       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77545       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
77546       testcase( regFree1==0 );
77547       testcase( jumpIfNull==0 );
77548       break;
77549     }
77550   }
77551   sqlite3ReleaseTempReg(pParse, regFree1);
77552   sqlite3ReleaseTempReg(pParse, regFree2);
77553 }
77554
77555 /*
77556 ** Do a deep comparison of two expression trees.  Return 0 if the two
77557 ** expressions are completely identical.  Return 1 if they differ only
77558 ** by a COLLATE operator at the top level.  Return 2 if there are differences
77559 ** other than the top-level COLLATE operator.
77560 **
77561 ** Sometimes this routine will return 2 even if the two expressions
77562 ** really are equivalent.  If we cannot prove that the expressions are
77563 ** identical, we return 2 just to be safe.  So if this routine
77564 ** returns 2, then you do not really know for certain if the two
77565 ** expressions are the same.  But if you get a 0 or 1 return, then you
77566 ** can be sure the expressions are the same.  In the places where
77567 ** this routine is used, it does not hurt to get an extra 2 - that
77568 ** just might result in some slightly slower code.  But returning
77569 ** an incorrect 0 or 1 could lead to a malfunction.
77570 */
77571 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
77572   if( pA==0||pB==0 ){
77573     return pB==pA ? 0 : 2;
77574   }
77575   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77576   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77577   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77578     return 2;
77579   }
77580   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77581   if( pA->op!=pB->op ){
77582     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
77583       return 1;
77584     }
77585     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
77586       return 1;
77587     }
77588     return 2;
77589   }
77590   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77591   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77592   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77593   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77594   if( ExprHasProperty(pA, EP_IntValue) ){
77595     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77596       return 2;
77597     }
77598   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
77599     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77600     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77601       return pA->op==TK_COLLATE ? 1 : 2;
77602     }
77603   }
77604   return 0;
77605 }
77606
77607 /*
77608 ** Compare two ExprList objects.  Return 0 if they are identical and 
77609 ** non-zero if they differ in any way.
77610 **
77611 ** This routine might return non-zero for equivalent ExprLists.  The
77612 ** only consequence will be disabled optimizations.  But this routine
77613 ** must never return 0 if the two ExprList objects are different, or
77614 ** a malfunction will result.
77615 **
77616 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77617 ** always differs from a non-NULL pointer.
77618 */
77619 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
77620   int i;
77621   if( pA==0 && pB==0 ) return 0;
77622   if( pA==0 || pB==0 ) return 1;
77623   if( pA->nExpr!=pB->nExpr ) return 1;
77624   for(i=0; i<pA->nExpr; i++){
77625     Expr *pExprA = pA->a[i].pExpr;
77626     Expr *pExprB = pB->a[i].pExpr;
77627     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77628     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
77629   }
77630   return 0;
77631 }
77632
77633 /*
77634 ** An instance of the following structure is used by the tree walker
77635 ** to count references to table columns in the arguments of an 
77636 ** aggregate function, in order to implement the
77637 ** sqlite3FunctionThisSrc() routine.
77638 */
77639 struct SrcCount {
77640   SrcList *pSrc;   /* One particular FROM clause in a nested query */
77641   int nThis;       /* Number of references to columns in pSrcList */
77642   int nOther;      /* Number of references to columns in other FROM clauses */
77643 };
77644
77645 /*
77646 ** Count the number of references to columns.
77647 */
77648 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
77649   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
77650   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
77651   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
77652   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
77653   ** NEVER() will need to be removed. */
77654   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
77655     int i;
77656     struct SrcCount *p = pWalker->u.pSrcCount;
77657     SrcList *pSrc = p->pSrc;
77658     for(i=0; i<pSrc->nSrc; i++){
77659       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
77660     }
77661     if( i<pSrc->nSrc ){
77662       p->nThis++;
77663     }else{
77664       p->nOther++;
77665     }
77666   }
77667   return WRC_Continue;
77668 }
77669
77670 /*
77671 ** Determine if any of the arguments to the pExpr Function reference
77672 ** pSrcList.  Return true if they do.  Also return true if the function
77673 ** has no arguments or has only constant arguments.  Return false if pExpr
77674 ** references columns but not columns of tables found in pSrcList.
77675 */
77676 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
77677   Walker w;
77678   struct SrcCount cnt;
77679   assert( pExpr->op==TK_AGG_FUNCTION );
77680   memset(&w, 0, sizeof(w));
77681   w.xExprCallback = exprSrcCount;
77682   w.u.pSrcCount = &cnt;
77683   cnt.pSrc = pSrcList;
77684   cnt.nThis = 0;
77685   cnt.nOther = 0;
77686   sqlite3WalkExprList(&w, pExpr->x.pList);
77687   return cnt.nThis>0 || cnt.nOther==0;
77688 }
77689
77690 /*
77691 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77692 ** the new element.  Return a negative number if malloc fails.
77693 */
77694 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
77695   int i;
77696   pInfo->aCol = sqlite3ArrayAllocate(
77697        db,
77698        pInfo->aCol,
77699        sizeof(pInfo->aCol[0]),
77700        &pInfo->nColumn,
77701        &i
77702   );
77703   return i;
77704 }    
77705
77706 /*
77707 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77708 ** the new element.  Return a negative number if malloc fails.
77709 */
77710 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
77711   int i;
77712   pInfo->aFunc = sqlite3ArrayAllocate(
77713        db, 
77714        pInfo->aFunc,
77715        sizeof(pInfo->aFunc[0]),
77716        &pInfo->nFunc,
77717        &i
77718   );
77719   return i;
77720 }    
77721
77722 /*
77723 ** This is the xExprCallback for a tree walker.  It is used to
77724 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
77725 ** for additional information.
77726 */
77727 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77728   int i;
77729   NameContext *pNC = pWalker->u.pNC;
77730   Parse *pParse = pNC->pParse;
77731   SrcList *pSrcList = pNC->pSrcList;
77732   AggInfo *pAggInfo = pNC->pAggInfo;
77733
77734   switch( pExpr->op ){
77735     case TK_AGG_COLUMN:
77736     case TK_COLUMN: {
77737       testcase( pExpr->op==TK_AGG_COLUMN );
77738       testcase( pExpr->op==TK_COLUMN );
77739       /* Check to see if the column is in one of the tables in the FROM
77740       ** clause of the aggregate query */
77741       if( ALWAYS(pSrcList!=0) ){
77742         struct SrcList_item *pItem = pSrcList->a;
77743         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77744           struct AggInfo_col *pCol;
77745           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77746           if( pExpr->iTable==pItem->iCursor ){
77747             /* If we reach this point, it means that pExpr refers to a table
77748             ** that is in the FROM clause of the aggregate query.  
77749             **
77750             ** Make an entry for the column in pAggInfo->aCol[] if there
77751             ** is not an entry there already.
77752             */
77753             int k;
77754             pCol = pAggInfo->aCol;
77755             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77756               if( pCol->iTable==pExpr->iTable &&
77757                   pCol->iColumn==pExpr->iColumn ){
77758                 break;
77759               }
77760             }
77761             if( (k>=pAggInfo->nColumn)
77762              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
77763             ){
77764               pCol = &pAggInfo->aCol[k];
77765               pCol->pTab = pExpr->pTab;
77766               pCol->iTable = pExpr->iTable;
77767               pCol->iColumn = pExpr->iColumn;
77768               pCol->iMem = ++pParse->nMem;
77769               pCol->iSorterColumn = -1;
77770               pCol->pExpr = pExpr;
77771               if( pAggInfo->pGroupBy ){
77772                 int j, n;
77773                 ExprList *pGB = pAggInfo->pGroupBy;
77774                 struct ExprList_item *pTerm = pGB->a;
77775                 n = pGB->nExpr;
77776                 for(j=0; j<n; j++, pTerm++){
77777                   Expr *pE = pTerm->pExpr;
77778                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77779                       pE->iColumn==pExpr->iColumn ){
77780                     pCol->iSorterColumn = j;
77781                     break;
77782                   }
77783                 }
77784               }
77785               if( pCol->iSorterColumn<0 ){
77786                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
77787               }
77788             }
77789             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
77790             ** because it was there before or because we just created it).
77791             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
77792             ** pAggInfo->aCol[] entry.
77793             */
77794             ExprSetIrreducible(pExpr);
77795             pExpr->pAggInfo = pAggInfo;
77796             pExpr->op = TK_AGG_COLUMN;
77797             pExpr->iAgg = (i16)k;
77798             break;
77799           } /* endif pExpr->iTable==pItem->iCursor */
77800         } /* end loop over pSrcList */
77801       }
77802       return WRC_Prune;
77803     }
77804     case TK_AGG_FUNCTION: {
77805       if( (pNC->ncFlags & NC_InAggFunc)==0
77806        && pWalker->walkerDepth==pExpr->op2
77807       ){
77808         /* Check to see if pExpr is a duplicate of another aggregate 
77809         ** function that is already in the pAggInfo structure
77810         */
77811         struct AggInfo_func *pItem = pAggInfo->aFunc;
77812         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
77813           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
77814             break;
77815           }
77816         }
77817         if( i>=pAggInfo->nFunc ){
77818           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
77819           */
77820           u8 enc = ENC(pParse->db);
77821           i = addAggInfoFunc(pParse->db, pAggInfo);
77822           if( i>=0 ){
77823             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77824             pItem = &pAggInfo->aFunc[i];
77825             pItem->pExpr = pExpr;
77826             pItem->iMem = ++pParse->nMem;
77827             assert( !ExprHasProperty(pExpr, EP_IntValue) );
77828             pItem->pFunc = sqlite3FindFunction(pParse->db,
77829                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
77830                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
77831             if( pExpr->flags & EP_Distinct ){
77832               pItem->iDistinct = pParse->nTab++;
77833             }else{
77834               pItem->iDistinct = -1;
77835             }
77836           }
77837         }
77838         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
77839         */
77840         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77841         ExprSetIrreducible(pExpr);
77842         pExpr->iAgg = (i16)i;
77843         pExpr->pAggInfo = pAggInfo;
77844         return WRC_Prune;
77845       }else{
77846         return WRC_Continue;
77847       }
77848     }
77849   }
77850   return WRC_Continue;
77851 }
77852 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
77853   UNUSED_PARAMETER(pWalker);
77854   UNUSED_PARAMETER(pSelect);
77855   return WRC_Continue;
77856 }
77857
77858 /*
77859 ** Analyze the pExpr expression looking for aggregate functions and
77860 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
77861 ** points to.  Additional entries are made on the AggInfo object as
77862 ** necessary.
77863 **
77864 ** This routine should only be called after the expression has been
77865 ** analyzed by sqlite3ResolveExprNames().
77866 */
77867 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
77868   Walker w;
77869   memset(&w, 0, sizeof(w));
77870   w.xExprCallback = analyzeAggregate;
77871   w.xSelectCallback = analyzeAggregatesInSelect;
77872   w.u.pNC = pNC;
77873   assert( pNC->pSrcList!=0 );
77874   sqlite3WalkExpr(&w, pExpr);
77875 }
77876
77877 /*
77878 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
77879 ** expression list.  Return the number of errors.
77880 **
77881 ** If an error is found, the analysis is cut short.
77882 */
77883 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
77884   struct ExprList_item *pItem;
77885   int i;
77886   if( pList ){
77887     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
77888       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
77889     }
77890   }
77891 }
77892
77893 /*
77894 ** Allocate a single new register for use to hold some intermediate result.
77895 */
77896 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
77897   if( pParse->nTempReg==0 ){
77898     return ++pParse->nMem;
77899   }
77900   return pParse->aTempReg[--pParse->nTempReg];
77901 }
77902
77903 /*
77904 ** Deallocate a register, making available for reuse for some other
77905 ** purpose.
77906 **
77907 ** If a register is currently being used by the column cache, then
77908 ** the dallocation is deferred until the column cache line that uses
77909 ** the register becomes stale.
77910 */
77911 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
77912   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77913     int i;
77914     struct yColCache *p;
77915     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77916       if( p->iReg==iReg ){
77917         p->tempReg = 1;
77918         return;
77919       }
77920     }
77921     pParse->aTempReg[pParse->nTempReg++] = iReg;
77922   }
77923 }
77924
77925 /*
77926 ** Allocate or deallocate a block of nReg consecutive registers
77927 */
77928 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
77929   int i, n;
77930   i = pParse->iRangeReg;
77931   n = pParse->nRangeReg;
77932   if( nReg<=n ){
77933     assert( !usedAsColumnCache(pParse, i, i+n-1) );
77934     pParse->iRangeReg += nReg;
77935     pParse->nRangeReg -= nReg;
77936   }else{
77937     i = pParse->nMem+1;
77938     pParse->nMem += nReg;
77939   }
77940   return i;
77941 }
77942 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
77943   sqlite3ExprCacheRemove(pParse, iReg, nReg);
77944   if( nReg>pParse->nRangeReg ){
77945     pParse->nRangeReg = nReg;
77946     pParse->iRangeReg = iReg;
77947   }
77948 }
77949
77950 /*
77951 ** Mark all temporary registers as being unavailable for reuse.
77952 */
77953 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
77954   pParse->nTempReg = 0;
77955   pParse->nRangeReg = 0;
77956 }
77957
77958 /************** End of expr.c ************************************************/
77959 /************** Begin file alter.c *******************************************/
77960 /*
77961 ** 2005 February 15
77962 **
77963 ** The author disclaims copyright to this source code.  In place of
77964 ** a legal notice, here is a blessing:
77965 **
77966 **    May you do good and not evil.
77967 **    May you find forgiveness for yourself and forgive others.
77968 **    May you share freely, never taking more than you give.
77969 **
77970 *************************************************************************
77971 ** This file contains C code routines that used to generate VDBE code
77972 ** that implements the ALTER TABLE command.
77973 */
77974
77975 /*
77976 ** The code in this file only exists if we are not omitting the
77977 ** ALTER TABLE logic from the build.
77978 */
77979 #ifndef SQLITE_OMIT_ALTERTABLE
77980
77981
77982 /*
77983 ** This function is used by SQL generated to implement the 
77984 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
77985 ** CREATE INDEX command. The second is a table name. The table name in 
77986 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
77987 ** argument and the result returned. Examples:
77988 **
77989 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
77990 **     -> 'CREATE TABLE def(a, b, c)'
77991 **
77992 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
77993 **     -> 'CREATE INDEX i ON def(a, b, c)'
77994 */
77995 static void renameTableFunc(
77996   sqlite3_context *context,
77997   int NotUsed,
77998   sqlite3_value **argv
77999 ){
78000   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78001   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78002
78003   int token;
78004   Token tname;
78005   unsigned char const *zCsr = zSql;
78006   int len = 0;
78007   char *zRet;
78008
78009   sqlite3 *db = sqlite3_context_db_handle(context);
78010
78011   UNUSED_PARAMETER(NotUsed);
78012
78013   /* The principle used to locate the table name in the CREATE TABLE 
78014   ** statement is that the table name is the first non-space token that
78015   ** is immediately followed by a TK_LP or TK_USING token.
78016   */
78017   if( zSql ){
78018     do {
78019       if( !*zCsr ){
78020         /* Ran out of input before finding an opening bracket. Return NULL. */
78021         return;
78022       }
78023
78024       /* Store the token that zCsr points to in tname. */
78025       tname.z = (char*)zCsr;
78026       tname.n = len;
78027
78028       /* Advance zCsr to the next token. Store that token type in 'token',
78029       ** and its length in 'len' (to be used next iteration of this loop).
78030       */
78031       do {
78032         zCsr += len;
78033         len = sqlite3GetToken(zCsr, &token);
78034       } while( token==TK_SPACE );
78035       assert( len>0 );
78036     } while( token!=TK_LP && token!=TK_USING );
78037
78038     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78039        zTableName, tname.z+tname.n);
78040     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78041   }
78042 }
78043
78044 /*
78045 ** This C function implements an SQL user function that is used by SQL code
78046 ** generated by the ALTER TABLE ... RENAME command to modify the definition
78047 ** of any foreign key constraints that use the table being renamed as the 
78048 ** parent table. It is passed three arguments:
78049 **
78050 **   1) The complete text of the CREATE TABLE statement being modified,
78051 **   2) The old name of the table being renamed, and
78052 **   3) The new name of the table being renamed.
78053 **
78054 ** It returns the new CREATE TABLE statement. For example:
78055 **
78056 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78057 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
78058 */
78059 #ifndef SQLITE_OMIT_FOREIGN_KEY
78060 static void renameParentFunc(
78061   sqlite3_context *context,
78062   int NotUsed,
78063   sqlite3_value **argv
78064 ){
78065   sqlite3 *db = sqlite3_context_db_handle(context);
78066   char *zOutput = 0;
78067   char *zResult;
78068   unsigned char const *zInput = sqlite3_value_text(argv[0]);
78069   unsigned char const *zOld = sqlite3_value_text(argv[1]);
78070   unsigned char const *zNew = sqlite3_value_text(argv[2]);
78071
78072   unsigned const char *z;         /* Pointer to token */
78073   int n;                          /* Length of token z */
78074   int token;                      /* Type of token */
78075
78076   UNUSED_PARAMETER(NotUsed);
78077   for(z=zInput; *z; z=z+n){
78078     n = sqlite3GetToken(z, &token);
78079     if( token==TK_REFERENCES ){
78080       char *zParent;
78081       do {
78082         z += n;
78083         n = sqlite3GetToken(z, &token);
78084       }while( token==TK_SPACE );
78085
78086       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
78087       if( zParent==0 ) break;
78088       sqlite3Dequote(zParent);
78089       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
78090         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
78091             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78092         );
78093         sqlite3DbFree(db, zOutput);
78094         zOutput = zOut;
78095         zInput = &z[n];
78096       }
78097       sqlite3DbFree(db, zParent);
78098     }
78099   }
78100
78101   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
78102   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
78103   sqlite3DbFree(db, zOutput);
78104 }
78105 #endif
78106
78107 #ifndef SQLITE_OMIT_TRIGGER
78108 /* This function is used by SQL generated to implement the
78109 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
78110 ** statement. The second is a table name. The table name in the CREATE 
78111 ** TRIGGER statement is replaced with the third argument and the result 
78112 ** returned. This is analagous to renameTableFunc() above, except for CREATE
78113 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
78114 */
78115 static void renameTriggerFunc(
78116   sqlite3_context *context,
78117   int NotUsed,
78118   sqlite3_value **argv
78119 ){
78120   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78121   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78122
78123   int token;
78124   Token tname;
78125   int dist = 3;
78126   unsigned char const *zCsr = zSql;
78127   int len = 0;
78128   char *zRet;
78129   sqlite3 *db = sqlite3_context_db_handle(context);
78130
78131   UNUSED_PARAMETER(NotUsed);
78132
78133   /* The principle used to locate the table name in the CREATE TRIGGER 
78134   ** statement is that the table name is the first token that is immediatedly
78135   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78136   ** of TK_WHEN, TK_BEGIN or TK_FOR.
78137   */
78138   if( zSql ){
78139     do {
78140
78141       if( !*zCsr ){
78142         /* Ran out of input before finding the table name. Return NULL. */
78143         return;
78144       }
78145
78146       /* Store the token that zCsr points to in tname. */
78147       tname.z = (char*)zCsr;
78148       tname.n = len;
78149
78150       /* Advance zCsr to the next token. Store that token type in 'token',
78151       ** and its length in 'len' (to be used next iteration of this loop).
78152       */
78153       do {
78154         zCsr += len;
78155         len = sqlite3GetToken(zCsr, &token);
78156       }while( token==TK_SPACE );
78157       assert( len>0 );
78158
78159       /* Variable 'dist' stores the number of tokens read since the most
78160       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
78161       ** token is read and 'dist' equals 2, the condition stated above
78162       ** to be met.
78163       **
78164       ** Note that ON cannot be a database, table or column name, so
78165       ** there is no need to worry about syntax like 
78166       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78167       */
78168       dist++;
78169       if( token==TK_DOT || token==TK_ON ){
78170         dist = 0;
78171       }
78172     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78173
78174     /* Variable tname now contains the token that is the old table-name
78175     ** in the CREATE TRIGGER statement.
78176     */
78177     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
78178        zTableName, tname.z+tname.n);
78179     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78180   }
78181 }
78182 #endif   /* !SQLITE_OMIT_TRIGGER */
78183
78184 /*
78185 ** Register built-in functions used to help implement ALTER TABLE
78186 */
78187 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
78188   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
78189     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
78190 #ifndef SQLITE_OMIT_TRIGGER
78191     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
78192 #endif
78193 #ifndef SQLITE_OMIT_FOREIGN_KEY
78194     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
78195 #endif
78196   };
78197   int i;
78198   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78199   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78200
78201   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78202     sqlite3FuncDefInsert(pHash, &aFunc[i]);
78203   }
78204 }
78205
78206 /*
78207 ** This function is used to create the text of expressions of the form:
78208 **
78209 **   name=<constant1> OR name=<constant2> OR ...
78210 **
78211 ** If argument zWhere is NULL, then a pointer string containing the text 
78212 ** "name=<constant>" is returned, where <constant> is the quoted version
78213 ** of the string passed as argument zConstant. The returned buffer is
78214 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
78215 ** caller to ensure that it is eventually freed.
78216 **
78217 ** If argument zWhere is not NULL, then the string returned is 
78218 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78219 ** In this case zWhere is passed to sqlite3DbFree() before returning.
78220 ** 
78221 */
78222 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
78223   char *zNew;
78224   if( !zWhere ){
78225     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
78226   }else{
78227     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78228     sqlite3DbFree(db, zWhere);
78229   }
78230   return zNew;
78231 }
78232
78233 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78234 /*
78235 ** Generate the text of a WHERE expression which can be used to select all
78236 ** tables that have foreign key constraints that refer to table pTab (i.e.
78237 ** constraints for which pTab is the parent table) from the sqlite_master
78238 ** table.
78239 */
78240 static char *whereForeignKeys(Parse *pParse, Table *pTab){
78241   FKey *p;
78242   char *zWhere = 0;
78243   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78244     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78245   }
78246   return zWhere;
78247 }
78248 #endif
78249
78250 /*
78251 ** Generate the text of a WHERE expression which can be used to select all
78252 ** temporary triggers on table pTab from the sqlite_temp_master table. If
78253 ** table pTab has no temporary triggers, or is itself stored in the 
78254 ** temporary database, NULL is returned.
78255 */
78256 static char *whereTempTriggers(Parse *pParse, Table *pTab){
78257   Trigger *pTrig;
78258   char *zWhere = 0;
78259   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78260
78261   /* If the table is not located in the temp-db (in which case NULL is 
78262   ** returned, loop through the tables list of triggers. For each trigger
78263   ** that is not part of the temp-db schema, add a clause to the WHERE 
78264   ** expression being built up in zWhere.
78265   */
78266   if( pTab->pSchema!=pTempSchema ){
78267     sqlite3 *db = pParse->db;
78268     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78269       if( pTrig->pSchema==pTempSchema ){
78270         zWhere = whereOrName(db, zWhere, pTrig->zName);
78271       }
78272     }
78273   }
78274   if( zWhere ){
78275     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78276     sqlite3DbFree(pParse->db, zWhere);
78277     zWhere = zNew;
78278   }
78279   return zWhere;
78280 }
78281
78282 /*
78283 ** Generate code to drop and reload the internal representation of table
78284 ** pTab from the database, including triggers and temporary triggers.
78285 ** Argument zName is the name of the table in the database schema at
78286 ** the time the generated code is executed. This can be different from
78287 ** pTab->zName if this function is being called to code part of an 
78288 ** "ALTER TABLE RENAME TO" statement.
78289 */
78290 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78291   Vdbe *v;
78292   char *zWhere;
78293   int iDb;                   /* Index of database containing pTab */
78294 #ifndef SQLITE_OMIT_TRIGGER
78295   Trigger *pTrig;
78296 #endif
78297
78298   v = sqlite3GetVdbe(pParse);
78299   if( NEVER(v==0) ) return;
78300   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78301   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78302   assert( iDb>=0 );
78303
78304 #ifndef SQLITE_OMIT_TRIGGER
78305   /* Drop any table triggers from the internal schema. */
78306   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78307     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78308     assert( iTrigDb==iDb || iTrigDb==1 );
78309     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78310   }
78311 #endif
78312
78313   /* Drop the table and index from the internal schema.  */
78314   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78315
78316   /* Reload the table, index and permanent trigger schemas. */
78317   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
78318   if( !zWhere ) return;
78319   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
78320
78321 #ifndef SQLITE_OMIT_TRIGGER
78322   /* Now, if the table is not stored in the temp database, reload any temp 
78323   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
78324   */
78325   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78326     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
78327   }
78328 #endif
78329 }
78330
78331 /*
78332 ** Parameter zName is the name of a table that is about to be altered
78333 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78334 ** If the table is a system table, this function leaves an error message
78335 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
78336 **
78337 ** Or, if zName is not a system table, zero is returned.
78338 */
78339 static int isSystemTable(Parse *pParse, const char *zName){
78340   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78341     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
78342     return 1;
78343   }
78344   return 0;
78345 }
78346
78347 /*
78348 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
78349 ** command. 
78350 */
78351 SQLITE_PRIVATE void sqlite3AlterRenameTable(
78352   Parse *pParse,            /* Parser context. */
78353   SrcList *pSrc,            /* The table to rename. */
78354   Token *pName              /* The new table name. */
78355 ){
78356   int iDb;                  /* Database that contains the table */
78357   char *zDb;                /* Name of database iDb */
78358   Table *pTab;              /* Table being renamed */
78359   char *zName = 0;          /* NULL-terminated version of pName */ 
78360   sqlite3 *db = pParse->db; /* Database connection */
78361   int nTabName;             /* Number of UTF-8 characters in zTabName */
78362   const char *zTabName;     /* Original name of the table */
78363   Vdbe *v;
78364 #ifndef SQLITE_OMIT_TRIGGER
78365   char *zWhere = 0;         /* Where clause to locate temp triggers */
78366 #endif
78367   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78368   int savedDbFlags;         /* Saved value of db->flags */
78369
78370   savedDbFlags = db->flags;  
78371   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78372   assert( pSrc->nSrc==1 );
78373   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78374
78375   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78376   if( !pTab ) goto exit_rename_table;
78377   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78378   zDb = db->aDb[iDb].zName;
78379   db->flags |= SQLITE_PreferBuiltin;
78380
78381   /* Get a NULL terminated version of the new table name. */
78382   zName = sqlite3NameFromToken(db, pName);
78383   if( !zName ) goto exit_rename_table;
78384
78385   /* Check that a table or index named 'zName' does not already exist
78386   ** in database iDb. If so, this is an error.
78387   */
78388   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
78389     sqlite3ErrorMsg(pParse, 
78390         "there is already another table or index with this name: %s", zName);
78391     goto exit_rename_table;
78392   }
78393
78394   /* Make sure it is not a system table being altered, or a reserved name
78395   ** that the table is being renamed to.
78396   */
78397   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78398     goto exit_rename_table;
78399   }
78400   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
78401     exit_rename_table;
78402   }
78403
78404 #ifndef SQLITE_OMIT_VIEW
78405   if( pTab->pSelect ){
78406     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78407     goto exit_rename_table;
78408   }
78409 #endif
78410
78411 #ifndef SQLITE_OMIT_AUTHORIZATION
78412   /* Invoke the authorization callback. */
78413   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78414     goto exit_rename_table;
78415   }
78416 #endif
78417
78418 #ifndef SQLITE_OMIT_VIRTUALTABLE
78419   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78420     goto exit_rename_table;
78421   }
78422   if( IsVirtual(pTab) ){
78423     pVTab = sqlite3GetVTable(db, pTab);
78424     if( pVTab->pVtab->pModule->xRename==0 ){
78425       pVTab = 0;
78426     }
78427   }
78428 #endif
78429
78430   /* Begin a transaction and code the VerifyCookie for database iDb. 
78431   ** Then modify the schema cookie (since the ALTER TABLE modifies the
78432   ** schema). Open a statement transaction if the table is a virtual
78433   ** table.
78434   */
78435   v = sqlite3GetVdbe(pParse);
78436   if( v==0 ){
78437     goto exit_rename_table;
78438   }
78439   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
78440   sqlite3ChangeCookie(pParse, iDb);
78441
78442   /* If this is a virtual table, invoke the xRename() function if
78443   ** one is defined. The xRename() callback will modify the names
78444   ** of any resources used by the v-table implementation (including other
78445   ** SQLite tables) that are identified by the name of the virtual table.
78446   */
78447 #ifndef SQLITE_OMIT_VIRTUALTABLE
78448   if( pVTab ){
78449     int i = ++pParse->nMem;
78450     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78451     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78452     sqlite3MayAbort(pParse);
78453   }
78454 #endif
78455
78456   /* figure out how many UTF-8 characters are in zName */
78457   zTabName = pTab->zName;
78458   nTabName = sqlite3Utf8CharLen(zTabName, -1);
78459
78460 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78461   if( db->flags&SQLITE_ForeignKeys ){
78462     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
78463     ** statements corresponding to all child tables of foreign key constraints
78464     ** for which the renamed table is the parent table.  */
78465     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78466       sqlite3NestedParse(pParse, 
78467           "UPDATE \"%w\".%s SET "
78468               "sql = sqlite_rename_parent(sql, %Q, %Q) "
78469               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78470       sqlite3DbFree(db, zWhere);
78471     }
78472   }
78473 #endif
78474
78475   /* Modify the sqlite_master table to use the new table name. */
78476   sqlite3NestedParse(pParse,
78477       "UPDATE %Q.%s SET "
78478 #ifdef SQLITE_OMIT_TRIGGER
78479           "sql = sqlite_rename_table(sql, %Q), "
78480 #else
78481           "sql = CASE "
78482             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
78483             "ELSE sqlite_rename_table(sql, %Q) END, "
78484 #endif
78485           "tbl_name = %Q, "
78486           "name = CASE "
78487             "WHEN type='table' THEN %Q "
78488             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
78489              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
78490             "ELSE name END "
78491       "WHERE tbl_name=%Q COLLATE nocase AND "
78492           "(type='table' OR type='index' OR type='trigger');", 
78493       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
78494 #ifndef SQLITE_OMIT_TRIGGER
78495       zName,
78496 #endif
78497       zName, nTabName, zTabName
78498   );
78499
78500 #ifndef SQLITE_OMIT_AUTOINCREMENT
78501   /* If the sqlite_sequence table exists in this database, then update 
78502   ** it with the new table name.
78503   */
78504   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
78505     sqlite3NestedParse(pParse,
78506         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
78507         zDb, zName, pTab->zName);
78508   }
78509 #endif
78510
78511 #ifndef SQLITE_OMIT_TRIGGER
78512   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
78513   ** table. Don't do this if the table being ALTERed is itself located in
78514   ** the temp database.
78515   */
78516   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78517     sqlite3NestedParse(pParse, 
78518         "UPDATE sqlite_temp_master SET "
78519             "sql = sqlite_rename_trigger(sql, %Q), "
78520             "tbl_name = %Q "
78521             "WHERE %s;", zName, zName, zWhere);
78522     sqlite3DbFree(db, zWhere);
78523   }
78524 #endif
78525
78526 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78527   if( db->flags&SQLITE_ForeignKeys ){
78528     FKey *p;
78529     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78530       Table *pFrom = p->pFrom;
78531       if( pFrom!=pTab ){
78532         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
78533       }
78534     }
78535   }
78536 #endif
78537
78538   /* Drop and reload the internal table schema. */
78539   reloadTableSchema(pParse, pTab, zName);
78540
78541 exit_rename_table:
78542   sqlite3SrcListDelete(db, pSrc);
78543   sqlite3DbFree(db, zName);
78544   db->flags = savedDbFlags;
78545 }
78546
78547
78548 /*
78549 ** Generate code to make sure the file format number is at least minFormat.
78550 ** The generated code will increase the file format number if necessary.
78551 */
78552 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
78553   Vdbe *v;
78554   v = sqlite3GetVdbe(pParse);
78555   /* The VDBE should have been allocated before this routine is called.
78556   ** If that allocation failed, we would have quit before reaching this
78557   ** point */
78558   if( ALWAYS(v) ){
78559     int r1 = sqlite3GetTempReg(pParse);
78560     int r2 = sqlite3GetTempReg(pParse);
78561     int j1;
78562     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
78563     sqlite3VdbeUsesBtree(v, iDb);
78564     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
78565     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
78566     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
78567     sqlite3VdbeJumpHere(v, j1);
78568     sqlite3ReleaseTempReg(pParse, r1);
78569     sqlite3ReleaseTempReg(pParse, r2);
78570   }
78571 }
78572
78573 /*
78574 ** This function is called after an "ALTER TABLE ... ADD" statement
78575 ** has been parsed. Argument pColDef contains the text of the new
78576 ** column definition.
78577 **
78578 ** The Table structure pParse->pNewTable was extended to include
78579 ** the new column during parsing.
78580 */
78581 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
78582   Table *pNew;              /* Copy of pParse->pNewTable */
78583   Table *pTab;              /* Table being altered */
78584   int iDb;                  /* Database number */
78585   const char *zDb;          /* Database name */
78586   const char *zTab;         /* Table name */
78587   char *zCol;               /* Null-terminated column definition */
78588   Column *pCol;             /* The new column */
78589   Expr *pDflt;              /* Default value for the new column */
78590   sqlite3 *db;              /* The database connection; */
78591
78592   db = pParse->db;
78593   if( pParse->nErr || db->mallocFailed ) return;
78594   pNew = pParse->pNewTable;
78595   assert( pNew );
78596
78597   assert( sqlite3BtreeHoldsAllMutexes(db) );
78598   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
78599   zDb = db->aDb[iDb].zName;
78600   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
78601   pCol = &pNew->aCol[pNew->nCol-1];
78602   pDflt = pCol->pDflt;
78603   pTab = sqlite3FindTable(db, zTab, zDb);
78604   assert( pTab );
78605
78606 #ifndef SQLITE_OMIT_AUTHORIZATION
78607   /* Invoke the authorization callback. */
78608   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78609     return;
78610   }
78611 #endif
78612
78613   /* If the default value for the new column was specified with a 
78614   ** literal NULL, then set pDflt to 0. This simplifies checking
78615   ** for an SQL NULL default below.
78616   */
78617   if( pDflt && pDflt->op==TK_NULL ){
78618     pDflt = 0;
78619   }
78620
78621   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78622   ** If there is a NOT NULL constraint, then the default value for the
78623   ** column must not be NULL.
78624   */
78625   if( pCol->colFlags & COLFLAG_PRIMKEY ){
78626     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78627     return;
78628   }
78629   if( pNew->pIndex ){
78630     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78631     return;
78632   }
78633   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
78634     sqlite3ErrorMsg(pParse, 
78635         "Cannot add a REFERENCES column with non-NULL default value");
78636     return;
78637   }
78638   if( pCol->notNull && !pDflt ){
78639     sqlite3ErrorMsg(pParse, 
78640         "Cannot add a NOT NULL column with default value NULL");
78641     return;
78642   }
78643
78644   /* Ensure the default expression is something that sqlite3ValueFromExpr()
78645   ** can handle (i.e. not CURRENT_TIME etc.)
78646   */
78647   if( pDflt ){
78648     sqlite3_value *pVal;
78649     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
78650       db->mallocFailed = 1;
78651       return;
78652     }
78653     if( !pVal ){
78654       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78655       return;
78656     }
78657     sqlite3ValueFree(pVal);
78658   }
78659
78660   /* Modify the CREATE TABLE statement. */
78661   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78662   if( zCol ){
78663     char *zEnd = &zCol[pColDef->n-1];
78664     int savedDbFlags = db->flags;
78665     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
78666       *zEnd-- = '\0';
78667     }
78668     db->flags |= SQLITE_PreferBuiltin;
78669     sqlite3NestedParse(pParse, 
78670         "UPDATE \"%w\".%s SET "
78671           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78672         "WHERE type = 'table' AND name = %Q", 
78673       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78674       zTab
78675     );
78676     sqlite3DbFree(db, zCol);
78677     db->flags = savedDbFlags;
78678   }
78679
78680   /* If the default value of the new column is NULL, then set the file
78681   ** format to 2. If the default value of the new column is not NULL,
78682   ** the file format becomes 3.
78683   */
78684   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78685
78686   /* Reload the schema of the modified table. */
78687   reloadTableSchema(pParse, pTab, pTab->zName);
78688 }
78689
78690 /*
78691 ** This function is called by the parser after the table-name in
78692 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
78693 ** pSrc is the full-name of the table being altered.
78694 **
78695 ** This routine makes a (partial) copy of the Table structure
78696 ** for the table being altered and sets Parse.pNewTable to point
78697 ** to it. Routines called by the parser as the column definition
78698 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
78699 ** the copy. The copy of the Table structure is deleted by tokenize.c 
78700 ** after parsing is finished.
78701 **
78702 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
78703 ** coding the "ALTER TABLE ... ADD" statement.
78704 */
78705 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78706   Table *pNew;
78707   Table *pTab;
78708   Vdbe *v;
78709   int iDb;
78710   int i;
78711   int nAlloc;
78712   sqlite3 *db = pParse->db;
78713
78714   /* Look up the table being altered. */
78715   assert( pParse->pNewTable==0 );
78716   assert( sqlite3BtreeHoldsAllMutexes(db) );
78717   if( db->mallocFailed ) goto exit_begin_add_column;
78718   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78719   if( !pTab ) goto exit_begin_add_column;
78720
78721 #ifndef SQLITE_OMIT_VIRTUALTABLE
78722   if( IsVirtual(pTab) ){
78723     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
78724     goto exit_begin_add_column;
78725   }
78726 #endif
78727
78728   /* Make sure this is not an attempt to ALTER a view. */
78729   if( pTab->pSelect ){
78730     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
78731     goto exit_begin_add_column;
78732   }
78733   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78734     goto exit_begin_add_column;
78735   }
78736
78737   assert( pTab->addColOffset>0 );
78738   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78739
78740   /* Put a copy of the Table struct in Parse.pNewTable for the
78741   ** sqlite3AddColumn() function and friends to modify.  But modify
78742   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
78743   ** prefix, we insure that the name will not collide with an existing
78744   ** table because user table are not allowed to have the "sqlite_"
78745   ** prefix on their name.
78746   */
78747   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
78748   if( !pNew ) goto exit_begin_add_column;
78749   pParse->pNewTable = pNew;
78750   pNew->nRef = 1;
78751   pNew->nCol = pTab->nCol;
78752   assert( pNew->nCol>0 );
78753   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78754   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78755   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
78756   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
78757   if( !pNew->aCol || !pNew->zName ){
78758     db->mallocFailed = 1;
78759     goto exit_begin_add_column;
78760   }
78761   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78762   for(i=0; i<pNew->nCol; i++){
78763     Column *pCol = &pNew->aCol[i];
78764     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
78765     pCol->zColl = 0;
78766     pCol->zType = 0;
78767     pCol->pDflt = 0;
78768     pCol->zDflt = 0;
78769   }
78770   pNew->pSchema = db->aDb[iDb].pSchema;
78771   pNew->addColOffset = pTab->addColOffset;
78772   pNew->nRef = 1;
78773
78774   /* Begin a transaction and increment the schema cookie.  */
78775   sqlite3BeginWriteOperation(pParse, 0, iDb);
78776   v = sqlite3GetVdbe(pParse);
78777   if( !v ) goto exit_begin_add_column;
78778   sqlite3ChangeCookie(pParse, iDb);
78779
78780 exit_begin_add_column:
78781   sqlite3SrcListDelete(db, pSrc);
78782   return;
78783 }
78784 #endif  /* SQLITE_ALTER_TABLE */
78785
78786 /************** End of alter.c ***********************************************/
78787 /************** Begin file analyze.c *****************************************/
78788 /*
78789 ** 2005 July 8
78790 **
78791 ** The author disclaims copyright to this source code.  In place of
78792 ** a legal notice, here is a blessing:
78793 **
78794 **    May you do good and not evil.
78795 **    May you find forgiveness for yourself and forgive others.
78796 **    May you share freely, never taking more than you give.
78797 **
78798 *************************************************************************
78799 ** This file contains code associated with the ANALYZE command.
78800 **
78801 ** The ANALYZE command gather statistics about the content of tables
78802 ** and indices.  These statistics are made available to the query planner
78803 ** to help it make better decisions about how to perform queries.
78804 **
78805 ** The following system tables are or have been supported:
78806 **
78807 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
78808 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
78809 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
78810 **
78811 ** Additional tables might be added in future releases of SQLite.
78812 ** The sqlite_stat2 table is not created or used unless the SQLite version
78813 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
78814 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
78815 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
78816 ** created and used by SQLite versions 3.7.9 and later and with
78817 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
78818 ** is a superset of sqlite_stat2.  
78819 **
78820 ** Format of sqlite_stat1:
78821 **
78822 ** There is normally one row per index, with the index identified by the
78823 ** name in the idx column.  The tbl column is the name of the table to
78824 ** which the index belongs.  In each such row, the stat column will be
78825 ** a string consisting of a list of integers.  The first integer in this
78826 ** list is the number of rows in the index and in the table.  The second
78827 ** integer is the average number of rows in the index that have the same
78828 ** value in the first column of the index.  The third integer is the average
78829 ** number of rows in the index that have the same value for the first two
78830 ** columns.  The N-th integer (for N>1) is the average number of rows in 
78831 ** the index which have the same value for the first N-1 columns.  For
78832 ** a K-column index, there will be K+1 integers in the stat column.  If
78833 ** the index is unique, then the last integer will be 1.
78834 **
78835 ** The list of integers in the stat column can optionally be followed
78836 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
78837 ** must be separated from the last integer by a single space.  If the
78838 ** "unordered" keyword is present, then the query planner assumes that
78839 ** the index is unordered and will not use the index for a range query.
78840 ** 
78841 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
78842 ** column contains a single integer which is the (estimated) number of
78843 ** rows in the table identified by sqlite_stat1.tbl.
78844 **
78845 ** Format of sqlite_stat2:
78846 **
78847 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
78848 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
78849 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
78850 ** about the distribution of keys within an index.  The index is identified by
78851 ** the "idx" column and the "tbl" column is the name of the table to which
78852 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
78853 ** table for each index.
78854 **
78855 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
78856 ** inclusive are samples of the left-most key value in the index taken at
78857 ** evenly spaced points along the index.  Let the number of samples be S
78858 ** (10 in the standard build) and let C be the number of rows in the index.
78859 ** Then the sampled rows are given by:
78860 **
78861 **     rownumber = (i*C*2 + C)/(S*2)
78862 **
78863 ** For i between 0 and S-1.  Conceptually, the index space is divided into
78864 ** S uniform buckets and the samples are the middle row from each bucket.
78865 **
78866 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
78867 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
78868 ** writes the sqlite_stat2 table.  This version of SQLite only supports
78869 ** sqlite_stat3.
78870 **
78871 ** Format for sqlite_stat3:
78872 **
78873 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
78874 ** used to avoid compatibility problems.  
78875 **
78876 ** The format of the sqlite_stat3 table is similar to the format of
78877 ** the sqlite_stat2 table.  There are multiple entries for each index.
78878 ** The idx column names the index and the tbl column is the table of the
78879 ** index.  If the idx and tbl columns are the same, then the sample is
78880 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
78881 ** the left-most column of the index.  The nEq column is the approximate
78882 ** number of entires in the index whose left-most column exactly matches
78883 ** the sample.  nLt is the approximate number of entires whose left-most
78884 ** column is less than the sample.  The nDLt column is the approximate
78885 ** number of distinct left-most entries in the index that are less than
78886 ** the sample.
78887 **
78888 ** Future versions of SQLite might change to store a string containing
78889 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
78890 ** integer will be the number of prior index entires that are distinct in
78891 ** the left-most column.  The second integer will be the number of prior index
78892 ** entries that are distinct in the first two columns.  The third integer
78893 ** will be the number of prior index entries that are distinct in the first
78894 ** three columns.  And so forth.  With that extension, the nDLt field is
78895 ** similar in function to the sqlite_stat1.stat field.
78896 **
78897 ** There can be an arbitrary number of sqlite_stat3 entries per index.
78898 ** The ANALYZE command will typically generate sqlite_stat3 tables
78899 ** that contain between 10 and 40 samples which are distributed across
78900 ** the key space, though not uniformly, and which include samples with
78901 ** largest possible nEq values.
78902 */
78903 #ifndef SQLITE_OMIT_ANALYZE
78904
78905 /*
78906 ** This routine generates code that opens the sqlite_stat1 table for
78907 ** writing with cursor iStatCur. If the library was built with the
78908 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
78909 ** opened for writing using cursor (iStatCur+1)
78910 **
78911 ** If the sqlite_stat1 tables does not previously exist, it is created.
78912 ** Similarly, if the sqlite_stat3 table does not exist and the library
78913 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. 
78914 **
78915 ** Argument zWhere may be a pointer to a buffer containing a table name,
78916 ** or it may be a NULL pointer. If it is not NULL, then all entries in
78917 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
78918 ** with the named table are deleted. If zWhere==0, then code is generated
78919 ** to delete all stat table entries.
78920 */
78921 static void openStatTable(
78922   Parse *pParse,          /* Parsing context */
78923   int iDb,                /* The database we are looking in */
78924   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
78925   const char *zWhere,     /* Delete entries for this table or index */
78926   const char *zWhereType  /* Either "tbl" or "idx" */
78927 ){
78928   static const struct {
78929     const char *zName;
78930     const char *zCols;
78931   } aTable[] = {
78932     { "sqlite_stat1", "tbl,idx,stat" },
78933 #ifdef SQLITE_ENABLE_STAT3
78934     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
78935 #endif
78936   };
78937
78938   int aRoot[] = {0, 0};
78939   u8 aCreateTbl[] = {0, 0};
78940
78941   int i;
78942   sqlite3 *db = pParse->db;
78943   Db *pDb;
78944   Vdbe *v = sqlite3GetVdbe(pParse);
78945   if( v==0 ) return;
78946   assert( sqlite3BtreeHoldsAllMutexes(db) );
78947   assert( sqlite3VdbeDb(v)==db );
78948   pDb = &db->aDb[iDb];
78949
78950   /* Create new statistic tables if they do not exist, or clear them
78951   ** if they do already exist.
78952   */
78953   for(i=0; i<ArraySize(aTable); i++){
78954     const char *zTab = aTable[i].zName;
78955     Table *pStat;
78956     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
78957       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
78958       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
78959       ** of the new table in register pParse->regRoot. This is important 
78960       ** because the OpenWrite opcode below will be needing it. */
78961       sqlite3NestedParse(pParse,
78962           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
78963       );
78964       aRoot[i] = pParse->regRoot;
78965       aCreateTbl[i] = OPFLAG_P2ISREG;
78966     }else{
78967       /* The table already exists. If zWhere is not NULL, delete all entries 
78968       ** associated with the table zWhere. If zWhere is NULL, delete the
78969       ** entire contents of the table. */
78970       aRoot[i] = pStat->tnum;
78971       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
78972       if( zWhere ){
78973         sqlite3NestedParse(pParse,
78974            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
78975         );
78976       }else{
78977         /* The sqlite_stat[12] table already exists.  Delete all rows. */
78978         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
78979       }
78980     }
78981   }
78982
78983   /* Open the sqlite_stat[13] tables for writing. */
78984   for(i=0; i<ArraySize(aTable); i++){
78985     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
78986     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
78987     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
78988   }
78989 }
78990
78991 /*
78992 ** Recommended number of samples for sqlite_stat3
78993 */
78994 #ifndef SQLITE_STAT3_SAMPLES
78995 # define SQLITE_STAT3_SAMPLES 24
78996 #endif
78997
78998 /*
78999 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79000 ** share an instance of the following structure to hold their state
79001 ** information.
79002 */
79003 typedef struct Stat3Accum Stat3Accum;
79004 struct Stat3Accum {
79005   tRowcnt nRow;             /* Number of rows in the entire table */
79006   tRowcnt nPSample;         /* How often to do a periodic sample */
79007   int iMin;                 /* Index of entry with minimum nEq and hash */
79008   int mxSample;             /* Maximum number of samples to accumulate */
79009   int nSample;              /* Current number of samples */
79010   u32 iPrn;                 /* Pseudo-random number used for sampling */
79011   struct Stat3Sample {
79012     i64 iRowid;                /* Rowid in main table of the key */
79013     tRowcnt nEq;               /* sqlite_stat3.nEq */
79014     tRowcnt nLt;               /* sqlite_stat3.nLt */
79015     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
79016     u8 isPSample;              /* True if a periodic sample */
79017     u32 iHash;                 /* Tiebreaker hash */
79018   } *a;                     /* An array of samples */
79019 };
79020
79021 #ifdef SQLITE_ENABLE_STAT3
79022 /*
79023 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79024 ** are the number of rows in the table or index (C) and the number of samples
79025 ** to accumulate (S).
79026 **
79027 ** This routine allocates the Stat3Accum object.
79028 **
79029 ** The return value is the Stat3Accum object (P).
79030 */
79031 static void stat3Init(
79032   sqlite3_context *context,
79033   int argc,
79034   sqlite3_value **argv
79035 ){
79036   Stat3Accum *p;
79037   tRowcnt nRow;
79038   int mxSample;
79039   int n;
79040
79041   UNUSED_PARAMETER(argc);
79042   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
79043   mxSample = sqlite3_value_int(argv[1]);
79044   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79045   p = sqlite3MallocZero( n );
79046   if( p==0 ){
79047     sqlite3_result_error_nomem(context);
79048     return;
79049   }
79050   p->a = (struct Stat3Sample*)&p[1];
79051   p->nRow = nRow;
79052   p->mxSample = mxSample;
79053   p->nPSample = p->nRow/(mxSample/3+1) + 1;
79054   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
79055   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
79056 }
79057 static const FuncDef stat3InitFuncdef = {
79058   2,                /* nArg */
79059   SQLITE_UTF8,      /* iPrefEnc */
79060   0,                /* flags */
79061   0,                /* pUserData */
79062   0,                /* pNext */
79063   stat3Init,        /* xFunc */
79064   0,                /* xStep */
79065   0,                /* xFinalize */
79066   "stat3_init",     /* zName */
79067   0,                /* pHash */
79068   0                 /* pDestructor */
79069 };
79070
79071
79072 /*
79073 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79074 ** arguments describe a single key instance.  This routine makes the 
79075 ** decision about whether or not to retain this key for the sqlite_stat3
79076 ** table.
79077 **
79078 ** The return value is NULL.
79079 */
79080 static void stat3Push(
79081   sqlite3_context *context,
79082   int argc,
79083   sqlite3_value **argv
79084 ){
79085   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
79086   tRowcnt nEq = sqlite3_value_int64(argv[0]);
79087   tRowcnt nLt = sqlite3_value_int64(argv[1]);
79088   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
79089   i64 rowid = sqlite3_value_int64(argv[3]);
79090   u8 isPSample = 0;
79091   u8 doInsert = 0;
79092   int iMin = p->iMin;
79093   struct Stat3Sample *pSample;
79094   int i;
79095   u32 h;
79096
79097   UNUSED_PARAMETER(context);
79098   UNUSED_PARAMETER(argc);
79099   if( nEq==0 ) return;
79100   h = p->iPrn = p->iPrn*1103515245 + 12345;
79101   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79102     doInsert = isPSample = 1;
79103   }else if( p->nSample<p->mxSample ){
79104     doInsert = 1;
79105   }else{
79106     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79107       doInsert = 1;
79108     }
79109   }
79110   if( !doInsert ) return;
79111   if( p->nSample==p->mxSample ){
79112     assert( p->nSample - iMin - 1 >= 0 );
79113     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79114     pSample = &p->a[p->nSample-1];
79115   }else{
79116     pSample = &p->a[p->nSample++];
79117   }
79118   pSample->iRowid = rowid;
79119   pSample->nEq = nEq;
79120   pSample->nLt = nLt;
79121   pSample->nDLt = nDLt;
79122   pSample->iHash = h;
79123   pSample->isPSample = isPSample;
79124
79125   /* Find the new minimum */
79126   if( p->nSample==p->mxSample ){
79127     pSample = p->a;
79128     i = 0;
79129     while( pSample->isPSample ){
79130       i++;
79131       pSample++;
79132       assert( i<p->nSample );
79133     }
79134     nEq = pSample->nEq;
79135     h = pSample->iHash;
79136     iMin = i;
79137     for(i++, pSample++; i<p->nSample; i++, pSample++){
79138       if( pSample->isPSample ) continue;
79139       if( pSample->nEq<nEq
79140        || (pSample->nEq==nEq && pSample->iHash<h)
79141       ){
79142         iMin = i;
79143         nEq = pSample->nEq;
79144         h = pSample->iHash;
79145       }
79146     }
79147     p->iMin = iMin;
79148   }
79149 }
79150 static const FuncDef stat3PushFuncdef = {
79151   5,                /* nArg */
79152   SQLITE_UTF8,      /* iPrefEnc */
79153   0,                /* flags */
79154   0,                /* pUserData */
79155   0,                /* pNext */
79156   stat3Push,        /* xFunc */
79157   0,                /* xStep */
79158   0,                /* xFinalize */
79159   "stat3_push",     /* zName */
79160   0,                /* pHash */
79161   0                 /* pDestructor */
79162 };
79163
79164 /*
79165 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79166 ** used to query the results.  Content is returned for the Nth sqlite_stat3
79167 ** row where N is between 0 and S-1 and S is the number of samples.  The
79168 ** value returned depends on the number of arguments.
79169 **
79170 **   argc==2    result:  rowid
79171 **   argc==3    result:  nEq
79172 **   argc==4    result:  nLt
79173 **   argc==5    result:  nDLt
79174 */
79175 static void stat3Get(
79176   sqlite3_context *context,
79177   int argc,
79178   sqlite3_value **argv
79179 ){
79180   int n = sqlite3_value_int(argv[1]);
79181   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
79182
79183   assert( p!=0 );
79184   if( p->nSample<=n ) return;
79185   switch( argc ){
79186     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
79187     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
79188     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
79189     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
79190   }
79191 }
79192 static const FuncDef stat3GetFuncdef = {
79193   -1,               /* nArg */
79194   SQLITE_UTF8,      /* iPrefEnc */
79195   0,                /* flags */
79196   0,                /* pUserData */
79197   0,                /* pNext */
79198   stat3Get,         /* xFunc */
79199   0,                /* xStep */
79200   0,                /* xFinalize */
79201   "stat3_get",     /* zName */
79202   0,                /* pHash */
79203   0                 /* pDestructor */
79204 };
79205 #endif /* SQLITE_ENABLE_STAT3 */
79206
79207
79208
79209
79210 /*
79211 ** Generate code to do an analysis of all indices associated with
79212 ** a single table.
79213 */
79214 static void analyzeOneTable(
79215   Parse *pParse,   /* Parser context */
79216   Table *pTab,     /* Table whose indices are to be analyzed */
79217   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79218   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
79219   int iMem         /* Available memory locations begin here */
79220 ){
79221   sqlite3 *db = pParse->db;    /* Database handle */
79222   Index *pIdx;                 /* An index to being analyzed */
79223   int iIdxCur;                 /* Cursor open on index being analyzed */
79224   Vdbe *v;                     /* The virtual machine being built up */
79225   int i;                       /* Loop counter */
79226   int topOfLoop;               /* The top of the loop */
79227   int endOfLoop;               /* The end of the loop */
79228   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79229   int iDb;                     /* Index of database containing pTab */
79230   int regTabname = iMem++;     /* Register containing table name */
79231   int regIdxname = iMem++;     /* Register containing index name */
79232   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
79233 #ifdef SQLITE_ENABLE_STAT3
79234   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79235   int regNumLt = iMem++;       /* Number of keys less than regSample */
79236   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79237   int regSample = iMem++;      /* The next sample value */
79238   int regRowid = regSample;    /* Rowid of a sample */
79239   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79240   int regLoop = iMem++;        /* Loop counter */
79241   int regCount = iMem++;       /* Number of rows in the table or index */
79242   int regTemp1 = iMem++;       /* Intermediate register */
79243   int regTemp2 = iMem++;       /* Intermediate register */
79244   int once = 1;                /* One-time initialization */
79245   int shortJump = 0;           /* Instruction address */
79246   int iTabCur = pParse->nTab++; /* Table cursor */
79247 #endif
79248   int regCol = iMem++;         /* Content of a column in analyzed table */
79249   int regRec = iMem++;         /* Register holding completed record */
79250   int regTemp = iMem++;        /* Temporary use register */
79251   int regNewRowid = iMem++;    /* Rowid for the inserted record */
79252
79253
79254   v = sqlite3GetVdbe(pParse);
79255   if( v==0 || NEVER(pTab==0) ){
79256     return;
79257   }
79258   if( pTab->tnum==0 ){
79259     /* Do not gather statistics on views or virtual tables */
79260     return;
79261   }
79262   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
79263     /* Do not gather statistics on system tables */
79264     return;
79265   }
79266   assert( sqlite3BtreeHoldsAllMutexes(db) );
79267   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79268   assert( iDb>=0 );
79269   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79270 #ifndef SQLITE_OMIT_AUTHORIZATION
79271   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
79272       db->aDb[iDb].zName ) ){
79273     return;
79274   }
79275 #endif
79276
79277   /* Establish a read-lock on the table at the shared-cache level. */
79278   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79279
79280   iIdxCur = pParse->nTab++;
79281   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79282   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79283     int nCol;
79284     KeyInfo *pKey;
79285     int addrIfNot = 0;           /* address of OP_IfNot */
79286     int *aChngAddr;              /* Array of jump instruction addresses */
79287
79288     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79289     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79290     nCol = pIdx->nColumn;
79291     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
79292     if( aChngAddr==0 ) continue;
79293     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79294     if( iMem+1+(nCol*2)>pParse->nMem ){
79295       pParse->nMem = iMem+1+(nCol*2);
79296     }
79297
79298     /* Open a cursor to the index to be analyzed. */
79299     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
79300     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79301         (char *)pKey, P4_KEYINFO_HANDOFF);
79302     VdbeComment((v, "%s", pIdx->zName));
79303
79304     /* Populate the register containing the index name. */
79305     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79306
79307 #ifdef SQLITE_ENABLE_STAT3
79308     if( once ){
79309       once = 0;
79310       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79311     }
79312     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79313     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
79314     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79315     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79316     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79317     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
79318     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79319                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
79320     sqlite3VdbeChangeP5(v, 2);
79321 #endif /* SQLITE_ENABLE_STAT3 */
79322
79323     /* The block of memory cells initialized here is used as follows.
79324     **
79325     **    iMem:                
79326     **        The total number of rows in the table.
79327     **
79328     **    iMem+1 .. iMem+nCol: 
79329     **        Number of distinct entries in index considering the 
79330     **        left-most N columns only, where N is between 1 and nCol, 
79331     **        inclusive.
79332     **
79333     **    iMem+nCol+1 .. Mem+2*nCol:  
79334     **        Previous value of indexed columns, from left to right.
79335     **
79336     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
79337     ** initialized to contain an SQL NULL.
79338     */
79339     for(i=0; i<=nCol; i++){
79340       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79341     }
79342     for(i=0; i<nCol; i++){
79343       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79344     }
79345
79346     /* Start the analysis loop. This loop runs through all the entries in
79347     ** the index b-tree.  */
79348     endOfLoop = sqlite3VdbeMakeLabel(v);
79349     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79350     topOfLoop = sqlite3VdbeCurrentAddr(v);
79351     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79352
79353     for(i=0; i<nCol; i++){
79354       CollSeq *pColl;
79355       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79356       if( i==0 ){
79357         /* Always record the very first row */
79358         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
79359       }
79360       assert( pIdx->azColl!=0 );
79361       assert( pIdx->azColl[i]!=0 );
79362       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
79363       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79364                                       (char*)pColl, P4_COLLSEQ);
79365       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
79366       VdbeComment((v, "jump if column %d changed", i));
79367 #ifdef SQLITE_ENABLE_STAT3
79368       if( i==0 ){
79369         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79370         VdbeComment((v, "incr repeat count"));
79371       }
79372 #endif
79373     }
79374     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79375     for(i=0; i<nCol; i++){
79376       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79377       if( i==0 ){
79378         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79379 #ifdef SQLITE_ENABLE_STAT3
79380         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79381                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
79382         sqlite3VdbeChangeP5(v, 5);
79383         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79384         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79385         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79386         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79387 #endif        
79388       }
79389       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79390       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79391     }
79392     sqlite3DbFree(db, aChngAddr);
79393
79394     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79395     sqlite3VdbeResolveLabel(v, endOfLoop);
79396
79397     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79398     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79399 #ifdef SQLITE_ENABLE_STAT3
79400     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79401                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
79402     sqlite3VdbeChangeP5(v, 5);
79403     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79404     shortJump = 
79405     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79406     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79407                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79408     sqlite3VdbeChangeP5(v, 2);
79409     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
79410     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79411     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79412     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79413     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79414                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79415     sqlite3VdbeChangeP5(v, 3);
79416     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79417                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79418     sqlite3VdbeChangeP5(v, 4);
79419     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79420                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79421     sqlite3VdbeChangeP5(v, 5);
79422     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79423     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79424     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79425     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79426     sqlite3VdbeJumpHere(v, shortJump+2);
79427 #endif        
79428
79429     /* Store the results in sqlite_stat1.
79430     **
79431     ** The result is a single row of the sqlite_stat1 table.  The first
79432     ** two columns are the names of the table and index.  The third column
79433     ** is a string composed of a list of integer statistics about the
79434     ** index.  The first integer in the list is the total number of entries
79435     ** in the index.  There is one additional integer in the list for each
79436     ** column of the table.  This additional integer is a guess of how many
79437     ** rows of the table the index will select.  If D is the count of distinct
79438     ** values and K is the total number of rows, then the integer is computed
79439     ** as:
79440     **
79441     **        I = (K+D-1)/D
79442     **
79443     ** If K==0 then no entry is made into the sqlite_stat1 table.  
79444     ** If K>0 then it is always the case the D>0 so division by zero
79445     ** is never possible.
79446     */
79447     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79448     if( jZeroRows<0 ){
79449       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
79450     }
79451     for(i=0; i<nCol; i++){
79452       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79453       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79454       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79455       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79456       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79457       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
79458       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79459     }
79460     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79461     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79462     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79463     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79464   }
79465
79466   /* If the table has no indices, create a single sqlite_stat1 entry
79467   ** containing NULL as the index name and the row count as the content.
79468   */
79469   if( pTab->pIndex==0 ){
79470     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79471     VdbeComment((v, "%s", pTab->zName));
79472     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79473     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79474     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
79475   }else{
79476     sqlite3VdbeJumpHere(v, jZeroRows);
79477     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
79478   }
79479   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79480   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79481   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79482   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79483   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79484   if( pParse->nMem<regRec ) pParse->nMem = regRec;
79485   sqlite3VdbeJumpHere(v, jZeroRows);
79486 }
79487
79488
79489 /*
79490 ** Generate code that will cause the most recent index analysis to
79491 ** be loaded into internal hash tables where is can be used.
79492 */
79493 static void loadAnalysis(Parse *pParse, int iDb){
79494   Vdbe *v = sqlite3GetVdbe(pParse);
79495   if( v ){
79496     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79497   }
79498 }
79499
79500 /*
79501 ** Generate code that will do an analysis of an entire database
79502 */
79503 static void analyzeDatabase(Parse *pParse, int iDb){
79504   sqlite3 *db = pParse->db;
79505   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79506   HashElem *k;
79507   int iStatCur;
79508   int iMem;
79509
79510   sqlite3BeginWriteOperation(pParse, 0, iDb);
79511   iStatCur = pParse->nTab;
79512   pParse->nTab += 3;
79513   openStatTable(pParse, iDb, iStatCur, 0, 0);
79514   iMem = pParse->nMem+1;
79515   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79516   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
79517     Table *pTab = (Table*)sqliteHashData(k);
79518     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79519   }
79520   loadAnalysis(pParse, iDb);
79521 }
79522
79523 /*
79524 ** Generate code that will do an analysis of a single table in
79525 ** a database.  If pOnlyIdx is not NULL then it is a single index
79526 ** in pTab that should be analyzed.
79527 */
79528 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
79529   int iDb;
79530   int iStatCur;
79531
79532   assert( pTab!=0 );
79533   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79534   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79535   sqlite3BeginWriteOperation(pParse, 0, iDb);
79536   iStatCur = pParse->nTab;
79537   pParse->nTab += 3;
79538   if( pOnlyIdx ){
79539     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
79540   }else{
79541     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
79542   }
79543   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
79544   loadAnalysis(pParse, iDb);
79545 }
79546
79547 /*
79548 ** Generate code for the ANALYZE command.  The parser calls this routine
79549 ** when it recognizes an ANALYZE command.
79550 **
79551 **        ANALYZE                            -- 1
79552 **        ANALYZE  <database>                -- 2
79553 **        ANALYZE  ?<database>.?<tablename>  -- 3
79554 **
79555 ** Form 1 causes all indices in all attached databases to be analyzed.
79556 ** Form 2 analyzes all indices the single database named.
79557 ** Form 3 analyzes all indices associated with the named table.
79558 */
79559 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
79560   sqlite3 *db = pParse->db;
79561   int iDb;
79562   int i;
79563   char *z, *zDb;
79564   Table *pTab;
79565   Index *pIdx;
79566   Token *pTableName;
79567
79568   /* Read the database schema. If an error occurs, leave an error message
79569   ** and code in pParse and return NULL. */
79570   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79571   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79572     return;
79573   }
79574
79575   assert( pName2!=0 || pName1==0 );
79576   if( pName1==0 ){
79577     /* Form 1:  Analyze everything */
79578     for(i=0; i<db->nDb; i++){
79579       if( i==1 ) continue;  /* Do not analyze the TEMP database */
79580       analyzeDatabase(pParse, i);
79581     }
79582   }else if( pName2->n==0 ){
79583     /* Form 2:  Analyze the database or table named */
79584     iDb = sqlite3FindDb(db, pName1);
79585     if( iDb>=0 ){
79586       analyzeDatabase(pParse, iDb);
79587     }else{
79588       z = sqlite3NameFromToken(db, pName1);
79589       if( z ){
79590         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
79591           analyzeTable(pParse, pIdx->pTable, pIdx);
79592         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
79593           analyzeTable(pParse, pTab, 0);
79594         }
79595         sqlite3DbFree(db, z);
79596       }
79597     }
79598   }else{
79599     /* Form 3: Analyze the fully qualified table name */
79600     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
79601     if( iDb>=0 ){
79602       zDb = db->aDb[iDb].zName;
79603       z = sqlite3NameFromToken(db, pTableName);
79604       if( z ){
79605         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
79606           analyzeTable(pParse, pIdx->pTable, pIdx);
79607         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
79608           analyzeTable(pParse, pTab, 0);
79609         }
79610         sqlite3DbFree(db, z);
79611       }
79612     }   
79613   }
79614 }
79615
79616 /*
79617 ** Used to pass information from the analyzer reader through to the
79618 ** callback routine.
79619 */
79620 typedef struct analysisInfo analysisInfo;
79621 struct analysisInfo {
79622   sqlite3 *db;
79623   const char *zDatabase;
79624 };
79625
79626 /*
79627 ** This callback is invoked once for each index when reading the
79628 ** sqlite_stat1 table.  
79629 **
79630 **     argv[0] = name of the table
79631 **     argv[1] = name of the index (might be NULL)
79632 **     argv[2] = results of analysis - on integer for each column
79633 **
79634 ** Entries for which argv[1]==NULL simply record the number of rows in
79635 ** the table.
79636 */
79637 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79638   analysisInfo *pInfo = (analysisInfo*)pData;
79639   Index *pIndex;
79640   Table *pTable;
79641   int i, c, n;
79642   tRowcnt v;
79643   const char *z;
79644
79645   assert( argc==3 );
79646   UNUSED_PARAMETER2(NotUsed, argc);
79647
79648   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79649     return 0;
79650   }
79651   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79652   if( pTable==0 ){
79653     return 0;
79654   }
79655   if( argv[1] ){
79656     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79657   }else{
79658     pIndex = 0;
79659   }
79660   n = pIndex ? pIndex->nColumn : 0;
79661   z = argv[2];
79662   for(i=0; *z && i<=n; i++){
79663     v = 0;
79664     while( (c=z[0])>='0' && c<='9' ){
79665       v = v*10 + c - '0';
79666       z++;
79667     }
79668     if( i==0 ) pTable->nRowEst = v;
79669     if( pIndex==0 ) break;
79670     pIndex->aiRowEst[i] = v;
79671     if( *z==' ' ) z++;
79672     if( memcmp(z, "unordered", 10)==0 ){
79673       pIndex->bUnordered = 1;
79674       break;
79675     }
79676   }
79677   return 0;
79678 }
79679
79680 /*
79681 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79682 ** and its contents.
79683 */
79684 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
79685 #ifdef SQLITE_ENABLE_STAT3
79686   if( pIdx->aSample ){
79687     int j;
79688     for(j=0; j<pIdx->nSample; j++){
79689       IndexSample *p = &pIdx->aSample[j];
79690       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
79691         sqlite3DbFree(db, p->u.z);
79692       }
79693     }
79694     sqlite3DbFree(db, pIdx->aSample);
79695   }
79696   if( db && db->pnBytesFreed==0 ){
79697     pIdx->nSample = 0;
79698     pIdx->aSample = 0;
79699   }
79700 #else
79701   UNUSED_PARAMETER(db);
79702   UNUSED_PARAMETER(pIdx);
79703 #endif
79704 }
79705
79706 #ifdef SQLITE_ENABLE_STAT3
79707 /*
79708 ** Load content from the sqlite_stat3 table into the Index.aSample[]
79709 ** arrays of all indices.
79710 */
79711 static int loadStat3(sqlite3 *db, const char *zDb){
79712   int rc;                       /* Result codes from subroutines */
79713   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
79714   char *zSql;                   /* Text of the SQL statement */
79715   Index *pPrevIdx = 0;          /* Previous index in the loop */
79716   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79717   int eType;                    /* Datatype of a sample */
79718   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79719
79720   assert( db->lookaside.bEnabled==0 );
79721   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
79722     return SQLITE_OK;
79723   }
79724
79725   zSql = sqlite3MPrintf(db, 
79726       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
79727       " GROUP BY idx", zDb);
79728   if( !zSql ){
79729     return SQLITE_NOMEM;
79730   }
79731   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79732   sqlite3DbFree(db, zSql);
79733   if( rc ) return rc;
79734
79735   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79736     char *zIndex;   /* Index name */
79737     Index *pIdx;    /* Pointer to the index object */
79738     int nSample;    /* Number of samples */
79739
79740     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79741     if( zIndex==0 ) continue;
79742     nSample = sqlite3_column_int(pStmt, 1);
79743     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79744     if( pIdx==0 ) continue;
79745     assert( pIdx->nSample==0 );
79746     pIdx->nSample = nSample;
79747     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
79748     pIdx->avgEq = pIdx->aiRowEst[1];
79749     if( pIdx->aSample==0 ){
79750       db->mallocFailed = 1;
79751       sqlite3_finalize(pStmt);
79752       return SQLITE_NOMEM;
79753     }
79754   }
79755   rc = sqlite3_finalize(pStmt);
79756   if( rc ) return rc;
79757
79758   zSql = sqlite3MPrintf(db, 
79759       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
79760   if( !zSql ){
79761     return SQLITE_NOMEM;
79762   }
79763   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79764   sqlite3DbFree(db, zSql);
79765   if( rc ) return rc;
79766
79767   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79768     char *zIndex;   /* Index name */
79769     Index *pIdx;    /* Pointer to the index object */
79770     int i;          /* Loop counter */
79771     tRowcnt sumEq;  /* Sum of the nEq values */
79772
79773     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79774     if( zIndex==0 ) continue;
79775     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79776     if( pIdx==0 ) continue;
79777     if( pIdx==pPrevIdx ){
79778       idx++;
79779     }else{
79780       pPrevIdx = pIdx;
79781       idx = 0;
79782     }
79783     assert( idx<pIdx->nSample );
79784     pSample = &pIdx->aSample[idx];
79785     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
79786     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
79787     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
79788     if( idx==pIdx->nSample-1 ){
79789       if( pSample->nDLt>0 ){
79790         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
79791         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
79792       }
79793       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
79794     }
79795     eType = sqlite3_column_type(pStmt, 4);
79796     pSample->eType = (u8)eType;
79797     switch( eType ){
79798       case SQLITE_INTEGER: {
79799         pSample->u.i = sqlite3_column_int64(pStmt, 4);
79800         break;
79801       }
79802       case SQLITE_FLOAT: {
79803         pSample->u.r = sqlite3_column_double(pStmt, 4);
79804         break;
79805       }
79806       case SQLITE_NULL: {
79807         break;
79808       }
79809       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
79810         const char *z = (const char *)(
79811               (eType==SQLITE_BLOB) ?
79812               sqlite3_column_blob(pStmt, 4):
79813               sqlite3_column_text(pStmt, 4)
79814            );
79815         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
79816         pSample->nByte = n;
79817         if( n < 1){
79818           pSample->u.z = 0;
79819         }else{
79820           pSample->u.z = sqlite3DbMallocRaw(db, n);
79821           if( pSample->u.z==0 ){
79822             db->mallocFailed = 1;
79823             sqlite3_finalize(pStmt);
79824             return SQLITE_NOMEM;
79825           }
79826           memcpy(pSample->u.z, z, n);
79827         }
79828       }
79829     }
79830   }
79831   return sqlite3_finalize(pStmt);
79832 }
79833 #endif /* SQLITE_ENABLE_STAT3 */
79834
79835 /*
79836 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
79837 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
79838 ** arrays. The contents of sqlite_stat3 are used to populate the
79839 ** Index.aSample[] arrays.
79840 **
79841 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
79842 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined 
79843 ** during compilation and the sqlite_stat3 table is present, no data is 
79844 ** read from it.
79845 **
79846 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the 
79847 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
79848 ** returned. However, in this case, data is read from the sqlite_stat1
79849 ** table (if it is present) before returning.
79850 **
79851 ** If an OOM error occurs, this function always sets db->mallocFailed.
79852 ** This means if the caller does not care about other errors, the return
79853 ** code may be ignored.
79854 */
79855 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
79856   analysisInfo sInfo;
79857   HashElem *i;
79858   char *zSql;
79859   int rc;
79860
79861   assert( iDb>=0 && iDb<db->nDb );
79862   assert( db->aDb[iDb].pBt!=0 );
79863
79864   /* Clear any prior statistics */
79865   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79866   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
79867     Index *pIdx = sqliteHashData(i);
79868     sqlite3DefaultRowEst(pIdx);
79869 #ifdef SQLITE_ENABLE_STAT3
79870     sqlite3DeleteIndexSamples(db, pIdx);
79871     pIdx->aSample = 0;
79872 #endif
79873   }
79874
79875   /* Check to make sure the sqlite_stat1 table exists */
79876   sInfo.db = db;
79877   sInfo.zDatabase = db->aDb[iDb].zName;
79878   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
79879     return SQLITE_ERROR;
79880   }
79881
79882   /* Load new statistics out of the sqlite_stat1 table */
79883   zSql = sqlite3MPrintf(db, 
79884       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
79885   if( zSql==0 ){
79886     rc = SQLITE_NOMEM;
79887   }else{
79888     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
79889     sqlite3DbFree(db, zSql);
79890   }
79891
79892
79893   /* Load the statistics from the sqlite_stat3 table. */
79894 #ifdef SQLITE_ENABLE_STAT3
79895   if( rc==SQLITE_OK ){
79896     int lookasideEnabled = db->lookaside.bEnabled;
79897     db->lookaside.bEnabled = 0;
79898     rc = loadStat3(db, sInfo.zDatabase);
79899     db->lookaside.bEnabled = lookasideEnabled;
79900   }
79901 #endif
79902
79903   if( rc==SQLITE_NOMEM ){
79904     db->mallocFailed = 1;
79905   }
79906   return rc;
79907 }
79908
79909
79910 #endif /* SQLITE_OMIT_ANALYZE */
79911
79912 /************** End of analyze.c *********************************************/
79913 /************** Begin file attach.c ******************************************/
79914 /*
79915 ** 2003 April 6
79916 **
79917 ** The author disclaims copyright to this source code.  In place of
79918 ** a legal notice, here is a blessing:
79919 **
79920 **    May you do good and not evil.
79921 **    May you find forgiveness for yourself and forgive others.
79922 **    May you share freely, never taking more than you give.
79923 **
79924 *************************************************************************
79925 ** This file contains code used to implement the ATTACH and DETACH commands.
79926 */
79927
79928 #ifndef SQLITE_OMIT_ATTACH
79929 /*
79930 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
79931 ** is slightly different from resolving a normal SQL expression, because simple
79932 ** identifiers are treated as strings, not possible column names or aliases.
79933 **
79934 ** i.e. if the parser sees:
79935 **
79936 **     ATTACH DATABASE abc AS def
79937 **
79938 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
79939 ** looking for columns of the same name.
79940 **
79941 ** This only applies to the root node of pExpr, so the statement:
79942 **
79943 **     ATTACH DATABASE abc||def AS 'db2'
79944 **
79945 ** will fail because neither abc or def can be resolved.
79946 */
79947 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
79948 {
79949   int rc = SQLITE_OK;
79950   if( pExpr ){
79951     if( pExpr->op!=TK_ID ){
79952       rc = sqlite3ResolveExprNames(pName, pExpr);
79953       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
79954         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
79955         return SQLITE_ERROR;
79956       }
79957     }else{
79958       pExpr->op = TK_STRING;
79959     }
79960   }
79961   return rc;
79962 }
79963
79964 /*
79965 ** An SQL user-function registered to do the work of an ATTACH statement. The
79966 ** three arguments to the function come directly from an attach statement:
79967 **
79968 **     ATTACH DATABASE x AS y KEY z
79969 **
79970 **     SELECT sqlite_attach(x, y, z)
79971 **
79972 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
79973 ** third argument.
79974 */
79975 static void attachFunc(
79976   sqlite3_context *context,
79977   int NotUsed,
79978   sqlite3_value **argv
79979 ){
79980   int i;
79981   int rc = 0;
79982   sqlite3 *db = sqlite3_context_db_handle(context);
79983   const char *zName;
79984   const char *zFile;
79985   char *zPath = 0;
79986   char *zErr = 0;
79987   unsigned int flags;
79988   Db *aNew;
79989   char *zErrDyn = 0;
79990   sqlite3_vfs *pVfs;
79991
79992   UNUSED_PARAMETER(NotUsed);
79993
79994   zFile = (const char *)sqlite3_value_text(argv[0]);
79995   zName = (const char *)sqlite3_value_text(argv[1]);
79996   if( zFile==0 ) zFile = "";
79997   if( zName==0 ) zName = "";
79998
79999   /* Check for the following errors:
80000   **
80001   **     * Too many attached databases,
80002   **     * Transaction currently open
80003   **     * Specified database name already being used.
80004   */
80005   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
80006     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
80007       db->aLimit[SQLITE_LIMIT_ATTACHED]
80008     );
80009     goto attach_error;
80010   }
80011   if( !db->autoCommit ){
80012     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
80013     goto attach_error;
80014   }
80015   for(i=0; i<db->nDb; i++){
80016     char *z = db->aDb[i].zName;
80017     assert( z && zName );
80018     if( sqlite3StrICmp(z, zName)==0 ){
80019       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
80020       goto attach_error;
80021     }
80022   }
80023
80024   /* Allocate the new entry in the db->aDb[] array and initialise the schema
80025   ** hash tables.
80026   */
80027   if( db->aDb==db->aDbStatic ){
80028     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80029     if( aNew==0 ) return;
80030     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80031   }else{
80032     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80033     if( aNew==0 ) return;
80034   }
80035   db->aDb = aNew;
80036   aNew = &db->aDb[db->nDb];
80037   memset(aNew, 0, sizeof(*aNew));
80038
80039   /* Open the database file. If the btree is successfully opened, use
80040   ** it to obtain the database schema. At this point the schema may
80041   ** or may not be initialised.
80042   */
80043   flags = db->openFlags;
80044   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80045   if( rc!=SQLITE_OK ){
80046     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
80047     sqlite3_result_error(context, zErr, -1);
80048     sqlite3_free(zErr);
80049     return;
80050   }
80051   assert( pVfs );
80052   flags |= SQLITE_OPEN_MAIN_DB;
80053   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80054   sqlite3_free( zPath );
80055   db->nDb++;
80056   if( rc==SQLITE_CONSTRAINT ){
80057     rc = SQLITE_ERROR;
80058     zErrDyn = sqlite3MPrintf(db, "database is already attached");
80059   }else if( rc==SQLITE_OK ){
80060     Pager *pPager;
80061     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
80062     if( !aNew->pSchema ){
80063       rc = SQLITE_NOMEM;
80064     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80065       zErrDyn = sqlite3MPrintf(db, 
80066         "attached databases must use the same text encoding as main database");
80067       rc = SQLITE_ERROR;
80068     }
80069     pPager = sqlite3BtreePager(aNew->pBt);
80070     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
80071     sqlite3BtreeSecureDelete(aNew->pBt,
80072                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80073   }
80074   aNew->safety_level = 3;
80075   aNew->zName = sqlite3DbStrDup(db, zName);
80076   if( rc==SQLITE_OK && aNew->zName==0 ){
80077     rc = SQLITE_NOMEM;
80078   }
80079
80080
80081 #ifdef SQLITE_HAS_CODEC
80082   if( rc==SQLITE_OK ){
80083     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
80084     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80085     int nKey;
80086     char *zKey;
80087     int t = sqlite3_value_type(argv[2]);
80088     switch( t ){
80089       case SQLITE_INTEGER:
80090       case SQLITE_FLOAT:
80091         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
80092         rc = SQLITE_ERROR;
80093         break;
80094         
80095       case SQLITE_TEXT:
80096       case SQLITE_BLOB:
80097         nKey = sqlite3_value_bytes(argv[2]);
80098         zKey = (char *)sqlite3_value_blob(argv[2]);
80099         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80100         break;
80101
80102       case SQLITE_NULL:
80103         /* No key specified.  Use the key from the main database */
80104         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80105         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80106           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80107         }
80108         break;
80109     }
80110   }
80111 #endif
80112
80113   /* If the file was opened successfully, read the schema for the new database.
80114   ** If this fails, or if opening the file failed, then close the file and 
80115   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80116   ** we found it.
80117   */
80118   if( rc==SQLITE_OK ){
80119     sqlite3BtreeEnterAll(db);
80120     rc = sqlite3Init(db, &zErrDyn);
80121     sqlite3BtreeLeaveAll(db);
80122   }
80123   if( rc ){
80124     int iDb = db->nDb - 1;
80125     assert( iDb>=2 );
80126     if( db->aDb[iDb].pBt ){
80127       sqlite3BtreeClose(db->aDb[iDb].pBt);
80128       db->aDb[iDb].pBt = 0;
80129       db->aDb[iDb].pSchema = 0;
80130     }
80131     sqlite3ResetAllSchemasOfConnection(db);
80132     db->nDb = iDb;
80133     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
80134       db->mallocFailed = 1;
80135       sqlite3DbFree(db, zErrDyn);
80136       zErrDyn = sqlite3MPrintf(db, "out of memory");
80137     }else if( zErrDyn==0 ){
80138       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
80139     }
80140     goto attach_error;
80141   }
80142   
80143   return;
80144
80145 attach_error:
80146   /* Return an error if we get here */
80147   if( zErrDyn ){
80148     sqlite3_result_error(context, zErrDyn, -1);
80149     sqlite3DbFree(db, zErrDyn);
80150   }
80151   if( rc ) sqlite3_result_error_code(context, rc);
80152 }
80153
80154 /*
80155 ** An SQL user-function registered to do the work of an DETACH statement. The
80156 ** three arguments to the function come directly from a detach statement:
80157 **
80158 **     DETACH DATABASE x
80159 **
80160 **     SELECT sqlite_detach(x)
80161 */
80162 static void detachFunc(
80163   sqlite3_context *context,
80164   int NotUsed,
80165   sqlite3_value **argv
80166 ){
80167   const char *zName = (const char *)sqlite3_value_text(argv[0]);
80168   sqlite3 *db = sqlite3_context_db_handle(context);
80169   int i;
80170   Db *pDb = 0;
80171   char zErr[128];
80172
80173   UNUSED_PARAMETER(NotUsed);
80174
80175   if( zName==0 ) zName = "";
80176   for(i=0; i<db->nDb; i++){
80177     pDb = &db->aDb[i];
80178     if( pDb->pBt==0 ) continue;
80179     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
80180   }
80181
80182   if( i>=db->nDb ){
80183     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80184     goto detach_error;
80185   }
80186   if( i<2 ){
80187     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80188     goto detach_error;
80189   }
80190   if( !db->autoCommit ){
80191     sqlite3_snprintf(sizeof(zErr), zErr,
80192                      "cannot DETACH database within transaction");
80193     goto detach_error;
80194   }
80195   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
80196     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80197     goto detach_error;
80198   }
80199
80200   sqlite3BtreeClose(pDb->pBt);
80201   pDb->pBt = 0;
80202   pDb->pSchema = 0;
80203   sqlite3ResetAllSchemasOfConnection(db);
80204   return;
80205
80206 detach_error:
80207   sqlite3_result_error(context, zErr, -1);
80208 }
80209
80210 /*
80211 ** This procedure generates VDBE code for a single invocation of either the
80212 ** sqlite_detach() or sqlite_attach() SQL user functions.
80213 */
80214 static void codeAttach(
80215   Parse *pParse,       /* The parser context */
80216   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
80217   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80218   Expr *pAuthArg,      /* Expression to pass to authorization callback */
80219   Expr *pFilename,     /* Name of database file */
80220   Expr *pDbname,       /* Name of the database to use internally */
80221   Expr *pKey           /* Database key for encryption extension */
80222 ){
80223   int rc;
80224   NameContext sName;
80225   Vdbe *v;
80226   sqlite3* db = pParse->db;
80227   int regArgs;
80228
80229   memset(&sName, 0, sizeof(NameContext));
80230   sName.pParse = pParse;
80231
80232   if( 
80233       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80234       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80235       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
80236   ){
80237     pParse->nErr++;
80238     goto attach_end;
80239   }
80240
80241 #ifndef SQLITE_OMIT_AUTHORIZATION
80242   if( pAuthArg ){
80243     char *zAuthArg;
80244     if( pAuthArg->op==TK_STRING ){
80245       zAuthArg = pAuthArg->u.zToken;
80246     }else{
80247       zAuthArg = 0;
80248     }
80249     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
80250     if(rc!=SQLITE_OK ){
80251       goto attach_end;
80252     }
80253   }
80254 #endif /* SQLITE_OMIT_AUTHORIZATION */
80255
80256
80257   v = sqlite3GetVdbe(pParse);
80258   regArgs = sqlite3GetTempRange(pParse, 4);
80259   sqlite3ExprCode(pParse, pFilename, regArgs);
80260   sqlite3ExprCode(pParse, pDbname, regArgs+1);
80261   sqlite3ExprCode(pParse, pKey, regArgs+2);
80262
80263   assert( v || db->mallocFailed );
80264   if( v ){
80265     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80266     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80267     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
80268     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80269
80270     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80271     ** statement only). For DETACH, set it to false (expire all existing
80272     ** statements).
80273     */
80274     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
80275   }
80276   
80277 attach_end:
80278   sqlite3ExprDelete(db, pFilename);
80279   sqlite3ExprDelete(db, pDbname);
80280   sqlite3ExprDelete(db, pKey);
80281 }
80282
80283 /*
80284 ** Called by the parser to compile a DETACH statement.
80285 **
80286 **     DETACH pDbname
80287 */
80288 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
80289   static const FuncDef detach_func = {
80290     1,                /* nArg */
80291     SQLITE_UTF8,      /* iPrefEnc */
80292     0,                /* flags */
80293     0,                /* pUserData */
80294     0,                /* pNext */
80295     detachFunc,       /* xFunc */
80296     0,                /* xStep */
80297     0,                /* xFinalize */
80298     "sqlite_detach",  /* zName */
80299     0,                /* pHash */
80300     0                 /* pDestructor */
80301   };
80302   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80303 }
80304
80305 /*
80306 ** Called by the parser to compile an ATTACH statement.
80307 **
80308 **     ATTACH p AS pDbname KEY pKey
80309 */
80310 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80311   static const FuncDef attach_func = {
80312     3,                /* nArg */
80313     SQLITE_UTF8,      /* iPrefEnc */
80314     0,                /* flags */
80315     0,                /* pUserData */
80316     0,                /* pNext */
80317     attachFunc,       /* xFunc */
80318     0,                /* xStep */
80319     0,                /* xFinalize */
80320     "sqlite_attach",  /* zName */
80321     0,                /* pHash */
80322     0                 /* pDestructor */
80323   };
80324   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
80325 }
80326 #endif /* SQLITE_OMIT_ATTACH */
80327
80328 /*
80329 ** Initialize a DbFixer structure.  This routine must be called prior
80330 ** to passing the structure to one of the sqliteFixAAAA() routines below.
80331 **
80332 ** The return value indicates whether or not fixation is required.  TRUE
80333 ** means we do need to fix the database references, FALSE means we do not.
80334 */
80335 SQLITE_PRIVATE int sqlite3FixInit(
80336   DbFixer *pFix,      /* The fixer to be initialized */
80337   Parse *pParse,      /* Error messages will be written here */
80338   int iDb,            /* This is the database that must be used */
80339   const char *zType,  /* "view", "trigger", or "index" */
80340   const Token *pName  /* Name of the view, trigger, or index */
80341 ){
80342   sqlite3 *db;
80343
80344   if( NEVER(iDb<0) || iDb==1 ) return 0;
80345   db = pParse->db;
80346   assert( db->nDb>iDb );
80347   pFix->pParse = pParse;
80348   pFix->zDb = db->aDb[iDb].zName;
80349   pFix->pSchema = db->aDb[iDb].pSchema;
80350   pFix->zType = zType;
80351   pFix->pName = pName;
80352   return 1;
80353 }
80354
80355 /*
80356 ** The following set of routines walk through the parse tree and assign
80357 ** a specific database to all table references where the database name
80358 ** was left unspecified in the original SQL statement.  The pFix structure
80359 ** must have been initialized by a prior call to sqlite3FixInit().
80360 **
80361 ** These routines are used to make sure that an index, trigger, or
80362 ** view in one database does not refer to objects in a different database.
80363 ** (Exception: indices, triggers, and views in the TEMP database are
80364 ** allowed to refer to anything.)  If a reference is explicitly made
80365 ** to an object in a different database, an error message is added to
80366 ** pParse->zErrMsg and these routines return non-zero.  If everything
80367 ** checks out, these routines return 0.
80368 */
80369 SQLITE_PRIVATE int sqlite3FixSrcList(
80370   DbFixer *pFix,       /* Context of the fixation */
80371   SrcList *pList       /* The Source list to check and modify */
80372 ){
80373   int i;
80374   const char *zDb;
80375   struct SrcList_item *pItem;
80376
80377   if( NEVER(pList==0) ) return 0;
80378   zDb = pFix->zDb;
80379   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80380     if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
80381       sqlite3ErrorMsg(pFix->pParse,
80382          "%s %T cannot reference objects in database %s",
80383          pFix->zType, pFix->pName, pItem->zDatabase);
80384       return 1;
80385     }
80386     sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
80387     pItem->zDatabase = 0;
80388     pItem->pSchema = pFix->pSchema;
80389 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80390     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
80391     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
80392 #endif
80393   }
80394   return 0;
80395 }
80396 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80397 SQLITE_PRIVATE int sqlite3FixSelect(
80398   DbFixer *pFix,       /* Context of the fixation */
80399   Select *pSelect      /* The SELECT statement to be fixed to one database */
80400 ){
80401   while( pSelect ){
80402     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
80403       return 1;
80404     }
80405     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
80406       return 1;
80407     }
80408     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
80409       return 1;
80410     }
80411     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
80412       return 1;
80413     }
80414     pSelect = pSelect->pPrior;
80415   }
80416   return 0;
80417 }
80418 SQLITE_PRIVATE int sqlite3FixExpr(
80419   DbFixer *pFix,     /* Context of the fixation */
80420   Expr *pExpr        /* The expression to be fixed to one database */
80421 ){
80422   while( pExpr ){
80423     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80424     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80425       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80426     }else{
80427       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
80428     }
80429     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
80430       return 1;
80431     }
80432     pExpr = pExpr->pLeft;
80433   }
80434   return 0;
80435 }
80436 SQLITE_PRIVATE int sqlite3FixExprList(
80437   DbFixer *pFix,     /* Context of the fixation */
80438   ExprList *pList    /* The expression to be fixed to one database */
80439 ){
80440   int i;
80441   struct ExprList_item *pItem;
80442   if( pList==0 ) return 0;
80443   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80444     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
80445       return 1;
80446     }
80447   }
80448   return 0;
80449 }
80450 #endif
80451
80452 #ifndef SQLITE_OMIT_TRIGGER
80453 SQLITE_PRIVATE int sqlite3FixTriggerStep(
80454   DbFixer *pFix,     /* Context of the fixation */
80455   TriggerStep *pStep /* The trigger step be fixed to one database */
80456 ){
80457   while( pStep ){
80458     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
80459       return 1;
80460     }
80461     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
80462       return 1;
80463     }
80464     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
80465       return 1;
80466     }
80467     pStep = pStep->pNext;
80468   }
80469   return 0;
80470 }
80471 #endif
80472
80473 /************** End of attach.c **********************************************/
80474 /************** Begin file auth.c ********************************************/
80475 /*
80476 ** 2003 January 11
80477 **
80478 ** The author disclaims copyright to this source code.  In place of
80479 ** a legal notice, here is a blessing:
80480 **
80481 **    May you do good and not evil.
80482 **    May you find forgiveness for yourself and forgive others.
80483 **    May you share freely, never taking more than you give.
80484 **
80485 *************************************************************************
80486 ** This file contains code used to implement the sqlite3_set_authorizer()
80487 ** API.  This facility is an optional feature of the library.  Embedded
80488 ** systems that do not need this facility may omit it by recompiling
80489 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
80490 */
80491
80492 /*
80493 ** All of the code in this file may be omitted by defining a single
80494 ** macro.
80495 */
80496 #ifndef SQLITE_OMIT_AUTHORIZATION
80497
80498 /*
80499 ** Set or clear the access authorization function.
80500 **
80501 ** The access authorization function is be called during the compilation
80502 ** phase to verify that the user has read and/or write access permission on
80503 ** various fields of the database.  The first argument to the auth function
80504 ** is a copy of the 3rd argument to this routine.  The second argument
80505 ** to the auth function is one of these constants:
80506 **
80507 **       SQLITE_CREATE_INDEX
80508 **       SQLITE_CREATE_TABLE
80509 **       SQLITE_CREATE_TEMP_INDEX
80510 **       SQLITE_CREATE_TEMP_TABLE
80511 **       SQLITE_CREATE_TEMP_TRIGGER
80512 **       SQLITE_CREATE_TEMP_VIEW
80513 **       SQLITE_CREATE_TRIGGER
80514 **       SQLITE_CREATE_VIEW
80515 **       SQLITE_DELETE
80516 **       SQLITE_DROP_INDEX
80517 **       SQLITE_DROP_TABLE
80518 **       SQLITE_DROP_TEMP_INDEX
80519 **       SQLITE_DROP_TEMP_TABLE
80520 **       SQLITE_DROP_TEMP_TRIGGER
80521 **       SQLITE_DROP_TEMP_VIEW
80522 **       SQLITE_DROP_TRIGGER
80523 **       SQLITE_DROP_VIEW
80524 **       SQLITE_INSERT
80525 **       SQLITE_PRAGMA
80526 **       SQLITE_READ
80527 **       SQLITE_SELECT
80528 **       SQLITE_TRANSACTION
80529 **       SQLITE_UPDATE
80530 **
80531 ** The third and fourth arguments to the auth function are the name of
80532 ** the table and the column that are being accessed.  The auth function
80533 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
80534 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
80535 ** means that the SQL statement will never-run - the sqlite3_exec() call
80536 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
80537 ** should run but attempts to read the specified column will return NULL
80538 ** and attempts to write the column will be ignored.
80539 **
80540 ** Setting the auth function to NULL disables this hook.  The default
80541 ** setting of the auth function is NULL.
80542 */
80543 SQLITE_API int sqlite3_set_authorizer(
80544   sqlite3 *db,
80545   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
80546   void *pArg
80547 ){
80548   sqlite3_mutex_enter(db->mutex);
80549   db->xAuth = xAuth;
80550   db->pAuthArg = pArg;
80551   sqlite3ExpirePreparedStatements(db);
80552   sqlite3_mutex_leave(db->mutex);
80553   return SQLITE_OK;
80554 }
80555
80556 /*
80557 ** Write an error message into pParse->zErrMsg that explains that the
80558 ** user-supplied authorization function returned an illegal value.
80559 */
80560 static void sqliteAuthBadReturnCode(Parse *pParse){
80561   sqlite3ErrorMsg(pParse, "authorizer malfunction");
80562   pParse->rc = SQLITE_ERROR;
80563 }
80564
80565 /*
80566 ** Invoke the authorization callback for permission to read column zCol from
80567 ** table zTab in database zDb. This function assumes that an authorization
80568 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
80569 **
80570 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
80571 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
80572 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
80573 */
80574 SQLITE_PRIVATE int sqlite3AuthReadCol(
80575   Parse *pParse,                  /* The parser context */
80576   const char *zTab,               /* Table name */
80577   const char *zCol,               /* Column name */
80578   int iDb                         /* Index of containing database. */
80579 ){
80580   sqlite3 *db = pParse->db;       /* Database handle */
80581   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
80582   int rc;                         /* Auth callback return code */
80583
80584   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
80585   if( rc==SQLITE_DENY ){
80586     if( db->nDb>2 || iDb!=0 ){
80587       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80588     }else{
80589       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80590     }
80591     pParse->rc = SQLITE_AUTH;
80592   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
80593     sqliteAuthBadReturnCode(pParse);
80594   }
80595   return rc;
80596 }
80597
80598 /*
80599 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80600 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
80601 ** Check to see if it is OK to read this particular column.
80602 **
80603 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
80604 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
80605 ** then generate an error.
80606 */
80607 SQLITE_PRIVATE void sqlite3AuthRead(
80608   Parse *pParse,        /* The parser context */
80609   Expr *pExpr,          /* The expression to check authorization on */
80610   Schema *pSchema,      /* The schema of the expression */
80611   SrcList *pTabList     /* All table that pExpr might refer to */
80612 ){
80613   sqlite3 *db = pParse->db;
80614   Table *pTab = 0;      /* The table being read */
80615   const char *zCol;     /* Name of the column of the table */
80616   int iSrc;             /* Index in pTabList->a[] of table being read */
80617   int iDb;              /* The index of the database the expression refers to */
80618   int iCol;             /* Index of column in table */
80619
80620   if( db->xAuth==0 ) return;
80621   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
80622   if( iDb<0 ){
80623     /* An attempt to read a column out of a subquery or other
80624     ** temporary table. */
80625     return;
80626   }
80627
80628   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80629   if( pExpr->op==TK_TRIGGER ){
80630     pTab = pParse->pTriggerTab;
80631   }else{
80632     assert( pTabList );
80633     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80634       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80635         pTab = pTabList->a[iSrc].pTab;
80636         break;
80637       }
80638     }
80639   }
80640   iCol = pExpr->iColumn;
80641   if( NEVER(pTab==0) ) return;
80642
80643   if( iCol>=0 ){
80644     assert( iCol<pTab->nCol );
80645     zCol = pTab->aCol[iCol].zName;
80646   }else if( pTab->iPKey>=0 ){
80647     assert( pTab->iPKey<pTab->nCol );
80648     zCol = pTab->aCol[pTab->iPKey].zName;
80649   }else{
80650     zCol = "ROWID";
80651   }
80652   assert( iDb>=0 && iDb<db->nDb );
80653   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80654     pExpr->op = TK_NULL;
80655   }
80656 }
80657
80658 /*
80659 ** Do an authorization check using the code and arguments given.  Return
80660 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
80661 ** is returned, then the error count and error message in pParse are
80662 ** modified appropriately.
80663 */
80664 SQLITE_PRIVATE int sqlite3AuthCheck(
80665   Parse *pParse,
80666   int code,
80667   const char *zArg1,
80668   const char *zArg2,
80669   const char *zArg3
80670 ){
80671   sqlite3 *db = pParse->db;
80672   int rc;
80673
80674   /* Don't do any authorization checks if the database is initialising
80675   ** or if the parser is being invoked from within sqlite3_declare_vtab.
80676   */
80677   if( db->init.busy || IN_DECLARE_VTAB ){
80678     return SQLITE_OK;
80679   }
80680
80681   if( db->xAuth==0 ){
80682     return SQLITE_OK;
80683   }
80684   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80685   if( rc==SQLITE_DENY ){
80686     sqlite3ErrorMsg(pParse, "not authorized");
80687     pParse->rc = SQLITE_AUTH;
80688   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
80689     rc = SQLITE_DENY;
80690     sqliteAuthBadReturnCode(pParse);
80691   }
80692   return rc;
80693 }
80694
80695 /*
80696 ** Push an authorization context.  After this routine is called, the
80697 ** zArg3 argument to authorization callbacks will be zContext until
80698 ** popped.  Or if pParse==0, this routine is a no-op.
80699 */
80700 SQLITE_PRIVATE void sqlite3AuthContextPush(
80701   Parse *pParse,
80702   AuthContext *pContext, 
80703   const char *zContext
80704 ){
80705   assert( pParse );
80706   pContext->pParse = pParse;
80707   pContext->zAuthContext = pParse->zAuthContext;
80708   pParse->zAuthContext = zContext;
80709 }
80710
80711 /*
80712 ** Pop an authorization context that was previously pushed
80713 ** by sqlite3AuthContextPush
80714 */
80715 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
80716   if( pContext->pParse ){
80717     pContext->pParse->zAuthContext = pContext->zAuthContext;
80718     pContext->pParse = 0;
80719   }
80720 }
80721
80722 #endif /* SQLITE_OMIT_AUTHORIZATION */
80723
80724 /************** End of auth.c ************************************************/
80725 /************** Begin file build.c *******************************************/
80726 /*
80727 ** 2001 September 15
80728 **
80729 ** The author disclaims copyright to this source code.  In place of
80730 ** a legal notice, here is a blessing:
80731 **
80732 **    May you do good and not evil.
80733 **    May you find forgiveness for yourself and forgive others.
80734 **    May you share freely, never taking more than you give.
80735 **
80736 *************************************************************************
80737 ** This file contains C code routines that are called by the SQLite parser
80738 ** when syntax rules are reduced.  The routines in this file handle the
80739 ** following kinds of SQL syntax:
80740 **
80741 **     CREATE TABLE
80742 **     DROP TABLE
80743 **     CREATE INDEX
80744 **     DROP INDEX
80745 **     creating ID lists
80746 **     BEGIN TRANSACTION
80747 **     COMMIT
80748 **     ROLLBACK
80749 */
80750
80751 /*
80752 ** This routine is called when a new SQL statement is beginning to
80753 ** be parsed.  Initialize the pParse structure as needed.
80754 */
80755 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
80756   pParse->explain = (u8)explainFlag;
80757   pParse->nVar = 0;
80758 }
80759
80760 #ifndef SQLITE_OMIT_SHARED_CACHE
80761 /*
80762 ** The TableLock structure is only used by the sqlite3TableLock() and
80763 ** codeTableLocks() functions.
80764 */
80765 struct TableLock {
80766   int iDb;             /* The database containing the table to be locked */
80767   int iTab;            /* The root page of the table to be locked */
80768   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80769   const char *zName;   /* Name of the table */
80770 };
80771
80772 /*
80773 ** Record the fact that we want to lock a table at run-time.  
80774 **
80775 ** The table to be locked has root page iTab and is found in database iDb.
80776 ** A read or a write lock can be taken depending on isWritelock.
80777 **
80778 ** This routine just records the fact that the lock is desired.  The
80779 ** code to make the lock occur is generated by a later call to
80780 ** codeTableLocks() which occurs during sqlite3FinishCoding().
80781 */
80782 SQLITE_PRIVATE void sqlite3TableLock(
80783   Parse *pParse,     /* Parsing context */
80784   int iDb,           /* Index of the database containing the table to lock */
80785   int iTab,          /* Root page number of the table to be locked */
80786   u8 isWriteLock,    /* True for a write lock */
80787   const char *zName  /* Name of the table to be locked */
80788 ){
80789   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80790   int i;
80791   int nBytes;
80792   TableLock *p;
80793   assert( iDb>=0 );
80794
80795   for(i=0; i<pToplevel->nTableLock; i++){
80796     p = &pToplevel->aTableLock[i];
80797     if( p->iDb==iDb && p->iTab==iTab ){
80798       p->isWriteLock = (p->isWriteLock || isWriteLock);
80799       return;
80800     }
80801   }
80802
80803   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80804   pToplevel->aTableLock =
80805       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
80806   if( pToplevel->aTableLock ){
80807     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
80808     p->iDb = iDb;
80809     p->iTab = iTab;
80810     p->isWriteLock = isWriteLock;
80811     p->zName = zName;
80812   }else{
80813     pToplevel->nTableLock = 0;
80814     pToplevel->db->mallocFailed = 1;
80815   }
80816 }
80817
80818 /*
80819 ** Code an OP_TableLock instruction for each table locked by the
80820 ** statement (configured by calls to sqlite3TableLock()).
80821 */
80822 static void codeTableLocks(Parse *pParse){
80823   int i;
80824   Vdbe *pVdbe; 
80825
80826   pVdbe = sqlite3GetVdbe(pParse);
80827   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
80828
80829   for(i=0; i<pParse->nTableLock; i++){
80830     TableLock *p = &pParse->aTableLock[i];
80831     int p1 = p->iDb;
80832     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
80833                       p->zName, P4_STATIC);
80834   }
80835 }
80836 #else
80837   #define codeTableLocks(x)
80838 #endif
80839
80840 /*
80841 ** This routine is called after a single SQL statement has been
80842 ** parsed and a VDBE program to execute that statement has been
80843 ** prepared.  This routine puts the finishing touches on the
80844 ** VDBE program and resets the pParse structure for the next
80845 ** parse.
80846 **
80847 ** Note that if an error occurred, it might be the case that
80848 ** no VDBE code was generated.
80849 */
80850 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
80851   sqlite3 *db;
80852   Vdbe *v;
80853
80854   assert( pParse->pToplevel==0 );
80855   db = pParse->db;
80856   if( db->mallocFailed ) return;
80857   if( pParse->nested ) return;
80858   if( pParse->nErr ) return;
80859
80860   /* Begin by generating some termination code at the end of the
80861   ** vdbe program
80862   */
80863   v = sqlite3GetVdbe(pParse);
80864   assert( !pParse->isMultiWrite 
80865        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
80866   if( v ){
80867     sqlite3VdbeAddOp0(v, OP_Halt);
80868
80869     /* The cookie mask contains one bit for each database file open.
80870     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
80871     ** set for each database that is used.  Generate code to start a
80872     ** transaction on each used database and to verify the schema cookie
80873     ** on each used database.
80874     */
80875     if( pParse->cookieGoto>0 ){
80876       yDbMask mask;
80877       int iDb;
80878       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
80879       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
80880         if( (mask & pParse->cookieMask)==0 ) continue;
80881         sqlite3VdbeUsesBtree(v, iDb);
80882         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
80883         if( db->init.busy==0 ){
80884           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80885           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
80886                             iDb, pParse->cookieValue[iDb],
80887                             db->aDb[iDb].pSchema->iGeneration);
80888         }
80889       }
80890 #ifndef SQLITE_OMIT_VIRTUALTABLE
80891       {
80892         int i;
80893         for(i=0; i<pParse->nVtabLock; i++){
80894           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
80895           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
80896         }
80897         pParse->nVtabLock = 0;
80898       }
80899 #endif
80900
80901       /* Once all the cookies have been verified and transactions opened, 
80902       ** obtain the required table-locks. This is a no-op unless the 
80903       ** shared-cache feature is enabled.
80904       */
80905       codeTableLocks(pParse);
80906
80907       /* Initialize any AUTOINCREMENT data structures required.
80908       */
80909       sqlite3AutoincrementBegin(pParse);
80910
80911       /* Finally, jump back to the beginning of the executable code. */
80912       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
80913     }
80914   }
80915
80916
80917   /* Get the VDBE program ready for execution
80918   */
80919   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
80920 #ifdef SQLITE_DEBUG
80921     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
80922     sqlite3VdbeTrace(v, trace);
80923 #endif
80924     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
80925     /* A minimum of one cursor is required if autoincrement is used
80926     *  See ticket [a696379c1f08866] */
80927     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
80928     sqlite3VdbeMakeReady(v, pParse);
80929     pParse->rc = SQLITE_DONE;
80930     pParse->colNamesSet = 0;
80931   }else{
80932     pParse->rc = SQLITE_ERROR;
80933   }
80934   pParse->nTab = 0;
80935   pParse->nMem = 0;
80936   pParse->nSet = 0;
80937   pParse->nVar = 0;
80938   pParse->cookieMask = 0;
80939   pParse->cookieGoto = 0;
80940 }
80941
80942 /*
80943 ** Run the parser and code generator recursively in order to generate
80944 ** code for the SQL statement given onto the end of the pParse context
80945 ** currently under construction.  When the parser is run recursively
80946 ** this way, the final OP_Halt is not appended and other initialization
80947 ** and finalization steps are omitted because those are handling by the
80948 ** outermost parser.
80949 **
80950 ** Not everything is nestable.  This facility is designed to permit
80951 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
80952 ** care if you decide to try to use this routine for some other purposes.
80953 */
80954 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
80955   va_list ap;
80956   char *zSql;
80957   char *zErrMsg = 0;
80958   sqlite3 *db = pParse->db;
80959 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
80960   char saveBuf[SAVE_SZ];
80961
80962   if( pParse->nErr ) return;
80963   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
80964   va_start(ap, zFormat);
80965   zSql = sqlite3VMPrintf(db, zFormat, ap);
80966   va_end(ap);
80967   if( zSql==0 ){
80968     return;   /* A malloc must have failed */
80969   }
80970   pParse->nested++;
80971   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
80972   memset(&pParse->nVar, 0, SAVE_SZ);
80973   sqlite3RunParser(pParse, zSql, &zErrMsg);
80974   sqlite3DbFree(db, zErrMsg);
80975   sqlite3DbFree(db, zSql);
80976   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
80977   pParse->nested--;
80978 }
80979
80980 /*
80981 ** Locate the in-memory structure that describes a particular database
80982 ** table given the name of that table and (optionally) the name of the
80983 ** database containing the table.  Return NULL if not found.
80984 **
80985 ** If zDatabase is 0, all databases are searched for the table and the
80986 ** first matching table is returned.  (No checking for duplicate table
80987 ** names is done.)  The search order is TEMP first, then MAIN, then any
80988 ** auxiliary databases added using the ATTACH command.
80989 **
80990 ** See also sqlite3LocateTable().
80991 */
80992 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
80993   Table *p = 0;
80994   int i;
80995   int nName;
80996   assert( zName!=0 );
80997   nName = sqlite3Strlen30(zName);
80998   /* All mutexes are required for schema access.  Make sure we hold them. */
80999   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81000   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81001     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81002     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81003     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81004     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81005     if( p ) break;
81006   }
81007   return p;
81008 }
81009
81010 /*
81011 ** Locate the in-memory structure that describes a particular database
81012 ** table given the name of that table and (optionally) the name of the
81013 ** database containing the table.  Return NULL if not found.  Also leave an
81014 ** error message in pParse->zErrMsg.
81015 **
81016 ** The difference between this routine and sqlite3FindTable() is that this
81017 ** routine leaves an error message in pParse->zErrMsg where
81018 ** sqlite3FindTable() does not.
81019 */
81020 SQLITE_PRIVATE Table *sqlite3LocateTable(
81021   Parse *pParse,         /* context in which to report errors */
81022   int isView,            /* True if looking for a VIEW rather than a TABLE */
81023   const char *zName,     /* Name of the table we are looking for */
81024   const char *zDbase     /* Name of the database.  Might be NULL */
81025 ){
81026   Table *p;
81027
81028   /* Read the database schema. If an error occurs, leave an error message
81029   ** and code in pParse and return NULL. */
81030   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81031     return 0;
81032   }
81033
81034   p = sqlite3FindTable(pParse->db, zName, zDbase);
81035   if( p==0 ){
81036     const char *zMsg = isView ? "no such view" : "no such table";
81037     if( zDbase ){
81038       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81039     }else{
81040       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81041     }
81042     pParse->checkSchema = 1;
81043   }
81044   return p;
81045 }
81046
81047 /*
81048 ** Locate the table identified by *p.
81049 **
81050 ** This is a wrapper around sqlite3LocateTable(). The difference between
81051 ** sqlite3LocateTable() and this function is that this function restricts
81052 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
81053 ** non-NULL if it is part of a view or trigger program definition. See
81054 ** sqlite3FixSrcList() for details.
81055 */
81056 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
81057   Parse *pParse, 
81058   int isView, 
81059   struct SrcList_item *p
81060 ){
81061   const char *zDb;
81062   assert( p->pSchema==0 || p->zDatabase==0 );
81063   if( p->pSchema ){
81064     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
81065     zDb = pParse->db->aDb[iDb].zName;
81066   }else{
81067     zDb = p->zDatabase;
81068   }
81069   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
81070 }
81071
81072 /*
81073 ** Locate the in-memory structure that describes 
81074 ** a particular index given the name of that index
81075 ** and the name of the database that contains the index.
81076 ** Return NULL if not found.
81077 **
81078 ** If zDatabase is 0, all databases are searched for the
81079 ** table and the first matching index is returned.  (No checking
81080 ** for duplicate index names is done.)  The search order is
81081 ** TEMP first, then MAIN, then any auxiliary databases added
81082 ** using the ATTACH command.
81083 */
81084 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
81085   Index *p = 0;
81086   int i;
81087   int nName = sqlite3Strlen30(zName);
81088   /* All mutexes are required for schema access.  Make sure we hold them. */
81089   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81090   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81091     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81092     Schema *pSchema = db->aDb[j].pSchema;
81093     assert( pSchema );
81094     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
81095     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81096     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
81097     if( p ) break;
81098   }
81099   return p;
81100 }
81101
81102 /*
81103 ** Reclaim the memory used by an index
81104 */
81105 static void freeIndex(sqlite3 *db, Index *p){
81106 #ifndef SQLITE_OMIT_ANALYZE
81107   sqlite3DeleteIndexSamples(db, p);
81108 #endif
81109   sqlite3DbFree(db, p->zColAff);
81110   sqlite3DbFree(db, p);
81111 }
81112
81113 /*
81114 ** For the index called zIdxName which is found in the database iDb,
81115 ** unlike that index from its Table then remove the index from
81116 ** the index hash table and free all memory structures associated
81117 ** with the index.
81118 */
81119 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
81120   Index *pIndex;
81121   int len;
81122   Hash *pHash;
81123
81124   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81125   pHash = &db->aDb[iDb].pSchema->idxHash;
81126   len = sqlite3Strlen30(zIdxName);
81127   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
81128   if( ALWAYS(pIndex) ){
81129     if( pIndex->pTable->pIndex==pIndex ){
81130       pIndex->pTable->pIndex = pIndex->pNext;
81131     }else{
81132       Index *p;
81133       /* Justification of ALWAYS();  The index must be on the list of
81134       ** indices. */
81135       p = pIndex->pTable->pIndex;
81136       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81137       if( ALWAYS(p && p->pNext==pIndex) ){
81138         p->pNext = pIndex->pNext;
81139       }
81140     }
81141     freeIndex(db, pIndex);
81142   }
81143   db->flags |= SQLITE_InternChanges;
81144 }
81145
81146 /*
81147 ** Look through the list of open database files in db->aDb[] and if
81148 ** any have been closed, remove them from the list.  Reallocate the
81149 ** db->aDb[] structure to a smaller size, if possible.
81150 **
81151 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
81152 ** are never candidates for being collapsed.
81153 */
81154 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
81155   int i, j;
81156   for(i=j=2; i<db->nDb; i++){
81157     struct Db *pDb = &db->aDb[i];
81158     if( pDb->pBt==0 ){
81159       sqlite3DbFree(db, pDb->zName);
81160       pDb->zName = 0;
81161       continue;
81162     }
81163     if( j<i ){
81164       db->aDb[j] = db->aDb[i];
81165     }
81166     j++;
81167   }
81168   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81169   db->nDb = j;
81170   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81171     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81172     sqlite3DbFree(db, db->aDb);
81173     db->aDb = db->aDbStatic;
81174   }
81175 }
81176
81177 /*
81178 ** Reset the schema for the database at index iDb.  Also reset the
81179 ** TEMP schema.
81180 */
81181 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
81182   Db *pDb;
81183   assert( iDb<db->nDb );
81184
81185   /* Case 1:  Reset the single schema identified by iDb */
81186   pDb = &db->aDb[iDb];
81187   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81188   assert( pDb->pSchema!=0 );
81189   sqlite3SchemaClear(pDb->pSchema);
81190
81191   /* If any database other than TEMP is reset, then also reset TEMP
81192   ** since TEMP might be holding triggers that reference tables in the
81193   ** other database.
81194   */
81195   if( iDb!=1 ){
81196     pDb = &db->aDb[1];
81197     assert( pDb->pSchema!=0 );
81198     sqlite3SchemaClear(pDb->pSchema);
81199   }
81200   return;
81201 }
81202
81203 /*
81204 ** Erase all schema information from all attached databases (including
81205 ** "main" and "temp") for a single database connection.
81206 */
81207 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
81208   int i;
81209   sqlite3BtreeEnterAll(db);
81210   for(i=0; i<db->nDb; i++){
81211     Db *pDb = &db->aDb[i];
81212     if( pDb->pSchema ){
81213       sqlite3SchemaClear(pDb->pSchema);
81214     }
81215   }
81216   db->flags &= ~SQLITE_InternChanges;
81217   sqlite3VtabUnlockList(db);
81218   sqlite3BtreeLeaveAll(db);
81219   sqlite3CollapseDatabaseArray(db);
81220 }
81221
81222 /*
81223 ** This routine is called when a commit occurs.
81224 */
81225 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
81226   db->flags &= ~SQLITE_InternChanges;
81227 }
81228
81229 /*
81230 ** Delete memory allocated for the column names of a table or view (the
81231 ** Table.aCol[] array).
81232 */
81233 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
81234   int i;
81235   Column *pCol;
81236   assert( pTable!=0 );
81237   if( (pCol = pTable->aCol)!=0 ){
81238     for(i=0; i<pTable->nCol; i++, pCol++){
81239       sqlite3DbFree(db, pCol->zName);
81240       sqlite3ExprDelete(db, pCol->pDflt);
81241       sqlite3DbFree(db, pCol->zDflt);
81242       sqlite3DbFree(db, pCol->zType);
81243       sqlite3DbFree(db, pCol->zColl);
81244     }
81245     sqlite3DbFree(db, pTable->aCol);
81246   }
81247 }
81248
81249 /*
81250 ** Remove the memory data structures associated with the given
81251 ** Table.  No changes are made to disk by this routine.
81252 **
81253 ** This routine just deletes the data structure.  It does not unlink
81254 ** the table data structure from the hash table.  But it does destroy
81255 ** memory structures of the indices and foreign keys associated with 
81256 ** the table.
81257 **
81258 ** The db parameter is optional.  It is needed if the Table object 
81259 ** contains lookaside memory.  (Table objects in the schema do not use
81260 ** lookaside memory, but some ephemeral Table objects do.)  Or the
81261 ** db parameter can be used with db->pnBytesFreed to measure the memory
81262 ** used by the Table object.
81263 */
81264 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
81265   Index *pIndex, *pNext;
81266   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
81267
81268   assert( !pTable || pTable->nRef>0 );
81269
81270   /* Do not delete the table until the reference count reaches zero. */
81271   if( !pTable ) return;
81272   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81273
81274   /* Record the number of outstanding lookaside allocations in schema Tables
81275   ** prior to doing any free() operations.  Since schema Tables do not use
81276   ** lookaside, this number should not change. */
81277   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
81278                          db->lookaside.nOut : 0 );
81279
81280   /* Delete all indices associated with this table. */
81281   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81282     pNext = pIndex->pNext;
81283     assert( pIndex->pSchema==pTable->pSchema );
81284     if( !db || db->pnBytesFreed==0 ){
81285       char *zName = pIndex->zName; 
81286       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
81287          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
81288       );
81289       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81290       assert( pOld==pIndex || pOld==0 );
81291     }
81292     freeIndex(db, pIndex);
81293   }
81294
81295   /* Delete any foreign keys attached to this table. */
81296   sqlite3FkDelete(db, pTable);
81297
81298   /* Delete the Table structure itself.
81299   */
81300   sqliteDeleteColumnNames(db, pTable);
81301   sqlite3DbFree(db, pTable->zName);
81302   sqlite3DbFree(db, pTable->zColAff);
81303   sqlite3SelectDelete(db, pTable->pSelect);
81304 #ifndef SQLITE_OMIT_CHECK
81305   sqlite3ExprListDelete(db, pTable->pCheck);
81306 #endif
81307 #ifndef SQLITE_OMIT_VIRTUALTABLE
81308   sqlite3VtabClear(db, pTable);
81309 #endif
81310   sqlite3DbFree(db, pTable);
81311
81312   /* Verify that no lookaside memory was used by schema tables */
81313   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
81314 }
81315
81316 /*
81317 ** Unlink the given table from the hash tables and the delete the
81318 ** table structure with all its indices and foreign keys.
81319 */
81320 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
81321   Table *p;
81322   Db *pDb;
81323
81324   assert( db!=0 );
81325   assert( iDb>=0 && iDb<db->nDb );
81326   assert( zTabName );
81327   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81328   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81329   pDb = &db->aDb[iDb];
81330   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
81331                         sqlite3Strlen30(zTabName),0);
81332   sqlite3DeleteTable(db, p);
81333   db->flags |= SQLITE_InternChanges;
81334 }
81335
81336 /*
81337 ** Given a token, return a string that consists of the text of that
81338 ** token.  Space to hold the returned string
81339 ** is obtained from sqliteMalloc() and must be freed by the calling
81340 ** function.
81341 **
81342 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81343 ** surround the body of the token are removed.
81344 **
81345 ** Tokens are often just pointers into the original SQL text and so
81346 ** are not \000 terminated and are not persistent.  The returned string
81347 ** is \000 terminated and is persistent.
81348 */
81349 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
81350   char *zName;
81351   if( pName ){
81352     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
81353     sqlite3Dequote(zName);
81354   }else{
81355     zName = 0;
81356   }
81357   return zName;
81358 }
81359
81360 /*
81361 ** Open the sqlite_master table stored in database number iDb for
81362 ** writing. The table is opened using cursor 0.
81363 */
81364 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
81365   Vdbe *v = sqlite3GetVdbe(p);
81366   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81367   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81368   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81369   if( p->nTab==0 ){
81370     p->nTab = 1;
81371   }
81372 }
81373
81374 /*
81375 ** Parameter zName points to a nul-terminated buffer containing the name
81376 ** of a database ("main", "temp" or the name of an attached db). This
81377 ** function returns the index of the named database in db->aDb[], or
81378 ** -1 if the named db cannot be found.
81379 */
81380 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
81381   int i = -1;         /* Database number */
81382   if( zName ){
81383     Db *pDb;
81384     int n = sqlite3Strlen30(zName);
81385     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81386       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
81387           0==sqlite3StrICmp(pDb->zName, zName) ){
81388         break;
81389       }
81390     }
81391   }
81392   return i;
81393 }
81394
81395 /*
81396 ** The token *pName contains the name of a database (either "main" or
81397 ** "temp" or the name of an attached db). This routine returns the
81398 ** index of the named database in db->aDb[], or -1 if the named db 
81399 ** does not exist.
81400 */
81401 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
81402   int i;                               /* Database number */
81403   char *zName;                         /* Name we are searching for */
81404   zName = sqlite3NameFromToken(db, pName);
81405   i = sqlite3FindDbName(db, zName);
81406   sqlite3DbFree(db, zName);
81407   return i;
81408 }
81409
81410 /* The table or view or trigger name is passed to this routine via tokens
81411 ** pName1 and pName2. If the table name was fully qualified, for example:
81412 **
81413 ** CREATE TABLE xxx.yyy (...);
81414 ** 
81415 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81416 ** the table name is not fully qualified, i.e.:
81417 **
81418 ** CREATE TABLE yyy(...);
81419 **
81420 ** Then pName1 is set to "yyy" and pName2 is "".
81421 **
81422 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81423 ** pName2) that stores the unqualified table name.  The index of the
81424 ** database "xxx" is returned.
81425 */
81426 SQLITE_PRIVATE int sqlite3TwoPartName(
81427   Parse *pParse,      /* Parsing and code generating context */
81428   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81429   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81430   Token **pUnqual     /* Write the unqualified object name here */
81431 ){
81432   int iDb;                    /* Database holding the object */
81433   sqlite3 *db = pParse->db;
81434
81435   if( ALWAYS(pName2!=0) && pName2->n>0 ){
81436     if( db->init.busy ) {
81437       sqlite3ErrorMsg(pParse, "corrupt database");
81438       pParse->nErr++;
81439       return -1;
81440     }
81441     *pUnqual = pName2;
81442     iDb = sqlite3FindDb(db, pName1);
81443     if( iDb<0 ){
81444       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
81445       pParse->nErr++;
81446       return -1;
81447     }
81448   }else{
81449     assert( db->init.iDb==0 || db->init.busy );
81450     iDb = db->init.iDb;
81451     *pUnqual = pName1;
81452   }
81453   return iDb;
81454 }
81455
81456 /*
81457 ** This routine is used to check if the UTF-8 string zName is a legal
81458 ** unqualified name for a new schema object (table, index, view or
81459 ** trigger). All names are legal except those that begin with the string
81460 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
81461 ** is reserved for internal use.
81462 */
81463 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
81464   if( !pParse->db->init.busy && pParse->nested==0 
81465           && (pParse->db->flags & SQLITE_WriteSchema)==0
81466           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81467     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81468     return SQLITE_ERROR;
81469   }
81470   return SQLITE_OK;
81471 }
81472
81473 /*
81474 ** Begin constructing a new table representation in memory.  This is
81475 ** the first of several action routines that get called in response
81476 ** to a CREATE TABLE statement.  In particular, this routine is called
81477 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81478 ** flag is true if the table should be stored in the auxiliary database
81479 ** file instead of in the main database file.  This is normally the case
81480 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
81481 ** CREATE and TABLE.
81482 **
81483 ** The new table record is initialized and put in pParse->pNewTable.
81484 ** As more of the CREATE TABLE statement is parsed, additional action
81485 ** routines will be called to add more information to this record.
81486 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
81487 ** is called to complete the construction of the new table record.
81488 */
81489 SQLITE_PRIVATE void sqlite3StartTable(
81490   Parse *pParse,   /* Parser context */
81491   Token *pName1,   /* First part of the name of the table or view */
81492   Token *pName2,   /* Second part of the name of the table or view */
81493   int isTemp,      /* True if this is a TEMP table */
81494   int isView,      /* True if this is a VIEW */
81495   int isVirtual,   /* True if this is a VIRTUAL table */
81496   int noErr        /* Do nothing if table already exists */
81497 ){
81498   Table *pTable;
81499   char *zName = 0; /* The name of the new table */
81500   sqlite3 *db = pParse->db;
81501   Vdbe *v;
81502   int iDb;         /* Database number to create the table in */
81503   Token *pName;    /* Unqualified name of the table to create */
81504
81505   /* The table or view name to create is passed to this routine via tokens
81506   ** pName1 and pName2. If the table name was fully qualified, for example:
81507   **
81508   ** CREATE TABLE xxx.yyy (...);
81509   ** 
81510   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81511   ** the table name is not fully qualified, i.e.:
81512   **
81513   ** CREATE TABLE yyy(...);
81514   **
81515   ** Then pName1 is set to "yyy" and pName2 is "".
81516   **
81517   ** The call below sets the pName pointer to point at the token (pName1 or
81518   ** pName2) that stores the unqualified table name. The variable iDb is
81519   ** set to the index of the database that the table or view is to be
81520   ** created in.
81521   */
81522   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81523   if( iDb<0 ) return;
81524   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81525     /* If creating a temp table, the name may not be qualified. Unless 
81526     ** the database name is "temp" anyway.  */
81527     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
81528     return;
81529   }
81530   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81531
81532   pParse->sNameToken = *pName;
81533   zName = sqlite3NameFromToken(db, pName);
81534   if( zName==0 ) return;
81535   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81536     goto begin_table_error;
81537   }
81538   if( db->init.iDb==1 ) isTemp = 1;
81539 #ifndef SQLITE_OMIT_AUTHORIZATION
81540   assert( (isTemp & 1)==isTemp );
81541   {
81542     int code;
81543     char *zDb = db->aDb[iDb].zName;
81544     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81545       goto begin_table_error;
81546     }
81547     if( isView ){
81548       if( !OMIT_TEMPDB && isTemp ){
81549         code = SQLITE_CREATE_TEMP_VIEW;
81550       }else{
81551         code = SQLITE_CREATE_VIEW;
81552       }
81553     }else{
81554       if( !OMIT_TEMPDB && isTemp ){
81555         code = SQLITE_CREATE_TEMP_TABLE;
81556       }else{
81557         code = SQLITE_CREATE_TABLE;
81558       }
81559     }
81560     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
81561       goto begin_table_error;
81562     }
81563   }
81564 #endif
81565
81566   /* Make sure the new table name does not collide with an existing
81567   ** index or table name in the same database.  Issue an error message if
81568   ** it does. The exception is if the statement being parsed was passed
81569   ** to an sqlite3_declare_vtab() call. In that case only the column names
81570   ** and types will be used, so there is no need to test for namespace
81571   ** collisions.
81572   */
81573   if( !IN_DECLARE_VTAB ){
81574     char *zDb = db->aDb[iDb].zName;
81575     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81576       goto begin_table_error;
81577     }
81578     pTable = sqlite3FindTable(db, zName, zDb);
81579     if( pTable ){
81580       if( !noErr ){
81581         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
81582       }else{
81583         assert( !db->init.busy );
81584         sqlite3CodeVerifySchema(pParse, iDb);
81585       }
81586       goto begin_table_error;
81587     }
81588     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
81589       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
81590       goto begin_table_error;
81591     }
81592   }
81593
81594   pTable = sqlite3DbMallocZero(db, sizeof(Table));
81595   if( pTable==0 ){
81596     db->mallocFailed = 1;
81597     pParse->rc = SQLITE_NOMEM;
81598     pParse->nErr++;
81599     goto begin_table_error;
81600   }
81601   pTable->zName = zName;
81602   pTable->iPKey = -1;
81603   pTable->pSchema = db->aDb[iDb].pSchema;
81604   pTable->nRef = 1;
81605   pTable->nRowEst = 1000000;
81606   assert( pParse->pNewTable==0 );
81607   pParse->pNewTable = pTable;
81608
81609   /* If this is the magic sqlite_sequence table used by autoincrement,
81610   ** then record a pointer to this table in the main database structure
81611   ** so that INSERT can find the table easily.
81612   */
81613 #ifndef SQLITE_OMIT_AUTOINCREMENT
81614   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
81615     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81616     pTable->pSchema->pSeqTab = pTable;
81617   }
81618 #endif
81619
81620   /* Begin generating the code that will insert the table record into
81621   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
81622   ** and allocate the record number for the table entry now.  Before any
81623   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81624   ** indices to be created and the table record must come before the 
81625   ** indices.  Hence, the record number for the table must be allocated
81626   ** now.
81627   */
81628   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
81629     int j1;
81630     int fileFormat;
81631     int reg1, reg2, reg3;
81632     sqlite3BeginWriteOperation(pParse, 0, iDb);
81633
81634 #ifndef SQLITE_OMIT_VIRTUALTABLE
81635     if( isVirtual ){
81636       sqlite3VdbeAddOp0(v, OP_VBegin);
81637     }
81638 #endif
81639
81640     /* If the file format and encoding in the database have not been set, 
81641     ** set them now.
81642     */
81643     reg1 = pParse->regRowid = ++pParse->nMem;
81644     reg2 = pParse->regRoot = ++pParse->nMem;
81645     reg3 = ++pParse->nMem;
81646     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81647     sqlite3VdbeUsesBtree(v, iDb);
81648     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
81649     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
81650                   1 : SQLITE_MAX_FILE_FORMAT;
81651     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81652     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81653     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81654     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81655     sqlite3VdbeJumpHere(v, j1);
81656
81657     /* This just creates a place-holder record in the sqlite_master table.
81658     ** The record created does not contain anything yet.  It will be replaced
81659     ** by the real entry in code generated at sqlite3EndTable().
81660     **
81661     ** The rowid for the new entry is left in register pParse->regRowid.
81662     ** The root page number of the new table is left in reg pParse->regRoot.
81663     ** The rowid and root page number values are needed by the code that
81664     ** sqlite3EndTable will generate.
81665     */
81666 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81667     if( isView || isVirtual ){
81668       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
81669     }else
81670 #endif
81671     {
81672       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81673     }
81674     sqlite3OpenMasterTable(pParse, iDb);
81675     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81676     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
81677     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81678     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81679     sqlite3VdbeAddOp0(v, OP_Close);
81680   }
81681
81682   /* Normal (non-error) return. */
81683   return;
81684
81685   /* If an error occurs, we jump here */
81686 begin_table_error:
81687   sqlite3DbFree(db, zName);
81688   return;
81689 }
81690
81691 /*
81692 ** This macro is used to compare two strings in a case-insensitive manner.
81693 ** It is slightly faster than calling sqlite3StrICmp() directly, but
81694 ** produces larger code.
81695 **
81696 ** WARNING: This macro is not compatible with the strcmp() family. It
81697 ** returns true if the two strings are equal, otherwise false.
81698 */
81699 #define STRICMP(x, y) (\
81700 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
81701 sqlite3UpperToLower[*(unsigned char *)(y)]     \
81702 && sqlite3StrICmp((x)+1,(y)+1)==0 )
81703
81704 /*
81705 ** Add a new column to the table currently being constructed.
81706 **
81707 ** The parser calls this routine once for each column declaration
81708 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
81709 ** first to get things going.  Then this routine is called for each
81710 ** column.
81711 */
81712 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
81713   Table *p;
81714   int i;
81715   char *z;
81716   Column *pCol;
81717   sqlite3 *db = pParse->db;
81718   if( (p = pParse->pNewTable)==0 ) return;
81719 #if SQLITE_MAX_COLUMN
81720   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81721     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
81722     return;
81723   }
81724 #endif
81725   z = sqlite3NameFromToken(db, pName);
81726   if( z==0 ) return;
81727   for(i=0; i<p->nCol; i++){
81728     if( STRICMP(z, p->aCol[i].zName) ){
81729       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
81730       sqlite3DbFree(db, z);
81731       return;
81732     }
81733   }
81734   if( (p->nCol & 0x7)==0 ){
81735     Column *aNew;
81736     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81737     if( aNew==0 ){
81738       sqlite3DbFree(db, z);
81739       return;
81740     }
81741     p->aCol = aNew;
81742   }
81743   pCol = &p->aCol[p->nCol];
81744   memset(pCol, 0, sizeof(p->aCol[0]));
81745   pCol->zName = z;
81746  
81747   /* If there is no type specified, columns have the default affinity
81748   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
81749   ** be called next to set pCol->affinity correctly.
81750   */
81751   pCol->affinity = SQLITE_AFF_NONE;
81752   p->nCol++;
81753 }
81754
81755 /*
81756 ** This routine is called by the parser while in the middle of
81757 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81758 ** been seen on a column.  This routine sets the notNull flag on
81759 ** the column currently under construction.
81760 */
81761 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
81762   Table *p;
81763   p = pParse->pNewTable;
81764   if( p==0 || NEVER(p->nCol<1) ) return;
81765   p->aCol[p->nCol-1].notNull = (u8)onError;
81766 }
81767
81768 /*
81769 ** Scan the column type name zType (length nType) and return the
81770 ** associated affinity type.
81771 **
81772 ** This routine does a case-independent search of zType for the 
81773 ** substrings in the following table. If one of the substrings is
81774 ** found, the corresponding affinity is returned. If zType contains
81775 ** more than one of the substrings, entries toward the top of 
81776 ** the table take priority. For example, if zType is 'BLOBINT', 
81777 ** SQLITE_AFF_INTEGER is returned.
81778 **
81779 ** Substring     | Affinity
81780 ** --------------------------------
81781 ** 'INT'         | SQLITE_AFF_INTEGER
81782 ** 'CHAR'        | SQLITE_AFF_TEXT
81783 ** 'CLOB'        | SQLITE_AFF_TEXT
81784 ** 'TEXT'        | SQLITE_AFF_TEXT
81785 ** 'BLOB'        | SQLITE_AFF_NONE
81786 ** 'REAL'        | SQLITE_AFF_REAL
81787 ** 'FLOA'        | SQLITE_AFF_REAL
81788 ** 'DOUB'        | SQLITE_AFF_REAL
81789 **
81790 ** If none of the substrings in the above table are found,
81791 ** SQLITE_AFF_NUMERIC is returned.
81792 */
81793 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
81794   u32 h = 0;
81795   char aff = SQLITE_AFF_NUMERIC;
81796
81797   if( zIn ) while( zIn[0] ){
81798     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
81799     zIn++;
81800     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
81801       aff = SQLITE_AFF_TEXT; 
81802     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
81803       aff = SQLITE_AFF_TEXT;
81804     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
81805       aff = SQLITE_AFF_TEXT;
81806     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
81807         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
81808       aff = SQLITE_AFF_NONE;
81809 #ifndef SQLITE_OMIT_FLOATING_POINT
81810     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
81811         && aff==SQLITE_AFF_NUMERIC ){
81812       aff = SQLITE_AFF_REAL;
81813     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
81814         && aff==SQLITE_AFF_NUMERIC ){
81815       aff = SQLITE_AFF_REAL;
81816     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
81817         && aff==SQLITE_AFF_NUMERIC ){
81818       aff = SQLITE_AFF_REAL;
81819 #endif
81820     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
81821       aff = SQLITE_AFF_INTEGER;
81822       break;
81823     }
81824   }
81825
81826   return aff;
81827 }
81828
81829 /*
81830 ** This routine is called by the parser while in the middle of
81831 ** parsing a CREATE TABLE statement.  The pFirst token is the first
81832 ** token in the sequence of tokens that describe the type of the
81833 ** column currently under construction.   pLast is the last token
81834 ** in the sequence.  Use this information to construct a string
81835 ** that contains the typename of the column and store that string
81836 ** in zType.
81837 */ 
81838 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
81839   Table *p;
81840   Column *pCol;
81841
81842   p = pParse->pNewTable;
81843   if( p==0 || NEVER(p->nCol<1) ) return;
81844   pCol = &p->aCol[p->nCol-1];
81845   assert( pCol->zType==0 );
81846   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
81847   pCol->affinity = sqlite3AffinityType(pCol->zType);
81848 }
81849
81850 /*
81851 ** The expression is the default value for the most recently added column
81852 ** of the table currently under construction.
81853 **
81854 ** Default value expressions must be constant.  Raise an exception if this
81855 ** is not the case.
81856 **
81857 ** This routine is called by the parser while in the middle of
81858 ** parsing a CREATE TABLE statement.
81859 */
81860 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
81861   Table *p;
81862   Column *pCol;
81863   sqlite3 *db = pParse->db;
81864   p = pParse->pNewTable;
81865   if( p!=0 ){
81866     pCol = &(p->aCol[p->nCol-1]);
81867     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
81868       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
81869           pCol->zName);
81870     }else{
81871       /* A copy of pExpr is used instead of the original, as pExpr contains
81872       ** tokens that point to volatile memory. The 'span' of the expression
81873       ** is required by pragma table_info.
81874       */
81875       sqlite3ExprDelete(db, pCol->pDflt);
81876       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
81877       sqlite3DbFree(db, pCol->zDflt);
81878       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
81879                                      (int)(pSpan->zEnd - pSpan->zStart));
81880     }
81881   }
81882   sqlite3ExprDelete(db, pSpan->pExpr);
81883 }
81884
81885 /*
81886 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
81887 ** of columns that form the primary key.  If pList is NULL, then the
81888 ** most recently added column of the table is the primary key.
81889 **
81890 ** A table can have at most one primary key.  If the table already has
81891 ** a primary key (and this is the second primary key) then create an
81892 ** error.
81893 **
81894 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
81895 ** then we will try to use that column as the rowid.  Set the Table.iPKey
81896 ** field of the table under construction to be the index of the
81897 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
81898 ** no INTEGER PRIMARY KEY.
81899 **
81900 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
81901 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
81902 */
81903 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
81904   Parse *pParse,    /* Parsing context */
81905   ExprList *pList,  /* List of field names to be indexed */
81906   int onError,      /* What to do with a uniqueness conflict */
81907   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
81908   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
81909 ){
81910   Table *pTab = pParse->pNewTable;
81911   char *zType = 0;
81912   int iCol = -1, i;
81913   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
81914   if( pTab->tabFlags & TF_HasPrimaryKey ){
81915     sqlite3ErrorMsg(pParse, 
81916       "table \"%s\" has more than one primary key", pTab->zName);
81917     goto primary_key_exit;
81918   }
81919   pTab->tabFlags |= TF_HasPrimaryKey;
81920   if( pList==0 ){
81921     iCol = pTab->nCol - 1;
81922     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
81923   }else{
81924     for(i=0; i<pList->nExpr; i++){
81925       for(iCol=0; iCol<pTab->nCol; iCol++){
81926         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
81927           break;
81928         }
81929       }
81930       if( iCol<pTab->nCol ){
81931         pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
81932       }
81933     }
81934     if( pList->nExpr>1 ) iCol = -1;
81935   }
81936   if( iCol>=0 && iCol<pTab->nCol ){
81937     zType = pTab->aCol[iCol].zType;
81938   }
81939   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
81940         && sortOrder==SQLITE_SO_ASC ){
81941     pTab->iPKey = iCol;
81942     pTab->keyConf = (u8)onError;
81943     assert( autoInc==0 || autoInc==1 );
81944     pTab->tabFlags |= autoInc*TF_Autoincrement;
81945   }else if( autoInc ){
81946 #ifndef SQLITE_OMIT_AUTOINCREMENT
81947     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
81948        "INTEGER PRIMARY KEY");
81949 #endif
81950   }else{
81951     Index *p;
81952     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
81953     if( p ){
81954       p->autoIndex = 2;
81955     }
81956     pList = 0;
81957   }
81958
81959 primary_key_exit:
81960   sqlite3ExprListDelete(pParse->db, pList);
81961   return;
81962 }
81963
81964 /*
81965 ** Add a new CHECK constraint to the table currently under construction.
81966 */
81967 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
81968   Parse *pParse,    /* Parsing context */
81969   Expr *pCheckExpr  /* The check expression */
81970 ){
81971 #ifndef SQLITE_OMIT_CHECK
81972   Table *pTab = pParse->pNewTable;
81973   if( pTab && !IN_DECLARE_VTAB ){
81974     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
81975     if( pParse->constraintName.n ){
81976       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
81977     }
81978   }else
81979 #endif
81980   {
81981     sqlite3ExprDelete(pParse->db, pCheckExpr);
81982   }
81983 }
81984
81985 /*
81986 ** Set the collation function of the most recently parsed table column
81987 ** to the CollSeq given.
81988 */
81989 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
81990   Table *p;
81991   int i;
81992   char *zColl;              /* Dequoted name of collation sequence */
81993   sqlite3 *db;
81994
81995   if( (p = pParse->pNewTable)==0 ) return;
81996   i = p->nCol-1;
81997   db = pParse->db;
81998   zColl = sqlite3NameFromToken(db, pToken);
81999   if( !zColl ) return;
82000
82001   if( sqlite3LocateCollSeq(pParse, zColl) ){
82002     Index *pIdx;
82003     p->aCol[i].zColl = zColl;
82004   
82005     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82006     ** then an index may have been created on this column before the
82007     ** collation type was added. Correct this if it is the case.
82008     */
82009     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82010       assert( pIdx->nColumn==1 );
82011       if( pIdx->aiColumn[0]==i ){
82012         pIdx->azColl[0] = p->aCol[i].zColl;
82013       }
82014     }
82015   }else{
82016     sqlite3DbFree(db, zColl);
82017   }
82018 }
82019
82020 /*
82021 ** This function returns the collation sequence for database native text
82022 ** encoding identified by the string zName, length nName.
82023 **
82024 ** If the requested collation sequence is not available, or not available
82025 ** in the database native encoding, the collation factory is invoked to
82026 ** request it. If the collation factory does not supply such a sequence,
82027 ** and the sequence is available in another text encoding, then that is
82028 ** returned instead.
82029 **
82030 ** If no versions of the requested collations sequence are available, or
82031 ** another error occurs, NULL is returned and an error message written into
82032 ** pParse.
82033 **
82034 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
82035 ** invokes the collation factory if the named collation cannot be found
82036 ** and generates an error message.
82037 **
82038 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
82039 */
82040 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
82041   sqlite3 *db = pParse->db;
82042   u8 enc = ENC(db);
82043   u8 initbusy = db->init.busy;
82044   CollSeq *pColl;
82045
82046   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
82047   if( !initbusy && (!pColl || !pColl->xCmp) ){
82048     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
82049   }
82050
82051   return pColl;
82052 }
82053
82054
82055 /*
82056 ** Generate code that will increment the schema cookie.
82057 **
82058 ** The schema cookie is used to determine when the schema for the
82059 ** database changes.  After each schema change, the cookie value
82060 ** changes.  When a process first reads the schema it records the
82061 ** cookie.  Thereafter, whenever it goes to access the database,
82062 ** it checks the cookie to make sure the schema has not changed
82063 ** since it was last read.
82064 **
82065 ** This plan is not completely bullet-proof.  It is possible for
82066 ** the schema to change multiple times and for the cookie to be
82067 ** set back to prior value.  But schema changes are infrequent
82068 ** and the probability of hitting the same cookie value is only
82069 ** 1 chance in 2^32.  So we're safe enough.
82070 */
82071 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
82072   int r1 = sqlite3GetTempReg(pParse);
82073   sqlite3 *db = pParse->db;
82074   Vdbe *v = pParse->pVdbe;
82075   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82076   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82077   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82078   sqlite3ReleaseTempReg(pParse, r1);
82079 }
82080
82081 /*
82082 ** Measure the number of characters needed to output the given
82083 ** identifier.  The number returned includes any quotes used
82084 ** but does not include the null terminator.
82085 **
82086 ** The estimate is conservative.  It might be larger that what is
82087 ** really needed.
82088 */
82089 static int identLength(const char *z){
82090   int n;
82091   for(n=0; *z; n++, z++){
82092     if( *z=='"' ){ n++; }
82093   }
82094   return n + 2;
82095 }
82096
82097 /*
82098 ** The first parameter is a pointer to an output buffer. The second 
82099 ** parameter is a pointer to an integer that contains the offset at
82100 ** which to write into the output buffer. This function copies the
82101 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
82102 ** to the specified offset in the buffer and updates *pIdx to refer
82103 ** to the first byte after the last byte written before returning.
82104 ** 
82105 ** If the string zSignedIdent consists entirely of alpha-numeric
82106 ** characters, does not begin with a digit and is not an SQL keyword,
82107 ** then it is copied to the output buffer exactly as it is. Otherwise,
82108 ** it is quoted using double-quotes.
82109 */
82110 static void identPut(char *z, int *pIdx, char *zSignedIdent){
82111   unsigned char *zIdent = (unsigned char*)zSignedIdent;
82112   int i, j, needQuote;
82113   i = *pIdx;
82114
82115   for(j=0; zIdent[j]; j++){
82116     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82117   }
82118   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
82119   if( !needQuote ){
82120     needQuote = zIdent[j];
82121   }
82122
82123   if( needQuote ) z[i++] = '"';
82124   for(j=0; zIdent[j]; j++){
82125     z[i++] = zIdent[j];
82126     if( zIdent[j]=='"' ) z[i++] = '"';
82127   }
82128   if( needQuote ) z[i++] = '"';
82129   z[i] = 0;
82130   *pIdx = i;
82131 }
82132
82133 /*
82134 ** Generate a CREATE TABLE statement appropriate for the given
82135 ** table.  Memory to hold the text of the statement is obtained
82136 ** from sqliteMalloc() and must be freed by the calling function.
82137 */
82138 static char *createTableStmt(sqlite3 *db, Table *p){
82139   int i, k, n;
82140   char *zStmt;
82141   char *zSep, *zSep2, *zEnd;
82142   Column *pCol;
82143   n = 0;
82144   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82145     n += identLength(pCol->zName) + 5;
82146   }
82147   n += identLength(p->zName);
82148   if( n<50 ){ 
82149     zSep = "";
82150     zSep2 = ",";
82151     zEnd = ")";
82152   }else{
82153     zSep = "\n  ";
82154     zSep2 = ",\n  ";
82155     zEnd = "\n)";
82156   }
82157   n += 35 + 6*p->nCol;
82158   zStmt = sqlite3DbMallocRaw(0, n);
82159   if( zStmt==0 ){
82160     db->mallocFailed = 1;
82161     return 0;
82162   }
82163   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
82164   k = sqlite3Strlen30(zStmt);
82165   identPut(zStmt, &k, p->zName);
82166   zStmt[k++] = '(';
82167   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82168     static const char * const azType[] = {
82169         /* SQLITE_AFF_TEXT    */ " TEXT",
82170         /* SQLITE_AFF_NONE    */ "",
82171         /* SQLITE_AFF_NUMERIC */ " NUM",
82172         /* SQLITE_AFF_INTEGER */ " INT",
82173         /* SQLITE_AFF_REAL    */ " REAL"
82174     };
82175     int len;
82176     const char *zType;
82177
82178     sqlite3_snprintf(n-k, &zStmt[k], zSep);
82179     k += sqlite3Strlen30(&zStmt[k]);
82180     zSep = zSep2;
82181     identPut(zStmt, &k, pCol->zName);
82182     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
82183     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
82184     testcase( pCol->affinity==SQLITE_AFF_TEXT );
82185     testcase( pCol->affinity==SQLITE_AFF_NONE );
82186     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
82187     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
82188     testcase( pCol->affinity==SQLITE_AFF_REAL );
82189     
82190     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
82191     len = sqlite3Strlen30(zType);
82192     assert( pCol->affinity==SQLITE_AFF_NONE 
82193             || pCol->affinity==sqlite3AffinityType(zType) );
82194     memcpy(&zStmt[k], zType, len);
82195     k += len;
82196     assert( k<=n );
82197   }
82198   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82199   return zStmt;
82200 }
82201
82202 /*
82203 ** This routine is called to report the final ")" that terminates
82204 ** a CREATE TABLE statement.
82205 **
82206 ** The table structure that other action routines have been building
82207 ** is added to the internal hash tables, assuming no errors have
82208 ** occurred.
82209 **
82210 ** An entry for the table is made in the master table on disk, unless
82211 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82212 ** it means we are reading the sqlite_master table because we just
82213 ** connected to the database or because the sqlite_master table has
82214 ** recently changed, so the entry for this table already exists in
82215 ** the sqlite_master table.  We do not want to create it again.
82216 **
82217 ** If the pSelect argument is not NULL, it means that this routine
82218 ** was called to create a table generated from a 
82219 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82220 ** the new table will match the result set of the SELECT.
82221 */
82222 SQLITE_PRIVATE void sqlite3EndTable(
82223   Parse *pParse,          /* Parse context */
82224   Token *pCons,           /* The ',' token after the last column defn. */
82225   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82226   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82227 ){
82228   Table *p;
82229   sqlite3 *db = pParse->db;
82230   int iDb;
82231
82232   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82233     return;
82234   }
82235   p = pParse->pNewTable;
82236   if( p==0 ) return;
82237
82238   assert( !db->init.busy || !pSelect );
82239
82240   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82241
82242 #ifndef SQLITE_OMIT_CHECK
82243   /* Resolve names in all CHECK constraint expressions.
82244   */
82245   if( p->pCheck ){
82246     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82247     NameContext sNC;                /* Name context for pParse->pNewTable */
82248     ExprList *pList;                /* List of all CHECK constraints */
82249     int i;                          /* Loop counter */
82250
82251     memset(&sNC, 0, sizeof(sNC));
82252     memset(&sSrc, 0, sizeof(sSrc));
82253     sSrc.nSrc = 1;
82254     sSrc.a[0].zName = p->zName;
82255     sSrc.a[0].pTab = p;
82256     sSrc.a[0].iCursor = -1;
82257     sNC.pParse = pParse;
82258     sNC.pSrcList = &sSrc;
82259     sNC.ncFlags = NC_IsCheck;
82260     pList = p->pCheck;
82261     for(i=0; i<pList->nExpr; i++){
82262       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82263         return;
82264       }
82265     }
82266   }
82267 #endif /* !defined(SQLITE_OMIT_CHECK) */
82268
82269   /* If the db->init.busy is 1 it means we are reading the SQL off the
82270   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
82271   ** So do not write to the disk again.  Extract the root page number
82272   ** for the table from the db->init.newTnum field.  (The page number
82273   ** should have been put there by the sqliteOpenCb routine.)
82274   */
82275   if( db->init.busy ){
82276     p->tnum = db->init.newTnum;
82277   }
82278
82279   /* If not initializing, then create a record for the new table
82280   ** in the SQLITE_MASTER table of the database.
82281   **
82282   ** If this is a TEMPORARY table, write the entry into the auxiliary
82283   ** file instead of into the main database file.
82284   */
82285   if( !db->init.busy ){
82286     int n;
82287     Vdbe *v;
82288     char *zType;    /* "view" or "table" */
82289     char *zType2;   /* "VIEW" or "TABLE" */
82290     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82291
82292     v = sqlite3GetVdbe(pParse);
82293     if( NEVER(v==0) ) return;
82294
82295     sqlite3VdbeAddOp1(v, OP_Close, 0);
82296
82297     /* 
82298     ** Initialize zType for the new view or table.
82299     */
82300     if( p->pSelect==0 ){
82301       /* A regular table */
82302       zType = "table";
82303       zType2 = "TABLE";
82304 #ifndef SQLITE_OMIT_VIEW
82305     }else{
82306       /* A view */
82307       zType = "view";
82308       zType2 = "VIEW";
82309 #endif
82310     }
82311
82312     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82313     ** statement to populate the new table. The root-page number for the
82314     ** new table is in register pParse->regRoot.
82315     **
82316     ** Once the SELECT has been coded by sqlite3Select(), it is in a
82317     ** suitable state to query for the column names and types to be used
82318     ** by the new table.
82319     **
82320     ** A shared-cache write-lock is not required to write to the new table,
82321     ** as a schema-lock must have already been obtained to create it. Since
82322     ** a schema-lock excludes all other database users, the write-lock would
82323     ** be redundant.
82324     */
82325     if( pSelect ){
82326       SelectDest dest;
82327       Table *pSelTab;
82328
82329       assert(pParse->nTab==1);
82330       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82331       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
82332       pParse->nTab = 2;
82333       sqlite3SelectDestInit(&dest, SRT_Table, 1);
82334       sqlite3Select(pParse, pSelect, &dest);
82335       sqlite3VdbeAddOp1(v, OP_Close, 1);
82336       if( pParse->nErr==0 ){
82337         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
82338         if( pSelTab==0 ) return;
82339         assert( p->aCol==0 );
82340         p->nCol = pSelTab->nCol;
82341         p->aCol = pSelTab->aCol;
82342         pSelTab->nCol = 0;
82343         pSelTab->aCol = 0;
82344         sqlite3DeleteTable(db, pSelTab);
82345       }
82346     }
82347
82348     /* Compute the complete text of the CREATE statement */
82349     if( pSelect ){
82350       zStmt = createTableStmt(db, p);
82351     }else{
82352       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82353       zStmt = sqlite3MPrintf(db, 
82354           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82355       );
82356     }
82357
82358     /* A slot for the record has already been allocated in the 
82359     ** SQLITE_MASTER table.  We just need to update that slot with all
82360     ** the information we've collected.
82361     */
82362     sqlite3NestedParse(pParse,
82363       "UPDATE %Q.%s "
82364          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82365        "WHERE rowid=#%d",
82366       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82367       zType,
82368       p->zName,
82369       p->zName,
82370       pParse->regRoot,
82371       zStmt,
82372       pParse->regRowid
82373     );
82374     sqlite3DbFree(db, zStmt);
82375     sqlite3ChangeCookie(pParse, iDb);
82376
82377 #ifndef SQLITE_OMIT_AUTOINCREMENT
82378     /* Check to see if we need to create an sqlite_sequence table for
82379     ** keeping track of autoincrement keys.
82380     */
82381     if( p->tabFlags & TF_Autoincrement ){
82382       Db *pDb = &db->aDb[iDb];
82383       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82384       if( pDb->pSchema->pSeqTab==0 ){
82385         sqlite3NestedParse(pParse,
82386           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
82387           pDb->zName
82388         );
82389       }
82390     }
82391 #endif
82392
82393     /* Reparse everything to update our internal data structures */
82394     sqlite3VdbeAddParseSchemaOp(v, iDb,
82395                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
82396   }
82397
82398
82399   /* Add the table to the in-memory representation of the database.
82400   */
82401   if( db->init.busy ){
82402     Table *pOld;
82403     Schema *pSchema = p->pSchema;
82404     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82405     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
82406                              sqlite3Strlen30(p->zName),p);
82407     if( pOld ){
82408       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82409       db->mallocFailed = 1;
82410       return;
82411     }
82412     pParse->pNewTable = 0;
82413     db->flags |= SQLITE_InternChanges;
82414
82415 #ifndef SQLITE_OMIT_ALTERTABLE
82416     if( !p->pSelect ){
82417       const char *zName = (const char *)pParse->sNameToken.z;
82418       int nName;
82419       assert( !pSelect && pCons && pEnd );
82420       if( pCons->z==0 ){
82421         pCons = pEnd;
82422       }
82423       nName = (int)((const char *)pCons->z - zName);
82424       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
82425     }
82426 #endif
82427   }
82428 }
82429
82430 #ifndef SQLITE_OMIT_VIEW
82431 /*
82432 ** The parser calls this routine in order to create a new VIEW
82433 */
82434 SQLITE_PRIVATE void sqlite3CreateView(
82435   Parse *pParse,     /* The parsing context */
82436   Token *pBegin,     /* The CREATE token that begins the statement */
82437   Token *pName1,     /* The token that holds the name of the view */
82438   Token *pName2,     /* The token that holds the name of the view */
82439   Select *pSelect,   /* A SELECT statement that will become the new view */
82440   int isTemp,        /* TRUE for a TEMPORARY view */
82441   int noErr          /* Suppress error messages if VIEW already exists */
82442 ){
82443   Table *p;
82444   int n;
82445   const char *z;
82446   Token sEnd;
82447   DbFixer sFix;
82448   Token *pName = 0;
82449   int iDb;
82450   sqlite3 *db = pParse->db;
82451
82452   if( pParse->nVar>0 ){
82453     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
82454     sqlite3SelectDelete(db, pSelect);
82455     return;
82456   }
82457   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82458   p = pParse->pNewTable;
82459   if( p==0 || pParse->nErr ){
82460     sqlite3SelectDelete(db, pSelect);
82461     return;
82462   }
82463   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82464   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82465   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
82466     && sqlite3FixSelect(&sFix, pSelect)
82467   ){
82468     sqlite3SelectDelete(db, pSelect);
82469     return;
82470   }
82471
82472   /* Make a copy of the entire SELECT statement that defines the view.
82473   ** This will force all the Expr.token.z values to be dynamically
82474   ** allocated rather than point to the input string - which means that
82475   ** they will persist after the current sqlite3_exec() call returns.
82476   */
82477   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82478   sqlite3SelectDelete(db, pSelect);
82479   if( db->mallocFailed ){
82480     return;
82481   }
82482   if( !db->init.busy ){
82483     sqlite3ViewGetColumnNames(pParse, p);
82484   }
82485
82486   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82487   ** the end.
82488   */
82489   sEnd = pParse->sLastToken;
82490   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82491     sEnd.z += sEnd.n;
82492   }
82493   sEnd.n = 0;
82494   n = (int)(sEnd.z - pBegin->z);
82495   z = pBegin->z;
82496   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
82497   sEnd.z = &z[n-1];
82498   sEnd.n = 1;
82499
82500   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
82501   sqlite3EndTable(pParse, 0, &sEnd, 0);
82502   return;
82503 }
82504 #endif /* SQLITE_OMIT_VIEW */
82505
82506 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82507 /*
82508 ** The Table structure pTable is really a VIEW.  Fill in the names of
82509 ** the columns of the view in the pTable structure.  Return the number
82510 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82511 */
82512 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
82513   Table *pSelTab;   /* A fake table from which we get the result set */
82514   Select *pSel;     /* Copy of the SELECT that implements the view */
82515   int nErr = 0;     /* Number of errors encountered */
82516   int n;            /* Temporarily holds the number of cursors assigned */
82517   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
82518   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82519
82520   assert( pTable );
82521
82522 #ifndef SQLITE_OMIT_VIRTUALTABLE
82523   if( sqlite3VtabCallConnect(pParse, pTable) ){
82524     return SQLITE_ERROR;
82525   }
82526   if( IsVirtual(pTable) ) return 0;
82527 #endif
82528
82529 #ifndef SQLITE_OMIT_VIEW
82530   /* A positive nCol means the columns names for this view are
82531   ** already known.
82532   */
82533   if( pTable->nCol>0 ) return 0;
82534
82535   /* A negative nCol is a special marker meaning that we are currently
82536   ** trying to compute the column names.  If we enter this routine with
82537   ** a negative nCol, it means two or more views form a loop, like this:
82538   **
82539   **     CREATE VIEW one AS SELECT * FROM two;
82540   **     CREATE VIEW two AS SELECT * FROM one;
82541   **
82542   ** Actually, the error above is now caught prior to reaching this point.
82543   ** But the following test is still important as it does come up
82544   ** in the following:
82545   ** 
82546   **     CREATE TABLE main.ex1(a);
82547   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82548   **     SELECT * FROM temp.ex1;
82549   */
82550   if( pTable->nCol<0 ){
82551     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82552     return 1;
82553   }
82554   assert( pTable->nCol>=0 );
82555
82556   /* If we get this far, it means we need to compute the table names.
82557   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
82558   ** "*" elements in the results set of the view and will assign cursors
82559   ** to the elements of the FROM clause.  But we do not want these changes
82560   ** to be permanent.  So the computation is done on a copy of the SELECT
82561   ** statement that defines the view.
82562   */
82563   assert( pTable->pSelect );
82564   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
82565   if( pSel ){
82566     u8 enableLookaside = db->lookaside.bEnabled;
82567     n = pParse->nTab;
82568     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
82569     pTable->nCol = -1;
82570     db->lookaside.bEnabled = 0;
82571 #ifndef SQLITE_OMIT_AUTHORIZATION
82572     xAuth = db->xAuth;
82573     db->xAuth = 0;
82574     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82575     db->xAuth = xAuth;
82576 #else
82577     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82578 #endif
82579     db->lookaside.bEnabled = enableLookaside;
82580     pParse->nTab = n;
82581     if( pSelTab ){
82582       assert( pTable->aCol==0 );
82583       pTable->nCol = pSelTab->nCol;
82584       pTable->aCol = pSelTab->aCol;
82585       pSelTab->nCol = 0;
82586       pSelTab->aCol = 0;
82587       sqlite3DeleteTable(db, pSelTab);
82588       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
82589       pTable->pSchema->flags |= DB_UnresetViews;
82590     }else{
82591       pTable->nCol = 0;
82592       nErr++;
82593     }
82594     sqlite3SelectDelete(db, pSel);
82595   } else {
82596     nErr++;
82597   }
82598 #endif /* SQLITE_OMIT_VIEW */
82599   return nErr;  
82600 }
82601 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
82602
82603 #ifndef SQLITE_OMIT_VIEW
82604 /*
82605 ** Clear the column names from every VIEW in database idx.
82606 */
82607 static void sqliteViewResetAll(sqlite3 *db, int idx){
82608   HashElem *i;
82609   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
82610   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82611   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
82612     Table *pTab = sqliteHashData(i);
82613     if( pTab->pSelect ){
82614       sqliteDeleteColumnNames(db, pTab);
82615       pTab->aCol = 0;
82616       pTab->nCol = 0;
82617     }
82618   }
82619   DbClearProperty(db, idx, DB_UnresetViews);
82620 }
82621 #else
82622 # define sqliteViewResetAll(A,B)
82623 #endif /* SQLITE_OMIT_VIEW */
82624
82625 /*
82626 ** This function is called by the VDBE to adjust the internal schema
82627 ** used by SQLite when the btree layer moves a table root page. The
82628 ** root-page of a table or index in database iDb has changed from iFrom
82629 ** to iTo.
82630 **
82631 ** Ticket #1728:  The symbol table might still contain information
82632 ** on tables and/or indices that are the process of being deleted.
82633 ** If you are unlucky, one of those deleted indices or tables might
82634 ** have the same rootpage number as the real table or index that is
82635 ** being moved.  So we cannot stop searching after the first match 
82636 ** because the first match might be for one of the deleted indices
82637 ** or tables and not the table/index that is actually being moved.
82638 ** We must continue looping until all tables and indices with
82639 ** rootpage==iFrom have been converted to have a rootpage of iTo
82640 ** in order to be certain that we got the right one.
82641 */
82642 #ifndef SQLITE_OMIT_AUTOVACUUM
82643 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
82644   HashElem *pElem;
82645   Hash *pHash;
82646   Db *pDb;
82647
82648   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82649   pDb = &db->aDb[iDb];
82650   pHash = &pDb->pSchema->tblHash;
82651   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82652     Table *pTab = sqliteHashData(pElem);
82653     if( pTab->tnum==iFrom ){
82654       pTab->tnum = iTo;
82655     }
82656   }
82657   pHash = &pDb->pSchema->idxHash;
82658   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82659     Index *pIdx = sqliteHashData(pElem);
82660     if( pIdx->tnum==iFrom ){
82661       pIdx->tnum = iTo;
82662     }
82663   }
82664 }
82665 #endif
82666
82667 /*
82668 ** Write code to erase the table with root-page iTable from database iDb.
82669 ** Also write code to modify the sqlite_master table and internal schema
82670 ** if a root-page of another table is moved by the btree-layer whilst
82671 ** erasing iTable (this can happen with an auto-vacuum database).
82672 */ 
82673 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82674   Vdbe *v = sqlite3GetVdbe(pParse);
82675   int r1 = sqlite3GetTempReg(pParse);
82676   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82677   sqlite3MayAbort(pParse);
82678 #ifndef SQLITE_OMIT_AUTOVACUUM
82679   /* OP_Destroy stores an in integer r1. If this integer
82680   ** is non-zero, then it is the root page number of a table moved to
82681   ** location iTable. The following code modifies the sqlite_master table to
82682   ** reflect this.
82683   **
82684   ** The "#NNN" in the SQL is a special constant that means whatever value
82685   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82686   ** token for additional information.
82687   */
82688   sqlite3NestedParse(pParse, 
82689      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82690      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82691 #endif
82692   sqlite3ReleaseTempReg(pParse, r1);
82693 }
82694
82695 /*
82696 ** Write VDBE code to erase table pTab and all associated indices on disk.
82697 ** Code to update the sqlite_master tables and internal schema definitions
82698 ** in case a root-page belonging to another table is moved by the btree layer
82699 ** is also added (this can happen with an auto-vacuum database).
82700 */
82701 static void destroyTable(Parse *pParse, Table *pTab){
82702 #ifdef SQLITE_OMIT_AUTOVACUUM
82703   Index *pIdx;
82704   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82705   destroyRootPage(pParse, pTab->tnum, iDb);
82706   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82707     destroyRootPage(pParse, pIdx->tnum, iDb);
82708   }
82709 #else
82710   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
82711   ** is not defined), then it is important to call OP_Destroy on the
82712   ** table and index root-pages in order, starting with the numerically 
82713   ** largest root-page number. This guarantees that none of the root-pages
82714   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82715   ** following were coded:
82716   **
82717   ** OP_Destroy 4 0
82718   ** ...
82719   ** OP_Destroy 5 0
82720   **
82721   ** and root page 5 happened to be the largest root-page number in the
82722   ** database, then root page 5 would be moved to page 4 by the 
82723   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82724   ** a free-list page.
82725   */
82726   int iTab = pTab->tnum;
82727   int iDestroyed = 0;
82728
82729   while( 1 ){
82730     Index *pIdx;
82731     int iLargest = 0;
82732
82733     if( iDestroyed==0 || iTab<iDestroyed ){
82734       iLargest = iTab;
82735     }
82736     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82737       int iIdx = pIdx->tnum;
82738       assert( pIdx->pSchema==pTab->pSchema );
82739       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82740         iLargest = iIdx;
82741       }
82742     }
82743     if( iLargest==0 ){
82744       return;
82745     }else{
82746       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82747       assert( iDb>=0 && iDb<pParse->db->nDb );
82748       destroyRootPage(pParse, iLargest, iDb);
82749       iDestroyed = iLargest;
82750     }
82751   }
82752 #endif
82753 }
82754
82755 /*
82756 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
82757 ** after a DROP INDEX or DROP TABLE command.
82758 */
82759 static void sqlite3ClearStatTables(
82760   Parse *pParse,         /* The parsing context */
82761   int iDb,               /* The database number */
82762   const char *zType,     /* "idx" or "tbl" */
82763   const char *zName      /* Name of index or table */
82764 ){
82765   int i;
82766   const char *zDbName = pParse->db->aDb[iDb].zName;
82767   for(i=1; i<=3; i++){
82768     char zTab[24];
82769     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
82770     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
82771       sqlite3NestedParse(pParse,
82772         "DELETE FROM %Q.%s WHERE %s=%Q",
82773         zDbName, zTab, zType, zName
82774       );
82775     }
82776   }
82777 }
82778
82779 /*
82780 ** Generate code to drop a table.
82781 */
82782 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82783   Vdbe *v;
82784   sqlite3 *db = pParse->db;
82785   Trigger *pTrigger;
82786   Db *pDb = &db->aDb[iDb];
82787
82788   v = sqlite3GetVdbe(pParse);
82789   assert( v!=0 );
82790   sqlite3BeginWriteOperation(pParse, 1, iDb);
82791
82792 #ifndef SQLITE_OMIT_VIRTUALTABLE
82793   if( IsVirtual(pTab) ){
82794     sqlite3VdbeAddOp0(v, OP_VBegin);
82795   }
82796 #endif
82797
82798   /* Drop all triggers associated with the table being dropped. Code
82799   ** is generated to remove entries from sqlite_master and/or
82800   ** sqlite_temp_master if required.
82801   */
82802   pTrigger = sqlite3TriggerList(pParse, pTab);
82803   while( pTrigger ){
82804     assert( pTrigger->pSchema==pTab->pSchema || 
82805         pTrigger->pSchema==db->aDb[1].pSchema );
82806     sqlite3DropTriggerPtr(pParse, pTrigger);
82807     pTrigger = pTrigger->pNext;
82808   }
82809
82810 #ifndef SQLITE_OMIT_AUTOINCREMENT
82811   /* Remove any entries of the sqlite_sequence table associated with
82812   ** the table being dropped. This is done before the table is dropped
82813   ** at the btree level, in case the sqlite_sequence table needs to
82814   ** move as a result of the drop (can happen in auto-vacuum mode).
82815   */
82816   if( pTab->tabFlags & TF_Autoincrement ){
82817     sqlite3NestedParse(pParse,
82818       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
82819       pDb->zName, pTab->zName
82820     );
82821   }
82822 #endif
82823
82824   /* Drop all SQLITE_MASTER table and index entries that refer to the
82825   ** table. The program name loops through the master table and deletes
82826   ** every row that refers to a table of the same name as the one being
82827   ** dropped. Triggers are handled seperately because a trigger can be
82828   ** created in the temp database that refers to a table in another
82829   ** database.
82830   */
82831   sqlite3NestedParse(pParse, 
82832       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
82833       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
82834   if( !isView && !IsVirtual(pTab) ){
82835     destroyTable(pParse, pTab);
82836   }
82837
82838   /* Remove the table entry from SQLite's internal schema and modify
82839   ** the schema cookie.
82840   */
82841   if( IsVirtual(pTab) ){
82842     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
82843   }
82844   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
82845   sqlite3ChangeCookie(pParse, iDb);
82846   sqliteViewResetAll(db, iDb);
82847 }
82848
82849 /*
82850 ** This routine is called to do the work of a DROP TABLE statement.
82851 ** pName is the name of the table to be dropped.
82852 */
82853 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
82854   Table *pTab;
82855   Vdbe *v;
82856   sqlite3 *db = pParse->db;
82857   int iDb;
82858
82859   if( db->mallocFailed ){
82860     goto exit_drop_table;
82861   }
82862   assert( pParse->nErr==0 );
82863   assert( pName->nSrc==1 );
82864   if( noErr ) db->suppressErr++;
82865   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
82866   if( noErr ) db->suppressErr--;
82867
82868   if( pTab==0 ){
82869     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82870     goto exit_drop_table;
82871   }
82872   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82873   assert( iDb>=0 && iDb<db->nDb );
82874
82875   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
82876   ** it is initialized.
82877   */
82878   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
82879     goto exit_drop_table;
82880   }
82881 #ifndef SQLITE_OMIT_AUTHORIZATION
82882   {
82883     int code;
82884     const char *zTab = SCHEMA_TABLE(iDb);
82885     const char *zDb = db->aDb[iDb].zName;
82886     const char *zArg2 = 0;
82887     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
82888       goto exit_drop_table;
82889     }
82890     if( isView ){
82891       if( !OMIT_TEMPDB && iDb==1 ){
82892         code = SQLITE_DROP_TEMP_VIEW;
82893       }else{
82894         code = SQLITE_DROP_VIEW;
82895       }
82896 #ifndef SQLITE_OMIT_VIRTUALTABLE
82897     }else if( IsVirtual(pTab) ){
82898       code = SQLITE_DROP_VTABLE;
82899       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
82900 #endif
82901     }else{
82902       if( !OMIT_TEMPDB && iDb==1 ){
82903         code = SQLITE_DROP_TEMP_TABLE;
82904       }else{
82905         code = SQLITE_DROP_TABLE;
82906       }
82907     }
82908     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
82909       goto exit_drop_table;
82910     }
82911     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
82912       goto exit_drop_table;
82913     }
82914   }
82915 #endif
82916   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
82917     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
82918     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
82919     goto exit_drop_table;
82920   }
82921
82922 #ifndef SQLITE_OMIT_VIEW
82923   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
82924   ** on a table.
82925   */
82926   if( isView && pTab->pSelect==0 ){
82927     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
82928     goto exit_drop_table;
82929   }
82930   if( !isView && pTab->pSelect ){
82931     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
82932     goto exit_drop_table;
82933   }
82934 #endif
82935
82936   /* Generate code to remove the table from the master table
82937   ** on disk.
82938   */
82939   v = sqlite3GetVdbe(pParse);
82940   if( v ){
82941     sqlite3BeginWriteOperation(pParse, 1, iDb);
82942     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
82943     sqlite3FkDropTable(pParse, pName, pTab);
82944     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
82945   }
82946
82947 exit_drop_table:
82948   sqlite3SrcListDelete(db, pName);
82949 }
82950
82951 /*
82952 ** This routine is called to create a new foreign key on the table
82953 ** currently under construction.  pFromCol determines which columns
82954 ** in the current table point to the foreign key.  If pFromCol==0 then
82955 ** connect the key to the last column inserted.  pTo is the name of
82956 ** the table referred to.  pToCol is a list of tables in the other
82957 ** pTo table that the foreign key points to.  flags contains all
82958 ** information about the conflict resolution algorithms specified
82959 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
82960 **
82961 ** An FKey structure is created and added to the table currently
82962 ** under construction in the pParse->pNewTable field.
82963 **
82964 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
82965 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
82966 */
82967 SQLITE_PRIVATE void sqlite3CreateForeignKey(
82968   Parse *pParse,       /* Parsing context */
82969   ExprList *pFromCol,  /* Columns in this table that point to other table */
82970   Token *pTo,          /* Name of the other table */
82971   ExprList *pToCol,    /* Columns in the other table */
82972   int flags            /* Conflict resolution algorithms. */
82973 ){
82974   sqlite3 *db = pParse->db;
82975 #ifndef SQLITE_OMIT_FOREIGN_KEY
82976   FKey *pFKey = 0;
82977   FKey *pNextTo;
82978   Table *p = pParse->pNewTable;
82979   int nByte;
82980   int i;
82981   int nCol;
82982   char *z;
82983
82984   assert( pTo!=0 );
82985   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
82986   if( pFromCol==0 ){
82987     int iCol = p->nCol-1;
82988     if( NEVER(iCol<0) ) goto fk_end;
82989     if( pToCol && pToCol->nExpr!=1 ){
82990       sqlite3ErrorMsg(pParse, "foreign key on %s"
82991          " should reference only one column of table %T",
82992          p->aCol[iCol].zName, pTo);
82993       goto fk_end;
82994     }
82995     nCol = 1;
82996   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
82997     sqlite3ErrorMsg(pParse,
82998         "number of columns in foreign key does not match the number of "
82999         "columns in the referenced table");
83000     goto fk_end;
83001   }else{
83002     nCol = pFromCol->nExpr;
83003   }
83004   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83005   if( pToCol ){
83006     for(i=0; i<pToCol->nExpr; i++){
83007       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
83008     }
83009   }
83010   pFKey = sqlite3DbMallocZero(db, nByte );
83011   if( pFKey==0 ){
83012     goto fk_end;
83013   }
83014   pFKey->pFrom = p;
83015   pFKey->pNextFrom = p->pFKey;
83016   z = (char*)&pFKey->aCol[nCol];
83017   pFKey->zTo = z;
83018   memcpy(z, pTo->z, pTo->n);
83019   z[pTo->n] = 0;
83020   sqlite3Dequote(z);
83021   z += pTo->n+1;
83022   pFKey->nCol = nCol;
83023   if( pFromCol==0 ){
83024     pFKey->aCol[0].iFrom = p->nCol-1;
83025   }else{
83026     for(i=0; i<nCol; i++){
83027       int j;
83028       for(j=0; j<p->nCol; j++){
83029         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83030           pFKey->aCol[i].iFrom = j;
83031           break;
83032         }
83033       }
83034       if( j>=p->nCol ){
83035         sqlite3ErrorMsg(pParse, 
83036           "unknown column \"%s\" in foreign key definition", 
83037           pFromCol->a[i].zName);
83038         goto fk_end;
83039       }
83040     }
83041   }
83042   if( pToCol ){
83043     for(i=0; i<nCol; i++){
83044       int n = sqlite3Strlen30(pToCol->a[i].zName);
83045       pFKey->aCol[i].zCol = z;
83046       memcpy(z, pToCol->a[i].zName, n);
83047       z[n] = 0;
83048       z += n+1;
83049     }
83050   }
83051   pFKey->isDeferred = 0;
83052   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83053   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83054
83055   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
83056   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
83057       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
83058   );
83059   if( pNextTo==pFKey ){
83060     db->mallocFailed = 1;
83061     goto fk_end;
83062   }
83063   if( pNextTo ){
83064     assert( pNextTo->pPrevTo==0 );
83065     pFKey->pNextTo = pNextTo;
83066     pNextTo->pPrevTo = pFKey;
83067   }
83068
83069   /* Link the foreign key to the table as the last step.
83070   */
83071   p->pFKey = pFKey;
83072   pFKey = 0;
83073
83074 fk_end:
83075   sqlite3DbFree(db, pFKey);
83076 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
83077   sqlite3ExprListDelete(db, pFromCol);
83078   sqlite3ExprListDelete(db, pToCol);
83079 }
83080
83081 /*
83082 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83083 ** clause is seen as part of a foreign key definition.  The isDeferred
83084 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83085 ** The behavior of the most recently created foreign key is adjusted
83086 ** accordingly.
83087 */
83088 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
83089 #ifndef SQLITE_OMIT_FOREIGN_KEY
83090   Table *pTab;
83091   FKey *pFKey;
83092   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83093   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83094   pFKey->isDeferred = (u8)isDeferred;
83095 #endif
83096 }
83097
83098 /*
83099 ** Generate code that will erase and refill index *pIdx.  This is
83100 ** used to initialize a newly created index or to recompute the
83101 ** content of an index in response to a REINDEX command.
83102 **
83103 ** if memRootPage is not negative, it means that the index is newly
83104 ** created.  The register specified by memRootPage contains the
83105 ** root page number of the index.  If memRootPage is negative, then
83106 ** the index already exists and must be cleared before being refilled and
83107 ** the root page number of the index is taken from pIndex->tnum.
83108 */
83109 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83110   Table *pTab = pIndex->pTable;  /* The table that is indexed */
83111   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83112   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83113   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83114   int addr1;                     /* Address of top of loop */
83115   int addr2;                     /* Address to jump to for next iteration */
83116   int tnum;                      /* Root page of index */
83117   Vdbe *v;                       /* Generate code into this virtual machine */
83118   KeyInfo *pKey;                 /* KeyInfo for index */
83119 #ifdef SQLITE_OMIT_MERGE_SORT
83120   int regIdxKey;                 /* Registers containing the index key */
83121 #endif
83122   int regRecord;                 /* Register holding assemblied index record */
83123   sqlite3 *db = pParse->db;      /* The database connection */
83124   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83125
83126 #ifndef SQLITE_OMIT_AUTHORIZATION
83127   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
83128       db->aDb[iDb].zName ) ){
83129     return;
83130   }
83131 #endif
83132
83133   /* Require a write-lock on the table to perform this operation */
83134   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83135
83136   v = sqlite3GetVdbe(pParse);
83137   if( v==0 ) return;
83138   if( memRootPage>=0 ){
83139     tnum = memRootPage;
83140   }else{
83141     tnum = pIndex->tnum;
83142     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83143   }
83144   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
83145   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
83146                     (char *)pKey, P4_KEYINFO_HANDOFF);
83147   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
83148
83149 #ifndef SQLITE_OMIT_MERGE_SORT
83150   /* Open the sorter cursor if we are to use one. */
83151   iSorter = pParse->nTab++;
83152   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83153 #else
83154   iSorter = iTab;
83155 #endif
83156
83157   /* Open the table. Loop through all rows of the table, inserting index
83158   ** records into the sorter. */
83159   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83160   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83161   regRecord = sqlite3GetTempReg(pParse);
83162
83163 #ifndef SQLITE_OMIT_MERGE_SORT
83164   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83165   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83166   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83167   sqlite3VdbeJumpHere(v, addr1);
83168   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83169   if( pIndex->onError!=OE_None ){
83170     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
83171     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
83172     addr2 = sqlite3VdbeCurrentAddr(v);
83173     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83174     sqlite3HaltConstraint(
83175         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
83176     );
83177   }else{
83178     addr2 = sqlite3VdbeCurrentAddr(v);
83179   }
83180   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83181   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83182   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83183 #else
83184   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83185   addr2 = addr1 + 1;
83186   if( pIndex->onError!=OE_None ){
83187     const int regRowid = regIdxKey + pIndex->nColumn;
83188     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
83189     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
83190
83191     /* The registers accessed by the OP_IsUnique opcode were allocated
83192     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
83193     ** call above. Just before that function was freed they were released
83194     ** (made available to the compiler for reuse) using 
83195     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
83196     ** opcode use the values stored within seems dangerous. However, since
83197     ** we can be sure that no other temp registers have been allocated
83198     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
83199     */
83200     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
83201     sqlite3HaltConstraint(
83202         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
83203   }
83204   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
83205   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83206 #endif
83207   sqlite3ReleaseTempReg(pParse, regRecord);
83208   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83209   sqlite3VdbeJumpHere(v, addr1);
83210
83211   sqlite3VdbeAddOp1(v, OP_Close, iTab);
83212   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
83213   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
83214 }
83215
83216 /*
83217 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
83218 ** and pTblList is the name of the table that is to be indexed.  Both will 
83219 ** be NULL for a primary key or an index that is created to satisfy a
83220 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83221 ** as the table to be indexed.  pParse->pNewTable is a table that is
83222 ** currently being constructed by a CREATE TABLE statement.
83223 **
83224 ** pList is a list of columns to be indexed.  pList will be NULL if this
83225 ** is a primary key or unique-constraint on the most recent column added
83226 ** to the table currently under construction.  
83227 **
83228 ** If the index is created successfully, return a pointer to the new Index
83229 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
83230 ** as the tables primary key (Index.autoIndex==2).
83231 */
83232 SQLITE_PRIVATE Index *sqlite3CreateIndex(
83233   Parse *pParse,     /* All information about this parse */
83234   Token *pName1,     /* First part of index name. May be NULL */
83235   Token *pName2,     /* Second part of index name. May be NULL */
83236   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83237   ExprList *pList,   /* A list of columns to be indexed */
83238   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83239   Token *pStart,     /* The CREATE token that begins this statement */
83240   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83241   int sortOrder,     /* Sort order of primary key when pList==NULL */
83242   int ifNotExist     /* Omit error if index already exists */
83243 ){
83244   Index *pRet = 0;     /* Pointer to return */
83245   Table *pTab = 0;     /* Table to be indexed */
83246   Index *pIndex = 0;   /* The index to be created */
83247   char *zName = 0;     /* Name of the index */
83248   int nName;           /* Number of characters in zName */
83249   int i, j;
83250   Token nullId;        /* Fake token for an empty ID list */
83251   DbFixer sFix;        /* For assigning database names to pTable */
83252   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83253   sqlite3 *db = pParse->db;
83254   Db *pDb;             /* The specific table containing the indexed database */
83255   int iDb;             /* Index of the database that is being written */
83256   Token *pName = 0;    /* Unqualified name of the index to create */
83257   struct ExprList_item *pListItem; /* For looping over pList */
83258   int nCol;
83259   int nExtra = 0;
83260   char *zExtra;
83261
83262   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83263   assert( pParse->nErr==0 );      /* Never called with prior errors */
83264   if( db->mallocFailed || IN_DECLARE_VTAB ){
83265     goto exit_create_index;
83266   }
83267   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83268     goto exit_create_index;
83269   }
83270
83271   /*
83272   ** Find the table that is to be indexed.  Return early if not found.
83273   */
83274   if( pTblName!=0 ){
83275
83276     /* Use the two-part index name to determine the database 
83277     ** to search for the table. 'Fix' the table name to this db
83278     ** before looking up the table.
83279     */
83280     assert( pName1 && pName2 );
83281     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83282     if( iDb<0 ) goto exit_create_index;
83283     assert( pName && pName->z );
83284
83285 #ifndef SQLITE_OMIT_TEMPDB
83286     /* If the index name was unqualified, check if the table
83287     ** is a temp table. If so, set the database to 1. Do not do this
83288     ** if initialising a database schema.
83289     */
83290     if( !db->init.busy ){
83291       pTab = sqlite3SrcListLookup(pParse, pTblName);
83292       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83293         iDb = 1;
83294       }
83295     }
83296 #endif
83297
83298     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
83299         sqlite3FixSrcList(&sFix, pTblName)
83300     ){
83301       /* Because the parser constructs pTblName from a single identifier,
83302       ** sqlite3FixSrcList can never fail. */
83303       assert(0);
83304     }
83305     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
83306     assert( db->mallocFailed==0 || pTab==0 );
83307     if( pTab==0 ) goto exit_create_index;
83308     assert( db->aDb[iDb].pSchema==pTab->pSchema );
83309   }else{
83310     assert( pName==0 );
83311     assert( pStart==0 );
83312     pTab = pParse->pNewTable;
83313     if( !pTab ) goto exit_create_index;
83314     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83315   }
83316   pDb = &db->aDb[iDb];
83317
83318   assert( pTab!=0 );
83319   assert( pParse->nErr==0 );
83320   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
83321        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
83322     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83323     goto exit_create_index;
83324   }
83325 #ifndef SQLITE_OMIT_VIEW
83326   if( pTab->pSelect ){
83327     sqlite3ErrorMsg(pParse, "views may not be indexed");
83328     goto exit_create_index;
83329   }
83330 #endif
83331 #ifndef SQLITE_OMIT_VIRTUALTABLE
83332   if( IsVirtual(pTab) ){
83333     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
83334     goto exit_create_index;
83335   }
83336 #endif
83337
83338   /*
83339   ** Find the name of the index.  Make sure there is not already another
83340   ** index or table with the same name.  
83341   **
83342   ** Exception:  If we are reading the names of permanent indices from the
83343   ** sqlite_master table (because some other process changed the schema) and
83344   ** one of the index names collides with the name of a temporary table or
83345   ** index, then we will continue to process this index.
83346   **
83347   ** If pName==0 it means that we are
83348   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83349   ** own name.
83350   */
83351   if( pName ){
83352     zName = sqlite3NameFromToken(db, pName);
83353     if( zName==0 ) goto exit_create_index;
83354     assert( pName->z!=0 );
83355     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83356       goto exit_create_index;
83357     }
83358     if( !db->init.busy ){
83359       if( sqlite3FindTable(db, zName, 0)!=0 ){
83360         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
83361         goto exit_create_index;
83362       }
83363     }
83364     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
83365       if( !ifNotExist ){
83366         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
83367       }else{
83368         assert( !db->init.busy );
83369         sqlite3CodeVerifySchema(pParse, iDb);
83370       }
83371       goto exit_create_index;
83372     }
83373   }else{
83374     int n;
83375     Index *pLoop;
83376     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83377     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
83378     if( zName==0 ){
83379       goto exit_create_index;
83380     }
83381   }
83382
83383   /* Check for authorization to create an index.
83384   */
83385 #ifndef SQLITE_OMIT_AUTHORIZATION
83386   {
83387     const char *zDb = pDb->zName;
83388     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83389       goto exit_create_index;
83390     }
83391     i = SQLITE_CREATE_INDEX;
83392     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
83393     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83394       goto exit_create_index;
83395     }
83396   }
83397 #endif
83398
83399   /* If pList==0, it means this routine was called to make a primary
83400   ** key out of the last column added to the table under construction.
83401   ** So create a fake list to simulate this.
83402   */
83403   if( pList==0 ){
83404     nullId.z = pTab->aCol[pTab->nCol-1].zName;
83405     nullId.n = sqlite3Strlen30((char*)nullId.z);
83406     pList = sqlite3ExprListAppend(pParse, 0, 0);
83407     if( pList==0 ) goto exit_create_index;
83408     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
83409     pList->a[0].sortOrder = (u8)sortOrder;
83410   }
83411
83412   /* Figure out how many bytes of space are required to store explicitly
83413   ** specified collation sequence names.
83414   */
83415   for(i=0; i<pList->nExpr; i++){
83416     Expr *pExpr = pList->a[i].pExpr;
83417     if( pExpr ){
83418       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
83419       if( pColl ){
83420         nExtra += (1 + sqlite3Strlen30(pColl->zName));
83421       }
83422     }
83423   }
83424
83425   /* 
83426   ** Allocate the index structure. 
83427   */
83428   nName = sqlite3Strlen30(zName);
83429   nCol = pList->nExpr;
83430   pIndex = sqlite3DbMallocZero(db, 
83431       ROUND8(sizeof(Index)) +              /* Index structure  */
83432       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
83433       sizeof(char *)*nCol +                /* Index.azColl     */
83434       sizeof(int)*nCol +                   /* Index.aiColumn   */
83435       sizeof(u8)*nCol +                    /* Index.aSortOrder */
83436       nName + 1 +                          /* Index.zName      */
83437       nExtra                               /* Collation sequence names */
83438   );
83439   if( db->mallocFailed ){
83440     goto exit_create_index;
83441   }
83442   zExtra = (char*)pIndex;
83443   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
83444   pIndex->azColl = (char**)
83445      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
83446   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
83447   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
83448   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83449   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83450   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83451   zExtra = (char *)(&pIndex->zName[nName+1]);
83452   memcpy(pIndex->zName, zName, nName+1);
83453   pIndex->pTable = pTab;
83454   pIndex->nColumn = pList->nExpr;
83455   pIndex->onError = (u8)onError;
83456   pIndex->autoIndex = (u8)(pName==0);
83457   pIndex->pSchema = db->aDb[iDb].pSchema;
83458   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83459
83460   /* Check to see if we should honor DESC requests on index columns
83461   */
83462   if( pDb->pSchema->file_format>=4 ){
83463     sortOrderMask = -1;   /* Honor DESC */
83464   }else{
83465     sortOrderMask = 0;    /* Ignore DESC */
83466   }
83467
83468   /* Scan the names of the columns of the table to be indexed and
83469   ** load the column indices into the Index structure.  Report an error
83470   ** if any column is not found.
83471   **
83472   ** TODO:  Add a test to make sure that the same column is not named
83473   ** more than once within the same index.  Only the first instance of
83474   ** the column will ever be used by the optimizer.  Note that using the
83475   ** same column more than once cannot be an error because that would 
83476   ** break backwards compatibility - it needs to be a warning.
83477   */
83478   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83479     const char *zColName = pListItem->zName;
83480     Column *pTabCol;
83481     int requestedSortOrder;
83482     CollSeq *pColl;                /* Collating sequence */
83483     char *zColl;                   /* Collation sequence name */
83484
83485     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83486       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
83487     }
83488     if( j>=pTab->nCol ){
83489       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
83490         pTab->zName, zColName);
83491       pParse->checkSchema = 1;
83492       goto exit_create_index;
83493     }
83494     pIndex->aiColumn[i] = j;
83495     if( pListItem->pExpr
83496      && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
83497     ){
83498       int nColl;
83499       zColl = pColl->zName;
83500       nColl = sqlite3Strlen30(zColl) + 1;
83501       assert( nExtra>=nColl );
83502       memcpy(zExtra, zColl, nColl);
83503       zColl = zExtra;
83504       zExtra += nColl;
83505       nExtra -= nColl;
83506     }else{
83507       zColl = pTab->aCol[j].zColl;
83508       if( !zColl ){
83509         zColl = "BINARY";
83510       }
83511     }
83512     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
83513       goto exit_create_index;
83514     }
83515     pIndex->azColl[i] = zColl;
83516     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83517     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83518   }
83519   sqlite3DefaultRowEst(pIndex);
83520
83521   if( pTab==pParse->pNewTable ){
83522     /* This routine has been called to create an automatic index as a
83523     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83524     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83525     ** i.e. one of:
83526     **
83527     ** CREATE TABLE t(x PRIMARY KEY, y);
83528     ** CREATE TABLE t(x, y, UNIQUE(x, y));
83529     **
83530     ** Either way, check to see if the table already has such an index. If
83531     ** so, don't bother creating this one. This only applies to
83532     ** automatically created indices. Users can do as they wish with
83533     ** explicit indices.
83534     **
83535     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83536     ** (and thus suppressing the second one) even if they have different
83537     ** sort orders.
83538     **
83539     ** If there are different collating sequences or if the columns of
83540     ** the constraint occur in different orders, then the constraints are
83541     ** considered distinct and both result in separate indices.
83542     */
83543     Index *pIdx;
83544     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83545       int k;
83546       assert( pIdx->onError!=OE_None );
83547       assert( pIdx->autoIndex );
83548       assert( pIndex->onError!=OE_None );
83549
83550       if( pIdx->nColumn!=pIndex->nColumn ) continue;
83551       for(k=0; k<pIdx->nColumn; k++){
83552         const char *z1;
83553         const char *z2;
83554         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83555         z1 = pIdx->azColl[k];
83556         z2 = pIndex->azColl[k];
83557         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
83558       }
83559       if( k==pIdx->nColumn ){
83560         if( pIdx->onError!=pIndex->onError ){
83561           /* This constraint creates the same index as a previous
83562           ** constraint specified somewhere in the CREATE TABLE statement.
83563           ** However the ON CONFLICT clauses are different. If both this 
83564           ** constraint and the previous equivalent constraint have explicit
83565           ** ON CONFLICT clauses this is an error. Otherwise, use the
83566           ** explicitly specified behaviour for the index.
83567           */
83568           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83569             sqlite3ErrorMsg(pParse, 
83570                 "conflicting ON CONFLICT clauses specified", 0);
83571           }
83572           if( pIdx->onError==OE_Default ){
83573             pIdx->onError = pIndex->onError;
83574           }
83575         }
83576         goto exit_create_index;
83577       }
83578     }
83579   }
83580
83581   /* Link the new Index structure to its table and to the other
83582   ** in-memory database structures. 
83583   */
83584   if( db->init.busy ){
83585     Index *p;
83586     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83587     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
83588                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
83589                           pIndex);
83590     if( p ){
83591       assert( p==pIndex );  /* Malloc must have failed */
83592       db->mallocFailed = 1;
83593       goto exit_create_index;
83594     }
83595     db->flags |= SQLITE_InternChanges;
83596     if( pTblName!=0 ){
83597       pIndex->tnum = db->init.newTnum;
83598     }
83599   }
83600
83601   /* If the db->init.busy is 0 then create the index on disk.  This
83602   ** involves writing the index into the master table and filling in the
83603   ** index with the current table contents.
83604   **
83605   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
83606   ** command.  db->init.busy is 1 when a database is opened and 
83607   ** CREATE INDEX statements are read out of the master table.  In
83608   ** the latter case the index already exists on disk, which is why
83609   ** we don't want to recreate it.
83610   **
83611   ** If pTblName==0 it means this index is generated as a primary key
83612   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83613   ** has just been created, it contains no data and the index initialization
83614   ** step can be skipped.
83615   */
83616   else{ /* if( db->init.busy==0 ) */
83617     Vdbe *v;
83618     char *zStmt;
83619     int iMem = ++pParse->nMem;
83620
83621     v = sqlite3GetVdbe(pParse);
83622     if( v==0 ) goto exit_create_index;
83623
83624
83625     /* Create the rootpage for the index
83626     */
83627     sqlite3BeginWriteOperation(pParse, 1, iDb);
83628     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83629
83630     /* Gather the complete text of the CREATE INDEX statement into
83631     ** the zStmt variable
83632     */
83633     if( pStart ){
83634       assert( pEnd!=0 );
83635       /* A named index with an explicit CREATE INDEX statement */
83636       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
83637         onError==OE_None ? "" : " UNIQUE",
83638         (int)(pEnd->z - pName->z) + 1,
83639         pName->z);
83640     }else{
83641       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83642       /* zStmt = sqlite3MPrintf(""); */
83643       zStmt = 0;
83644     }
83645
83646     /* Add an entry in sqlite_master for this index
83647     */
83648     sqlite3NestedParse(pParse, 
83649         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83650         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83651         pIndex->zName,
83652         pTab->zName,
83653         iMem,
83654         zStmt
83655     );
83656     sqlite3DbFree(db, zStmt);
83657
83658     /* Fill the index with data and reparse the schema. Code an OP_Expire
83659     ** to invalidate all pre-compiled statements.
83660     */
83661     if( pTblName ){
83662       sqlite3RefillIndex(pParse, pIndex, iMem);
83663       sqlite3ChangeCookie(pParse, iDb);
83664       sqlite3VdbeAddParseSchemaOp(v, iDb,
83665          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83666       sqlite3VdbeAddOp1(v, OP_Expire, 0);
83667     }
83668   }
83669
83670   /* When adding an index to the list of indices for a table, make
83671   ** sure all indices labeled OE_Replace come after all those labeled
83672   ** OE_Ignore.  This is necessary for the correct constraint check
83673   ** processing (in sqlite3GenerateConstraintChecks()) as part of
83674   ** UPDATE and INSERT statements.  
83675   */
83676   if( db->init.busy || pTblName==0 ){
83677     if( onError!=OE_Replace || pTab->pIndex==0
83678          || pTab->pIndex->onError==OE_Replace){
83679       pIndex->pNext = pTab->pIndex;
83680       pTab->pIndex = pIndex;
83681     }else{
83682       Index *pOther = pTab->pIndex;
83683       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83684         pOther = pOther->pNext;
83685       }
83686       pIndex->pNext = pOther->pNext;
83687       pOther->pNext = pIndex;
83688     }
83689     pRet = pIndex;
83690     pIndex = 0;
83691   }
83692
83693   /* Clean up before exiting */
83694 exit_create_index:
83695   if( pIndex ){
83696     sqlite3DbFree(db, pIndex->zColAff);
83697     sqlite3DbFree(db, pIndex);
83698   }
83699   sqlite3ExprListDelete(db, pList);
83700   sqlite3SrcListDelete(db, pTblName);
83701   sqlite3DbFree(db, zName);
83702   return pRet;
83703 }
83704
83705 /*
83706 ** Fill the Index.aiRowEst[] array with default information - information
83707 ** to be used when we have not run the ANALYZE command.
83708 **
83709 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83710 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83711 ** number of rows in the table that match any particular value of the
83712 ** first column of the index.  aiRowEst[2] is an estimate of the number
83713 ** of rows that match any particular combiniation of the first 2 columns
83714 ** of the index.  And so forth.  It must always be the case that
83715 *
83716 **           aiRowEst[N]<=aiRowEst[N-1]
83717 **           aiRowEst[N]>=1
83718 **
83719 ** Apart from that, we have little to go on besides intuition as to
83720 ** how aiRowEst[] should be initialized.  The numbers generated here
83721 ** are based on typical values found in actual indices.
83722 */
83723 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
83724   tRowcnt *a = pIdx->aiRowEst;
83725   int i;
83726   tRowcnt n;
83727   assert( a!=0 );
83728   a[0] = pIdx->pTable->nRowEst;
83729   if( a[0]<10 ) a[0] = 10;
83730   n = 10;
83731   for(i=1; i<=pIdx->nColumn; i++){
83732     a[i] = n;
83733     if( n>5 ) n--;
83734   }
83735   if( pIdx->onError!=OE_None ){
83736     a[pIdx->nColumn] = 1;
83737   }
83738 }
83739
83740 /*
83741 ** This routine will drop an existing named index.  This routine
83742 ** implements the DROP INDEX statement.
83743 */
83744 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83745   Index *pIndex;
83746   Vdbe *v;
83747   sqlite3 *db = pParse->db;
83748   int iDb;
83749
83750   assert( pParse->nErr==0 );   /* Never called with prior errors */
83751   if( db->mallocFailed ){
83752     goto exit_drop_index;
83753   }
83754   assert( pName->nSrc==1 );
83755   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83756     goto exit_drop_index;
83757   }
83758   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83759   if( pIndex==0 ){
83760     if( !ifExists ){
83761       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
83762     }else{
83763       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83764     }
83765     pParse->checkSchema = 1;
83766     goto exit_drop_index;
83767   }
83768   if( pIndex->autoIndex ){
83769     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
83770       "or PRIMARY KEY constraint cannot be dropped", 0);
83771     goto exit_drop_index;
83772   }
83773   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83774 #ifndef SQLITE_OMIT_AUTHORIZATION
83775   {
83776     int code = SQLITE_DROP_INDEX;
83777     Table *pTab = pIndex->pTable;
83778     const char *zDb = db->aDb[iDb].zName;
83779     const char *zTab = SCHEMA_TABLE(iDb);
83780     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
83781       goto exit_drop_index;
83782     }
83783     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
83784     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83785       goto exit_drop_index;
83786     }
83787   }
83788 #endif
83789
83790   /* Generate code to remove the index and from the master table */
83791   v = sqlite3GetVdbe(pParse);
83792   if( v ){
83793     sqlite3BeginWriteOperation(pParse, 1, iDb);
83794     sqlite3NestedParse(pParse,
83795        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83796        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83797     );
83798     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83799     sqlite3ChangeCookie(pParse, iDb);
83800     destroyRootPage(pParse, pIndex->tnum, iDb);
83801     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83802   }
83803
83804 exit_drop_index:
83805   sqlite3SrcListDelete(db, pName);
83806 }
83807
83808 /*
83809 ** pArray is a pointer to an array of objects. Each object in the
83810 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
83811 ** to extend the array so that there is space for a new object at the end.
83812 **
83813 ** When this function is called, *pnEntry contains the current size of
83814 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
83815 ** in total).
83816 **
83817 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
83818 ** space allocated for the new object is zeroed, *pnEntry updated to
83819 ** reflect the new size of the array and a pointer to the new allocation
83820 ** returned. *pIdx is set to the index of the new array entry in this case.
83821 **
83822 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
83823 ** unchanged and a copy of pArray returned.
83824 */
83825 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
83826   sqlite3 *db,      /* Connection to notify of malloc failures */
83827   void *pArray,     /* Array of objects.  Might be reallocated */
83828   int szEntry,      /* Size of each object in the array */
83829   int *pnEntry,     /* Number of objects currently in use */
83830   int *pIdx         /* Write the index of a new slot here */
83831 ){
83832   char *z;
83833   int n = *pnEntry;
83834   if( (n & (n-1))==0 ){
83835     int sz = (n==0) ? 1 : 2*n;
83836     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
83837     if( pNew==0 ){
83838       *pIdx = -1;
83839       return pArray;
83840     }
83841     pArray = pNew;
83842   }
83843   z = (char*)pArray;
83844   memset(&z[n * szEntry], 0, szEntry);
83845   *pIdx = n;
83846   ++*pnEntry;
83847   return pArray;
83848 }
83849
83850 /*
83851 ** Append a new element to the given IdList.  Create a new IdList if
83852 ** need be.
83853 **
83854 ** A new IdList is returned, or NULL if malloc() fails.
83855 */
83856 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
83857   int i;
83858   if( pList==0 ){
83859     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
83860     if( pList==0 ) return 0;
83861   }
83862   pList->a = sqlite3ArrayAllocate(
83863       db,
83864       pList->a,
83865       sizeof(pList->a[0]),
83866       &pList->nId,
83867       &i
83868   );
83869   if( i<0 ){
83870     sqlite3IdListDelete(db, pList);
83871     return 0;
83872   }
83873   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
83874   return pList;
83875 }
83876
83877 /*
83878 ** Delete an IdList.
83879 */
83880 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
83881   int i;
83882   if( pList==0 ) return;
83883   for(i=0; i<pList->nId; i++){
83884     sqlite3DbFree(db, pList->a[i].zName);
83885   }
83886   sqlite3DbFree(db, pList->a);
83887   sqlite3DbFree(db, pList);
83888 }
83889
83890 /*
83891 ** Return the index in pList of the identifier named zId.  Return -1
83892 ** if not found.
83893 */
83894 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
83895   int i;
83896   if( pList==0 ) return -1;
83897   for(i=0; i<pList->nId; i++){
83898     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
83899   }
83900   return -1;
83901 }
83902
83903 /*
83904 ** Expand the space allocated for the given SrcList object by
83905 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
83906 ** New slots are zeroed.
83907 **
83908 ** For example, suppose a SrcList initially contains two entries: A,B.
83909 ** To append 3 new entries onto the end, do this:
83910 **
83911 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
83912 **
83913 ** After the call above it would contain:  A, B, nil, nil, nil.
83914 ** If the iStart argument had been 1 instead of 2, then the result
83915 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
83916 ** the iStart value would be 0.  The result then would
83917 ** be: nil, nil, nil, A, B.
83918 **
83919 ** If a memory allocation fails the SrcList is unchanged.  The
83920 ** db->mallocFailed flag will be set to true.
83921 */
83922 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
83923   sqlite3 *db,       /* Database connection to notify of OOM errors */
83924   SrcList *pSrc,     /* The SrcList to be enlarged */
83925   int nExtra,        /* Number of new slots to add to pSrc->a[] */
83926   int iStart         /* Index in pSrc->a[] of first new slot */
83927 ){
83928   int i;
83929
83930   /* Sanity checking on calling parameters */
83931   assert( iStart>=0 );
83932   assert( nExtra>=1 );
83933   assert( pSrc!=0 );
83934   assert( iStart<=pSrc->nSrc );
83935
83936   /* Allocate additional space if needed */
83937   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
83938     SrcList *pNew;
83939     int nAlloc = pSrc->nSrc+nExtra;
83940     int nGot;
83941     pNew = sqlite3DbRealloc(db, pSrc,
83942                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
83943     if( pNew==0 ){
83944       assert( db->mallocFailed );
83945       return pSrc;
83946     }
83947     pSrc = pNew;
83948     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
83949     pSrc->nAlloc = (u16)nGot;
83950   }
83951
83952   /* Move existing slots that come after the newly inserted slots
83953   ** out of the way */
83954   for(i=pSrc->nSrc-1; i>=iStart; i--){
83955     pSrc->a[i+nExtra] = pSrc->a[i];
83956   }
83957   pSrc->nSrc += (i16)nExtra;
83958
83959   /* Zero the newly allocated slots */
83960   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
83961   for(i=iStart; i<iStart+nExtra; i++){
83962     pSrc->a[i].iCursor = -1;
83963   }
83964
83965   /* Return a pointer to the enlarged SrcList */
83966   return pSrc;
83967 }
83968
83969
83970 /*
83971 ** Append a new table name to the given SrcList.  Create a new SrcList if
83972 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
83973 **
83974 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
83975 ** SrcList might be the same as the SrcList that was input or it might be
83976 ** a new one.  If an OOM error does occurs, then the prior value of pList
83977 ** that is input to this routine is automatically freed.
83978 **
83979 ** If pDatabase is not null, it means that the table has an optional
83980 ** database name prefix.  Like this:  "database.table".  The pDatabase
83981 ** points to the table name and the pTable points to the database name.
83982 ** The SrcList.a[].zName field is filled with the table name which might
83983 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
83984 ** SrcList.a[].zDatabase is filled with the database name from pTable,
83985 ** or with NULL if no database is specified.
83986 **
83987 ** In other words, if call like this:
83988 **
83989 **         sqlite3SrcListAppend(D,A,B,0);
83990 **
83991 ** Then B is a table name and the database name is unspecified.  If called
83992 ** like this:
83993 **
83994 **         sqlite3SrcListAppend(D,A,B,C);
83995 **
83996 ** Then C is the table name and B is the database name.  If C is defined
83997 ** then so is B.  In other words, we never have a case where:
83998 **
83999 **         sqlite3SrcListAppend(D,A,0,C);
84000 **
84001 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84002 ** before being added to the SrcList.
84003 */
84004 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
84005   sqlite3 *db,        /* Connection to notify of malloc failures */
84006   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84007   Token *pTable,      /* Table to append */
84008   Token *pDatabase    /* Database of the table */
84009 ){
84010   struct SrcList_item *pItem;
84011   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84012   if( pList==0 ){
84013     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
84014     if( pList==0 ) return 0;
84015     pList->nAlloc = 1;
84016   }
84017   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
84018   if( db->mallocFailed ){
84019     sqlite3SrcListDelete(db, pList);
84020     return 0;
84021   }
84022   pItem = &pList->a[pList->nSrc-1];
84023   if( pDatabase && pDatabase->z==0 ){
84024     pDatabase = 0;
84025   }
84026   if( pDatabase ){
84027     Token *pTemp = pDatabase;
84028     pDatabase = pTable;
84029     pTable = pTemp;
84030   }
84031   pItem->zName = sqlite3NameFromToken(db, pTable);
84032   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
84033   return pList;
84034 }
84035
84036 /*
84037 ** Assign VdbeCursor index numbers to all tables in a SrcList
84038 */
84039 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84040   int i;
84041   struct SrcList_item *pItem;
84042   assert(pList || pParse->db->mallocFailed );
84043   if( pList ){
84044     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84045       if( pItem->iCursor>=0 ) break;
84046       pItem->iCursor = pParse->nTab++;
84047       if( pItem->pSelect ){
84048         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84049       }
84050     }
84051   }
84052 }
84053
84054 /*
84055 ** Delete an entire SrcList including all its substructure.
84056 */
84057 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
84058   int i;
84059   struct SrcList_item *pItem;
84060   if( pList==0 ) return;
84061   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84062     sqlite3DbFree(db, pItem->zDatabase);
84063     sqlite3DbFree(db, pItem->zName);
84064     sqlite3DbFree(db, pItem->zAlias);
84065     sqlite3DbFree(db, pItem->zIndex);
84066     sqlite3DeleteTable(db, pItem->pTab);
84067     sqlite3SelectDelete(db, pItem->pSelect);
84068     sqlite3ExprDelete(db, pItem->pOn);
84069     sqlite3IdListDelete(db, pItem->pUsing);
84070   }
84071   sqlite3DbFree(db, pList);
84072 }
84073
84074 /*
84075 ** This routine is called by the parser to add a new term to the
84076 ** end of a growing FROM clause.  The "p" parameter is the part of
84077 ** the FROM clause that has already been constructed.  "p" is NULL
84078 ** if this is the first term of the FROM clause.  pTable and pDatabase
84079 ** are the name of the table and database named in the FROM clause term.
84080 ** pDatabase is NULL if the database name qualifier is missing - the
84081 ** usual case.  If the term has a alias, then pAlias points to the
84082 ** alias token.  If the term is a subquery, then pSubquery is the
84083 ** SELECT statement that the subquery encodes.  The pTable and
84084 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84085 ** parameters are the content of the ON and USING clauses.
84086 **
84087 ** Return a new SrcList which encodes is the FROM with the new
84088 ** term added.
84089 */
84090 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
84091   Parse *pParse,          /* Parsing context */
84092   SrcList *p,             /* The left part of the FROM clause already seen */
84093   Token *pTable,          /* Name of the table to add to the FROM clause */
84094   Token *pDatabase,       /* Name of the database containing pTable */
84095   Token *pAlias,          /* The right-hand side of the AS subexpression */
84096   Select *pSubquery,      /* A subquery used in place of a table name */
84097   Expr *pOn,              /* The ON clause of a join */
84098   IdList *pUsing          /* The USING clause of a join */
84099 ){
84100   struct SrcList_item *pItem;
84101   sqlite3 *db = pParse->db;
84102   if( !p && (pOn || pUsing) ){
84103     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
84104       (pOn ? "ON" : "USING")
84105     );
84106     goto append_from_error;
84107   }
84108   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
84109   if( p==0 || NEVER(p->nSrc==0) ){
84110     goto append_from_error;
84111   }
84112   pItem = &p->a[p->nSrc-1];
84113   assert( pAlias!=0 );
84114   if( pAlias->n ){
84115     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
84116   }
84117   pItem->pSelect = pSubquery;
84118   pItem->pOn = pOn;
84119   pItem->pUsing = pUsing;
84120   return p;
84121
84122  append_from_error:
84123   assert( p==0 );
84124   sqlite3ExprDelete(db, pOn);
84125   sqlite3IdListDelete(db, pUsing);
84126   sqlite3SelectDelete(db, pSubquery);
84127   return 0;
84128 }
84129
84130 /*
84131 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
84132 ** element of the source-list passed as the second argument.
84133 */
84134 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84135   assert( pIndexedBy!=0 );
84136   if( p && ALWAYS(p->nSrc>0) ){
84137     struct SrcList_item *pItem = &p->a[p->nSrc-1];
84138     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84139     if( pIndexedBy->n==1 && !pIndexedBy->z ){
84140       /* A "NOT INDEXED" clause was supplied. See parse.y 
84141       ** construct "indexed_opt" for details. */
84142       pItem->notIndexed = 1;
84143     }else{
84144       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
84145     }
84146   }
84147 }
84148
84149 /*
84150 ** When building up a FROM clause in the parser, the join operator
84151 ** is initially attached to the left operand.  But the code generator
84152 ** expects the join operator to be on the right operand.  This routine
84153 ** Shifts all join operators from left to right for an entire FROM
84154 ** clause.
84155 **
84156 ** Example: Suppose the join is like this:
84157 **
84158 **           A natural cross join B
84159 **
84160 ** The operator is "natural cross join".  The A and B operands are stored
84161 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84162 ** operator with A.  This routine shifts that operator over to B.
84163 */
84164 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
84165   if( p ){
84166     int i;
84167     assert( p->a || p->nSrc==0 );
84168     for(i=p->nSrc-1; i>0; i--){
84169       p->a[i].jointype = p->a[i-1].jointype;
84170     }
84171     p->a[0].jointype = 0;
84172   }
84173 }
84174
84175 /*
84176 ** Begin a transaction
84177 */
84178 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
84179   sqlite3 *db;
84180   Vdbe *v;
84181   int i;
84182
84183   assert( pParse!=0 );
84184   db = pParse->db;
84185   assert( db!=0 );
84186 /*  if( db->aDb[0].pBt==0 ) return; */
84187   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
84188     return;
84189   }
84190   v = sqlite3GetVdbe(pParse);
84191   if( !v ) return;
84192   if( type!=TK_DEFERRED ){
84193     for(i=0; i<db->nDb; i++){
84194       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84195       sqlite3VdbeUsesBtree(v, i);
84196     }
84197   }
84198   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84199 }
84200
84201 /*
84202 ** Commit a transaction
84203 */
84204 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
84205   Vdbe *v;
84206
84207   assert( pParse!=0 );
84208   assert( pParse->db!=0 );
84209   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
84210     return;
84211   }
84212   v = sqlite3GetVdbe(pParse);
84213   if( v ){
84214     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84215   }
84216 }
84217
84218 /*
84219 ** Rollback a transaction
84220 */
84221 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
84222   Vdbe *v;
84223
84224   assert( pParse!=0 );
84225   assert( pParse->db!=0 );
84226   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
84227     return;
84228   }
84229   v = sqlite3GetVdbe(pParse);
84230   if( v ){
84231     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84232   }
84233 }
84234
84235 /*
84236 ** This function is called by the parser when it parses a command to create,
84237 ** release or rollback an SQL savepoint. 
84238 */
84239 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
84240   char *zName = sqlite3NameFromToken(pParse->db, pName);
84241   if( zName ){
84242     Vdbe *v = sqlite3GetVdbe(pParse);
84243 #ifndef SQLITE_OMIT_AUTHORIZATION
84244     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84245     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84246 #endif
84247     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
84248       sqlite3DbFree(pParse->db, zName);
84249       return;
84250     }
84251     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84252   }
84253 }
84254
84255 /*
84256 ** Make sure the TEMP database is open and available for use.  Return
84257 ** the number of errors.  Leave any error messages in the pParse structure.
84258 */
84259 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
84260   sqlite3 *db = pParse->db;
84261   if( db->aDb[1].pBt==0 && !pParse->explain ){
84262     int rc;
84263     Btree *pBt;
84264     static const int flags = 
84265           SQLITE_OPEN_READWRITE |
84266           SQLITE_OPEN_CREATE |
84267           SQLITE_OPEN_EXCLUSIVE |
84268           SQLITE_OPEN_DELETEONCLOSE |
84269           SQLITE_OPEN_TEMP_DB;
84270
84271     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84272     if( rc!=SQLITE_OK ){
84273       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
84274         "file for storing temporary tables");
84275       pParse->rc = rc;
84276       return 1;
84277     }
84278     db->aDb[1].pBt = pBt;
84279     assert( db->aDb[1].pSchema );
84280     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84281       db->mallocFailed = 1;
84282       return 1;
84283     }
84284   }
84285   return 0;
84286 }
84287
84288 /*
84289 ** Generate VDBE code that will verify the schema cookie and start
84290 ** a read-transaction for all named database files.
84291 **
84292 ** It is important that all schema cookies be verified and all
84293 ** read transactions be started before anything else happens in
84294 ** the VDBE program.  But this routine can be called after much other
84295 ** code has been generated.  So here is what we do:
84296 **
84297 ** The first time this routine is called, we code an OP_Goto that
84298 ** will jump to a subroutine at the end of the program.  Then we
84299 ** record every database that needs its schema verified in the
84300 ** pParse->cookieMask field.  Later, after all other code has been
84301 ** generated, the subroutine that does the cookie verifications and
84302 ** starts the transactions will be coded and the OP_Goto P2 value
84303 ** will be made to point to that subroutine.  The generation of the
84304 ** cookie verification subroutine code happens in sqlite3FinishCoding().
84305 **
84306 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84307 ** schema on any databases.  This can be used to position the OP_Goto
84308 ** early in the code, before we know if any database tables will be used.
84309 */
84310 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
84311   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84312
84313 #ifndef SQLITE_OMIT_TRIGGER
84314   if( pToplevel!=pParse ){
84315     /* This branch is taken if a trigger is currently being coded. In this
84316     ** case, set cookieGoto to a non-zero value to show that this function
84317     ** has been called. This is used by the sqlite3ExprCodeConstants()
84318     ** function. */
84319     pParse->cookieGoto = -1;
84320   }
84321 #endif
84322   if( pToplevel->cookieGoto==0 ){
84323     Vdbe *v = sqlite3GetVdbe(pToplevel);
84324     if( v==0 ) return;  /* This only happens if there was a prior error */
84325     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84326   }
84327   if( iDb>=0 ){
84328     sqlite3 *db = pToplevel->db;
84329     yDbMask mask;
84330
84331     assert( iDb<db->nDb );
84332     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84333     assert( iDb<SQLITE_MAX_ATTACHED+2 );
84334     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84335     mask = ((yDbMask)1)<<iDb;
84336     if( (pToplevel->cookieMask & mask)==0 ){
84337       pToplevel->cookieMask |= mask;
84338       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84339       if( !OMIT_TEMPDB && iDb==1 ){
84340         sqlite3OpenTempDatabase(pToplevel);
84341       }
84342     }
84343   }
84344 }
84345
84346 /*
84347 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
84348 ** attached database. Otherwise, invoke it for the database named zDb only.
84349 */
84350 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84351   sqlite3 *db = pParse->db;
84352   int i;
84353   for(i=0; i<db->nDb; i++){
84354     Db *pDb = &db->aDb[i];
84355     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
84356       sqlite3CodeVerifySchema(pParse, i);
84357     }
84358   }
84359 }
84360
84361 /*
84362 ** Generate VDBE code that prepares for doing an operation that
84363 ** might change the database.
84364 **
84365 ** This routine starts a new transaction if we are not already within
84366 ** a transaction.  If we are already within a transaction, then a checkpoint
84367 ** is set if the setStatement parameter is true.  A checkpoint should
84368 ** be set for operations that might fail (due to a constraint) part of
84369 ** the way through and which will need to undo some writes without having to
84370 ** rollback the whole transaction.  For operations where all constraints
84371 ** can be checked before any changes are made to the database, it is never
84372 ** necessary to undo a write and the checkpoint should not be set.
84373 */
84374 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84375   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84376   sqlite3CodeVerifySchema(pParse, iDb);
84377   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84378   pToplevel->isMultiWrite |= setStatement;
84379 }
84380
84381 /*
84382 ** Indicate that the statement currently under construction might write
84383 ** more than one entry (example: deleting one row then inserting another,
84384 ** inserting multiple rows in a table, or inserting a row and index entries.)
84385 ** If an abort occurs after some of these writes have completed, then it will
84386 ** be necessary to undo the completed writes.
84387 */
84388 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
84389   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84390   pToplevel->isMultiWrite = 1;
84391 }
84392
84393 /* 
84394 ** The code generator calls this routine if is discovers that it is
84395 ** possible to abort a statement prior to completion.  In order to 
84396 ** perform this abort without corrupting the database, we need to make
84397 ** sure that the statement is protected by a statement transaction.
84398 **
84399 ** Technically, we only need to set the mayAbort flag if the
84400 ** isMultiWrite flag was previously set.  There is a time dependency
84401 ** such that the abort must occur after the multiwrite.  This makes
84402 ** some statements involving the REPLACE conflict resolution algorithm
84403 ** go a little faster.  But taking advantage of this time dependency
84404 ** makes it more difficult to prove that the code is correct (in 
84405 ** particular, it prevents us from writing an effective
84406 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
84407 ** to take the safe route and skip the optimization.
84408 */
84409 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
84410   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84411   pToplevel->mayAbort = 1;
84412 }
84413
84414 /*
84415 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
84416 ** error. The onError parameter determines which (if any) of the statement
84417 ** and/or current transaction is rolled back.
84418 */
84419 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
84420   Vdbe *v = sqlite3GetVdbe(pParse);
84421   if( onError==OE_Abort ){
84422     sqlite3MayAbort(pParse);
84423   }
84424   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
84425 }
84426
84427 /*
84428 ** Check to see if pIndex uses the collating sequence pColl.  Return
84429 ** true if it does and false if it does not.
84430 */
84431 #ifndef SQLITE_OMIT_REINDEX
84432 static int collationMatch(const char *zColl, Index *pIndex){
84433   int i;
84434   assert( zColl!=0 );
84435   for(i=0; i<pIndex->nColumn; i++){
84436     const char *z = pIndex->azColl[i];
84437     assert( z!=0 );
84438     if( 0==sqlite3StrICmp(z, zColl) ){
84439       return 1;
84440     }
84441   }
84442   return 0;
84443 }
84444 #endif
84445
84446 /*
84447 ** Recompute all indices of pTab that use the collating sequence pColl.
84448 ** If pColl==0 then recompute all indices of pTab.
84449 */
84450 #ifndef SQLITE_OMIT_REINDEX
84451 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84452   Index *pIndex;              /* An index associated with pTab */
84453
84454   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84455     if( zColl==0 || collationMatch(zColl, pIndex) ){
84456       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84457       sqlite3BeginWriteOperation(pParse, 0, iDb);
84458       sqlite3RefillIndex(pParse, pIndex, -1);
84459     }
84460   }
84461 }
84462 #endif
84463
84464 /*
84465 ** Recompute all indices of all tables in all databases where the
84466 ** indices use the collating sequence pColl.  If pColl==0 then recompute
84467 ** all indices everywhere.
84468 */
84469 #ifndef SQLITE_OMIT_REINDEX
84470 static void reindexDatabases(Parse *pParse, char const *zColl){
84471   Db *pDb;                    /* A single database */
84472   int iDb;                    /* The database index number */
84473   sqlite3 *db = pParse->db;   /* The database connection */
84474   HashElem *k;                /* For looping over tables in pDb */
84475   Table *pTab;                /* A table in the database */
84476
84477   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84478   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84479     assert( pDb!=0 );
84480     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
84481       pTab = (Table*)sqliteHashData(k);
84482       reindexTable(pParse, pTab, zColl);
84483     }
84484   }
84485 }
84486 #endif
84487
84488 /*
84489 ** Generate code for the REINDEX command.
84490 **
84491 **        REINDEX                            -- 1
84492 **        REINDEX  <collation>               -- 2
84493 **        REINDEX  ?<database>.?<tablename>  -- 3
84494 **        REINDEX  ?<database>.?<indexname>  -- 4
84495 **
84496 ** Form 1 causes all indices in all attached databases to be rebuilt.
84497 ** Form 2 rebuilds all indices in all databases that use the named
84498 ** collating function.  Forms 3 and 4 rebuild the named index or all
84499 ** indices associated with the named table.
84500 */
84501 #ifndef SQLITE_OMIT_REINDEX
84502 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84503   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84504   char *z;                    /* Name of a table or index */
84505   const char *zDb;            /* Name of the database */
84506   Table *pTab;                /* A table in the database */
84507   Index *pIndex;              /* An index associated with pTab */
84508   int iDb;                    /* The database index number */
84509   sqlite3 *db = pParse->db;   /* The database connection */
84510   Token *pObjName;            /* Name of the table or index to be reindexed */
84511
84512   /* Read the database schema. If an error occurs, leave an error message
84513   ** and code in pParse and return NULL. */
84514   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84515     return;
84516   }
84517
84518   if( pName1==0 ){
84519     reindexDatabases(pParse, 0);
84520     return;
84521   }else if( NEVER(pName2==0) || pName2->z==0 ){
84522     char *zColl;
84523     assert( pName1->z );
84524     zColl = sqlite3NameFromToken(pParse->db, pName1);
84525     if( !zColl ) return;
84526     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
84527     if( pColl ){
84528       reindexDatabases(pParse, zColl);
84529       sqlite3DbFree(db, zColl);
84530       return;
84531     }
84532     sqlite3DbFree(db, zColl);
84533   }
84534   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
84535   if( iDb<0 ) return;
84536   z = sqlite3NameFromToken(db, pObjName);
84537   if( z==0 ) return;
84538   zDb = db->aDb[iDb].zName;
84539   pTab = sqlite3FindTable(db, z, zDb);
84540   if( pTab ){
84541     reindexTable(pParse, pTab, 0);
84542     sqlite3DbFree(db, z);
84543     return;
84544   }
84545   pIndex = sqlite3FindIndex(db, z, zDb);
84546   sqlite3DbFree(db, z);
84547   if( pIndex ){
84548     sqlite3BeginWriteOperation(pParse, 0, iDb);
84549     sqlite3RefillIndex(pParse, pIndex, -1);
84550     return;
84551   }
84552   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84553 }
84554 #endif
84555
84556 /*
84557 ** Return a dynamicly allocated KeyInfo structure that can be used
84558 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84559 **
84560 ** If successful, a pointer to the new structure is returned. In this case
84561 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
84562 ** pointer. If an error occurs (out of memory or missing collation 
84563 ** sequence), NULL is returned and the state of pParse updated to reflect
84564 ** the error.
84565 */
84566 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
84567   int i;
84568   int nCol = pIdx->nColumn;
84569   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84570   sqlite3 *db = pParse->db;
84571   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
84572
84573   if( pKey ){
84574     pKey->db = pParse->db;
84575     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84576     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84577     for(i=0; i<nCol; i++){
84578       char *zColl = pIdx->azColl[i];
84579       assert( zColl );
84580       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
84581       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
84582     }
84583     pKey->nField = (u16)nCol;
84584   }
84585
84586   if( pParse->nErr ){
84587     sqlite3DbFree(db, pKey);
84588     pKey = 0;
84589   }
84590   return pKey;
84591 }
84592
84593 /************** End of build.c ***********************************************/
84594 /************** Begin file callback.c ****************************************/
84595 /*
84596 ** 2005 May 23 
84597 **
84598 ** The author disclaims copyright to this source code.  In place of
84599 ** a legal notice, here is a blessing:
84600 **
84601 **    May you do good and not evil.
84602 **    May you find forgiveness for yourself and forgive others.
84603 **    May you share freely, never taking more than you give.
84604 **
84605 *************************************************************************
84606 **
84607 ** This file contains functions used to access the internal hash tables
84608 ** of user defined functions and collation sequences.
84609 */
84610
84611
84612 /*
84613 ** Invoke the 'collation needed' callback to request a collation sequence
84614 ** in the encoding enc of name zName, length nName.
84615 */
84616 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
84617   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84618   if( db->xCollNeeded ){
84619     char *zExternal = sqlite3DbStrDup(db, zName);
84620     if( !zExternal ) return;
84621     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84622     sqlite3DbFree(db, zExternal);
84623   }
84624 #ifndef SQLITE_OMIT_UTF16
84625   if( db->xCollNeeded16 ){
84626     char const *zExternal;
84627     sqlite3_value *pTmp = sqlite3ValueNew(db);
84628     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
84629     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
84630     if( zExternal ){
84631       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84632     }
84633     sqlite3ValueFree(pTmp);
84634   }
84635 #endif
84636 }
84637
84638 /*
84639 ** This routine is called if the collation factory fails to deliver a
84640 ** collation function in the best encoding but there may be other versions
84641 ** of this collation function (for other text encodings) available. Use one
84642 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84643 ** possible.
84644 */
84645 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
84646   CollSeq *pColl2;
84647   char *z = pColl->zName;
84648   int i;
84649   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
84650   for(i=0; i<3; i++){
84651     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
84652     if( pColl2->xCmp!=0 ){
84653       memcpy(pColl, pColl2, sizeof(CollSeq));
84654       pColl->xDel = 0;         /* Do not copy the destructor */
84655       return SQLITE_OK;
84656     }
84657   }
84658   return SQLITE_ERROR;
84659 }
84660
84661 /*
84662 ** This function is responsible for invoking the collation factory callback
84663 ** or substituting a collation sequence of a different encoding when the
84664 ** requested collation sequence is not available in the desired encoding.
84665 ** 
84666 ** If it is not NULL, then pColl must point to the database native encoding 
84667 ** collation sequence with name zName, length nName.
84668 **
84669 ** The return value is either the collation sequence to be used in database
84670 ** db for collation type name zName, length nName, or NULL, if no collation
84671 ** sequence can be found.  If no collation is found, leave an error message.
84672 **
84673 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
84674 */
84675 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
84676   Parse *pParse,        /* Parsing context */
84677   u8 enc,               /* The desired encoding for the collating sequence */
84678   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84679   const char *zName     /* Collating sequence name */
84680 ){
84681   CollSeq *p;
84682   sqlite3 *db = pParse->db;
84683
84684   p = pColl;
84685   if( !p ){
84686     p = sqlite3FindCollSeq(db, enc, zName, 0);
84687   }
84688   if( !p || !p->xCmp ){
84689     /* No collation sequence of this type for this encoding is registered.
84690     ** Call the collation factory to see if it can supply us with one.
84691     */
84692     callCollNeeded(db, enc, zName);
84693     p = sqlite3FindCollSeq(db, enc, zName, 0);
84694   }
84695   if( p && !p->xCmp && synthCollSeq(db, p) ){
84696     p = 0;
84697   }
84698   assert( !p || p->xCmp );
84699   if( p==0 ){
84700     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84701   }
84702   return p;
84703 }
84704
84705 /*
84706 ** This routine is called on a collation sequence before it is used to
84707 ** check that it is defined. An undefined collation sequence exists when
84708 ** a database is loaded that contains references to collation sequences
84709 ** that have not been defined by sqlite3_create_collation() etc.
84710 **
84711 ** If required, this routine calls the 'collation needed' callback to
84712 ** request a definition of the collating sequence. If this doesn't work, 
84713 ** an equivalent collating sequence that uses a text encoding different
84714 ** from the main database is substituted, if one is available.
84715 */
84716 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84717   if( pColl ){
84718     const char *zName = pColl->zName;
84719     sqlite3 *db = pParse->db;
84720     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
84721     if( !p ){
84722       return SQLITE_ERROR;
84723     }
84724     assert( p==pColl );
84725   }
84726   return SQLITE_OK;
84727 }
84728
84729
84730
84731 /*
84732 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84733 ** specified by zName and nName is not found and parameter 'create' is
84734 ** true, then create a new entry. Otherwise return NULL.
84735 **
84736 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
84737 ** array of three CollSeq structures. The first is the collation sequence
84738 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84739 **
84740 ** Stored immediately after the three collation sequences is a copy of
84741 ** the collation sequence name. A pointer to this string is stored in
84742 ** each collation sequence structure.
84743 */
84744 static CollSeq *findCollSeqEntry(
84745   sqlite3 *db,          /* Database connection */
84746   const char *zName,    /* Name of the collating sequence */
84747   int create            /* Create a new entry if true */
84748 ){
84749   CollSeq *pColl;
84750   int nName = sqlite3Strlen30(zName);
84751   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
84752
84753   if( 0==pColl && create ){
84754     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84755     if( pColl ){
84756       CollSeq *pDel = 0;
84757       pColl[0].zName = (char*)&pColl[3];
84758       pColl[0].enc = SQLITE_UTF8;
84759       pColl[1].zName = (char*)&pColl[3];
84760       pColl[1].enc = SQLITE_UTF16LE;
84761       pColl[2].zName = (char*)&pColl[3];
84762       pColl[2].enc = SQLITE_UTF16BE;
84763       memcpy(pColl[0].zName, zName, nName);
84764       pColl[0].zName[nName] = 0;
84765       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84766
84767       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
84768       ** return the pColl pointer to be deleted (because it wasn't added
84769       ** to the hash table).
84770       */
84771       assert( pDel==0 || pDel==pColl );
84772       if( pDel!=0 ){
84773         db->mallocFailed = 1;
84774         sqlite3DbFree(db, pDel);
84775         pColl = 0;
84776       }
84777     }
84778   }
84779   return pColl;
84780 }
84781
84782 /*
84783 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84784 ** Return the CollSeq* pointer for the collation sequence named zName
84785 ** for the encoding 'enc' from the database 'db'.
84786 **
84787 ** If the entry specified is not found and 'create' is true, then create a
84788 ** new entry.  Otherwise return NULL.
84789 **
84790 ** A separate function sqlite3LocateCollSeq() is a wrapper around
84791 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
84792 ** if necessary and generates an error message if the collating sequence
84793 ** cannot be found.
84794 **
84795 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
84796 */
84797 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
84798   sqlite3 *db,
84799   u8 enc,
84800   const char *zName,
84801   int create
84802 ){
84803   CollSeq *pColl;
84804   if( zName ){
84805     pColl = findCollSeqEntry(db, zName, create);
84806   }else{
84807     pColl = db->pDfltColl;
84808   }
84809   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
84810   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
84811   if( pColl ) pColl += enc-1;
84812   return pColl;
84813 }
84814
84815 /* During the search for the best function definition, this procedure
84816 ** is called to test how well the function passed as the first argument
84817 ** matches the request for a function with nArg arguments in a system
84818 ** that uses encoding enc. The value returned indicates how well the
84819 ** request is matched. A higher value indicates a better match.
84820 **
84821 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
84822 ** is also -1.  In other words, we are searching for a function that
84823 ** takes a variable number of arguments.
84824 **
84825 ** If nArg is -2 that means that we are searching for any function 
84826 ** regardless of the number of arguments it uses, so return a positive
84827 ** match score for any
84828 **
84829 ** The returned value is always between 0 and 6, as follows:
84830 **
84831 ** 0: Not a match.
84832 ** 1: UTF8/16 conversion required and function takes any number of arguments.
84833 ** 2: UTF16 byte order change required and function takes any number of args.
84834 ** 3: encoding matches and function takes any number of arguments
84835 ** 4: UTF8/16 conversion required - argument count matches exactly
84836 ** 5: UTF16 byte order conversion required - argument count matches exactly
84837 ** 6: Perfect match:  encoding and argument count match exactly.
84838 **
84839 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
84840 ** a perfect match and any function with both xStep and xFunc NULL is
84841 ** a non-match.
84842 */
84843 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
84844 static int matchQuality(
84845   FuncDef *p,     /* The function we are evaluating for match quality */
84846   int nArg,       /* Desired number of arguments.  (-1)==any */
84847   u8 enc          /* Desired text encoding */
84848 ){
84849   int match;
84850
84851   /* nArg of -2 is a special case */
84852   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
84853
84854   /* Wrong number of arguments means "no match" */
84855   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
84856
84857   /* Give a better score to a function with a specific number of arguments
84858   ** than to function that accepts any number of arguments. */
84859   if( p->nArg==nArg ){
84860     match = 4;
84861   }else{
84862     match = 1;
84863   }
84864
84865   /* Bonus points if the text encoding matches */
84866   if( enc==p->iPrefEnc ){
84867     match += 2;  /* Exact encoding match */
84868   }else if( (enc & p->iPrefEnc & 2)!=0 ){
84869     match += 1;  /* Both are UTF16, but with different byte orders */
84870   }
84871
84872   return match;
84873 }
84874
84875 /*
84876 ** Search a FuncDefHash for a function with the given name.  Return
84877 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
84878 */
84879 static FuncDef *functionSearch(
84880   FuncDefHash *pHash,  /* Hash table to search */
84881   int h,               /* Hash of the name */
84882   const char *zFunc,   /* Name of function */
84883   int nFunc            /* Number of bytes in zFunc */
84884 ){
84885   FuncDef *p;
84886   for(p=pHash->a[h]; p; p=p->pHash){
84887     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
84888       return p;
84889     }
84890   }
84891   return 0;
84892 }
84893
84894 /*
84895 ** Insert a new FuncDef into a FuncDefHash hash table.
84896 */
84897 SQLITE_PRIVATE void sqlite3FuncDefInsert(
84898   FuncDefHash *pHash,  /* The hash table into which to insert */
84899   FuncDef *pDef        /* The function definition to insert */
84900 ){
84901   FuncDef *pOther;
84902   int nName = sqlite3Strlen30(pDef->zName);
84903   u8 c1 = (u8)pDef->zName[0];
84904   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
84905   pOther = functionSearch(pHash, h, pDef->zName, nName);
84906   if( pOther ){
84907     assert( pOther!=pDef && pOther->pNext!=pDef );
84908     pDef->pNext = pOther->pNext;
84909     pOther->pNext = pDef;
84910   }else{
84911     pDef->pNext = 0;
84912     pDef->pHash = pHash->a[h];
84913     pHash->a[h] = pDef;
84914   }
84915 }
84916   
84917   
84918
84919 /*
84920 ** Locate a user function given a name, a number of arguments and a flag
84921 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
84922 ** pointer to the FuncDef structure that defines that function, or return
84923 ** NULL if the function does not exist.
84924 **
84925 ** If the createFlag argument is true, then a new (blank) FuncDef
84926 ** structure is created and liked into the "db" structure if a
84927 ** no matching function previously existed.
84928 **
84929 ** If nArg is -2, then the first valid function found is returned.  A
84930 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
84931 ** case is used to see if zName is a valid function name for some number
84932 ** of arguments.  If nArg is -2, then createFlag must be 0.
84933 **
84934 ** If createFlag is false, then a function with the required name and
84935 ** number of arguments may be returned even if the eTextRep flag does not
84936 ** match that requested.
84937 */
84938 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
84939   sqlite3 *db,       /* An open database */
84940   const char *zName, /* Name of the function.  Not null-terminated */
84941   int nName,         /* Number of characters in the name */
84942   int nArg,          /* Number of arguments.  -1 means any number */
84943   u8 enc,            /* Preferred text encoding */
84944   u8 createFlag      /* Create new entry if true and does not otherwise exist */
84945 ){
84946   FuncDef *p;         /* Iterator variable */
84947   FuncDef *pBest = 0; /* Best match found so far */
84948   int bestScore = 0;  /* Score of best match */
84949   int h;              /* Hash value */
84950
84951   assert( nArg>=(-2) );
84952   assert( nArg>=(-1) || createFlag==0 );
84953   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
84954   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
84955
84956   /* First search for a match amongst the application-defined functions.
84957   */
84958   p = functionSearch(&db->aFunc, h, zName, nName);
84959   while( p ){
84960     int score = matchQuality(p, nArg, enc);
84961     if( score>bestScore ){
84962       pBest = p;
84963       bestScore = score;
84964     }
84965     p = p->pNext;
84966   }
84967
84968   /* If no match is found, search the built-in functions.
84969   **
84970   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
84971   ** functions even if a prior app-defined function was found.  And give
84972   ** priority to built-in functions.
84973   **
84974   ** Except, if createFlag is true, that means that we are trying to
84975   ** install a new function.  Whatever FuncDef structure is returned it will
84976   ** have fields overwritten with new information appropriate for the
84977   ** new function.  But the FuncDefs for built-in functions are read-only.
84978   ** So we must not search for built-ins when creating a new function.
84979   */ 
84980   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
84981     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
84982     bestScore = 0;
84983     p = functionSearch(pHash, h, zName, nName);
84984     while( p ){
84985       int score = matchQuality(p, nArg, enc);
84986       if( score>bestScore ){
84987         pBest = p;
84988         bestScore = score;
84989       }
84990       p = p->pNext;
84991     }
84992   }
84993
84994   /* If the createFlag parameter is true and the search did not reveal an
84995   ** exact match for the name, number of arguments and encoding, then add a
84996   ** new entry to the hash table and return it.
84997   */
84998   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
84999       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85000     pBest->zName = (char *)&pBest[1];
85001     pBest->nArg = (u16)nArg;
85002     pBest->iPrefEnc = enc;
85003     memcpy(pBest->zName, zName, nName);
85004     pBest->zName[nName] = 0;
85005     sqlite3FuncDefInsert(&db->aFunc, pBest);
85006   }
85007
85008   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85009     return pBest;
85010   }
85011   return 0;
85012 }
85013
85014 /*
85015 ** Free all resources held by the schema structure. The void* argument points
85016 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
85017 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85018 ** of the schema hash tables).
85019 **
85020 ** The Schema.cache_size variable is not cleared.
85021 */
85022 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
85023   Hash temp1;
85024   Hash temp2;
85025   HashElem *pElem;
85026   Schema *pSchema = (Schema *)p;
85027
85028   temp1 = pSchema->tblHash;
85029   temp2 = pSchema->trigHash;
85030   sqlite3HashInit(&pSchema->trigHash);
85031   sqlite3HashClear(&pSchema->idxHash);
85032   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
85033     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
85034   }
85035   sqlite3HashClear(&temp2);
85036   sqlite3HashInit(&pSchema->tblHash);
85037   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
85038     Table *pTab = sqliteHashData(pElem);
85039     sqlite3DeleteTable(0, pTab);
85040   }
85041   sqlite3HashClear(&temp1);
85042   sqlite3HashClear(&pSchema->fkeyHash);
85043   pSchema->pSeqTab = 0;
85044   if( pSchema->flags & DB_SchemaLoaded ){
85045     pSchema->iGeneration++;
85046     pSchema->flags &= ~DB_SchemaLoaded;
85047   }
85048 }
85049
85050 /*
85051 ** Find and return the schema associated with a BTree.  Create
85052 ** a new one if necessary.
85053 */
85054 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
85055   Schema * p;
85056   if( pBt ){
85057     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
85058   }else{
85059     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
85060   }
85061   if( !p ){
85062     db->mallocFailed = 1;
85063   }else if ( 0==p->file_format ){
85064     sqlite3HashInit(&p->tblHash);
85065     sqlite3HashInit(&p->idxHash);
85066     sqlite3HashInit(&p->trigHash);
85067     sqlite3HashInit(&p->fkeyHash);
85068     p->enc = SQLITE_UTF8;
85069   }
85070   return p;
85071 }
85072
85073 /************** End of callback.c ********************************************/
85074 /************** Begin file delete.c ******************************************/
85075 /*
85076 ** 2001 September 15
85077 **
85078 ** The author disclaims copyright to this source code.  In place of
85079 ** a legal notice, here is a blessing:
85080 **
85081 **    May you do good and not evil.
85082 **    May you find forgiveness for yourself and forgive others.
85083 **    May you share freely, never taking more than you give.
85084 **
85085 *************************************************************************
85086 ** This file contains C code routines that are called by the parser
85087 ** in order to generate code for DELETE FROM statements.
85088 */
85089
85090 /*
85091 ** While a SrcList can in general represent multiple tables and subqueries
85092 ** (as in the FROM clause of a SELECT statement) in this case it contains
85093 ** the name of a single table, as one might find in an INSERT, DELETE,
85094 ** or UPDATE statement.  Look up that table in the symbol table and
85095 ** return a pointer.  Set an error message and return NULL if the table 
85096 ** name is not found or if any other error occurs.
85097 **
85098 ** The following fields are initialized appropriate in pSrc:
85099 **
85100 **    pSrc->a[0].pTab       Pointer to the Table object
85101 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85102 **
85103 */
85104 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
85105   struct SrcList_item *pItem = pSrc->a;
85106   Table *pTab;
85107   assert( pItem && pSrc->nSrc==1 );
85108   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
85109   sqlite3DeleteTable(pParse->db, pItem->pTab);
85110   pItem->pTab = pTab;
85111   if( pTab ){
85112     pTab->nRef++;
85113   }
85114   if( sqlite3IndexedByLookup(pParse, pItem) ){
85115     pTab = 0;
85116   }
85117   return pTab;
85118 }
85119
85120 /*
85121 ** Check to make sure the given table is writable.  If it is not
85122 ** writable, generate an error message and return 1.  If it is
85123 ** writable return 0;
85124 */
85125 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85126   /* A table is not writable under the following circumstances:
85127   **
85128   **   1) It is a virtual table and no implementation of the xUpdate method
85129   **      has been provided, or
85130   **   2) It is a system table (i.e. sqlite_master), this call is not
85131   **      part of a nested parse and writable_schema pragma has not 
85132   **      been specified.
85133   **
85134   ** In either case leave an error message in pParse and return non-zero.
85135   */
85136   if( ( IsVirtual(pTab) 
85137      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85138    || ( (pTab->tabFlags & TF_Readonly)!=0
85139      && (pParse->db->flags & SQLITE_WriteSchema)==0
85140      && pParse->nested==0 )
85141   ){
85142     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85143     return 1;
85144   }
85145
85146 #ifndef SQLITE_OMIT_VIEW
85147   if( !viewOk && pTab->pSelect ){
85148     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85149     return 1;
85150   }
85151 #endif
85152   return 0;
85153 }
85154
85155
85156 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85157 /*
85158 ** Evaluate a view and store its result in an ephemeral table.  The
85159 ** pWhere argument is an optional WHERE clause that restricts the
85160 ** set of rows in the view that are to be added to the ephemeral table.
85161 */
85162 SQLITE_PRIVATE void sqlite3MaterializeView(
85163   Parse *pParse,       /* Parsing context */
85164   Table *pView,        /* View definition */
85165   Expr *pWhere,        /* Optional WHERE clause to be added */
85166   int iCur             /* Cursor number for ephemerial table */
85167 ){
85168   SelectDest dest;
85169   Select *pDup;
85170   sqlite3 *db = pParse->db;
85171
85172   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
85173   if( pWhere ){
85174     SrcList *pFrom;
85175     
85176     pWhere = sqlite3ExprDup(db, pWhere, 0);
85177     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
85178     if( pFrom ){
85179       assert( pFrom->nSrc==1 );
85180       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
85181       pFrom->a[0].pSelect = pDup;
85182       assert( pFrom->a[0].pOn==0 );
85183       assert( pFrom->a[0].pUsing==0 );
85184     }else{
85185       sqlite3SelectDelete(db, pDup);
85186     }
85187     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85188     if( pDup ) pDup->selFlags |= SF_Materialize;
85189   }
85190   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
85191   sqlite3Select(pParse, pDup, &dest);
85192   sqlite3SelectDelete(db, pDup);
85193 }
85194 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
85195
85196 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
85197 /*
85198 ** Generate an expression tree to implement the WHERE, ORDER BY,
85199 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85200 **
85201 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85202 **                            \__________________________/
85203 **                               pLimitWhere (pInClause)
85204 */
85205 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
85206   Parse *pParse,               /* The parser context */
85207   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85208   Expr *pWhere,                /* The WHERE clause.  May be null */
85209   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85210   Expr *pLimit,                /* The LIMIT clause.  May be null */
85211   Expr *pOffset,               /* The OFFSET clause.  May be null */
85212   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85213 ){
85214   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85215   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85216   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85217   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85218   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85219   Select *pSelect = NULL;      /* Complete SELECT tree */
85220
85221   /* Check that there isn't an ORDER BY without a LIMIT clause.
85222   */
85223   if( pOrderBy && (pLimit == 0) ) {
85224     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85225     goto limit_where_cleanup_2;
85226   }
85227
85228   /* We only need to generate a select expression if there
85229   ** is a limit/offset term to enforce.
85230   */
85231   if( pLimit == 0 ) {
85232     /* if pLimit is null, pOffset will always be null as well. */
85233     assert( pOffset == 0 );
85234     return pWhere;
85235   }
85236
85237   /* Generate a select expression tree to enforce the limit/offset 
85238   ** term for the DELETE or UPDATE statement.  For example:
85239   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85240   ** becomes:
85241   **   DELETE FROM table_a WHERE rowid IN ( 
85242   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85243   **   );
85244   */
85245
85246   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85247   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85248   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
85249   if( pEList == 0 ) goto limit_where_cleanup_2;
85250
85251   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85252   ** and the SELECT subtree. */
85253   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
85254   if( pSelectSrc == 0 ) {
85255     sqlite3ExprListDelete(pParse->db, pEList);
85256     goto limit_where_cleanup_2;
85257   }
85258
85259   /* generate the SELECT expression tree. */
85260   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85261                              pOrderBy,0,pLimit,pOffset);
85262   if( pSelect == 0 ) return 0;
85263
85264   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85265   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85266   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85267   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85268   if( pInClause == 0 ) goto limit_where_cleanup_1;
85269
85270   pInClause->x.pSelect = pSelect;
85271   pInClause->flags |= EP_xIsSelect;
85272   sqlite3ExprSetHeight(pParse, pInClause);
85273   return pInClause;
85274
85275   /* something went wrong. clean up anything allocated. */
85276 limit_where_cleanup_1:
85277   sqlite3SelectDelete(pParse->db, pSelect);
85278   return 0;
85279
85280 limit_where_cleanup_2:
85281   sqlite3ExprDelete(pParse->db, pWhere);
85282   sqlite3ExprListDelete(pParse->db, pOrderBy);
85283   sqlite3ExprDelete(pParse->db, pLimit);
85284   sqlite3ExprDelete(pParse->db, pOffset);
85285   return 0;
85286 }
85287 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
85288
85289 /*
85290 ** Generate code for a DELETE FROM statement.
85291 **
85292 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85293 **                 \________/       \________________/
85294 **                  pTabList              pWhere
85295 */
85296 SQLITE_PRIVATE void sqlite3DeleteFrom(
85297   Parse *pParse,         /* The parser context */
85298   SrcList *pTabList,     /* The table from which we should delete things */
85299   Expr *pWhere           /* The WHERE clause.  May be null */
85300 ){
85301   Vdbe *v;               /* The virtual database engine */
85302   Table *pTab;           /* The table from which records will be deleted */
85303   const char *zDb;       /* Name of database holding pTab */
85304   int end, addr = 0;     /* A couple addresses of generated code */
85305   int i;                 /* Loop counter */
85306   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85307   Index *pIdx;           /* For looping over indices of the table */
85308   int iCur;              /* VDBE Cursor number for pTab */
85309   sqlite3 *db;           /* Main database structure */
85310   AuthContext sContext;  /* Authorization context */
85311   NameContext sNC;       /* Name context to resolve expressions in */
85312   int iDb;               /* Database number */
85313   int memCnt = -1;       /* Memory cell used for change counting */
85314   int rcauth;            /* Value returned by authorization callback */
85315
85316 #ifndef SQLITE_OMIT_TRIGGER
85317   int isView;                  /* True if attempting to delete from a view */
85318   Trigger *pTrigger;           /* List of table triggers, if required */
85319 #endif
85320
85321   memset(&sContext, 0, sizeof(sContext));
85322   db = pParse->db;
85323   if( pParse->nErr || db->mallocFailed ){
85324     goto delete_from_cleanup;
85325   }
85326   assert( pTabList->nSrc==1 );
85327
85328   /* Locate the table which we want to delete.  This table has to be
85329   ** put in an SrcList structure because some of the subroutines we
85330   ** will be calling are designed to work with multiple tables and expect
85331   ** an SrcList* parameter instead of just a Table* parameter.
85332   */
85333   pTab = sqlite3SrcListLookup(pParse, pTabList);
85334   if( pTab==0 )  goto delete_from_cleanup;
85335
85336   /* Figure out if we have any triggers and if the table being
85337   ** deleted from is a view
85338   */
85339 #ifndef SQLITE_OMIT_TRIGGER
85340   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85341   isView = pTab->pSelect!=0;
85342 #else
85343 # define pTrigger 0
85344 # define isView 0
85345 #endif
85346 #ifdef SQLITE_OMIT_VIEW
85347 # undef isView
85348 # define isView 0
85349 #endif
85350
85351   /* If pTab is really a view, make sure it has been initialized.
85352   */
85353   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85354     goto delete_from_cleanup;
85355   }
85356
85357   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85358     goto delete_from_cleanup;
85359   }
85360   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85361   assert( iDb<db->nDb );
85362   zDb = db->aDb[iDb].zName;
85363   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
85364   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
85365   if( rcauth==SQLITE_DENY ){
85366     goto delete_from_cleanup;
85367   }
85368   assert(!isView || pTrigger);
85369
85370   /* Assign  cursor number to the table and all its indices.
85371   */
85372   assert( pTabList->nSrc==1 );
85373   iCur = pTabList->a[0].iCursor = pParse->nTab++;
85374   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85375     pParse->nTab++;
85376   }
85377
85378   /* Start the view context
85379   */
85380   if( isView ){
85381     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85382   }
85383
85384   /* Begin generating code.
85385   */
85386   v = sqlite3GetVdbe(pParse);
85387   if( v==0 ){
85388     goto delete_from_cleanup;
85389   }
85390   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85391   sqlite3BeginWriteOperation(pParse, 1, iDb);
85392
85393   /* If we are trying to delete from a view, realize that view into
85394   ** a ephemeral table.
85395   */
85396 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85397   if( isView ){
85398     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85399   }
85400 #endif
85401
85402   /* Resolve the column names in the WHERE clause.
85403   */
85404   memset(&sNC, 0, sizeof(sNC));
85405   sNC.pParse = pParse;
85406   sNC.pSrcList = pTabList;
85407   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85408     goto delete_from_cleanup;
85409   }
85410
85411   /* Initialize the counter of the number of rows deleted, if
85412   ** we are counting rows.
85413   */
85414   if( db->flags & SQLITE_CountRows ){
85415     memCnt = ++pParse->nMem;
85416     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85417   }
85418
85419 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
85420   /* Special case: A DELETE without a WHERE clause deletes everything.
85421   ** It is easier just to erase the whole table. Prior to version 3.6.5,
85422   ** this optimization caused the row change count (the value returned by 
85423   ** API function sqlite3_count_changes) to be set incorrectly.  */
85424   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
85425    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
85426   ){
85427     assert( !isView );
85428     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85429                       pTab->zName, P4_STATIC);
85430     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85431       assert( pIdx->pSchema==pTab->pSchema );
85432       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85433     }
85434   }else
85435 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
85436   /* The usual case: There is a WHERE clause so we have to scan through
85437   ** the table and pick which records to delete.
85438   */
85439   {
85440     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85441     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85442     int regRowid;                   /* Actual register containing rowids */
85443
85444     /* Collect rowids of every row to be deleted.
85445     */
85446     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85447     pWInfo = sqlite3WhereBegin(
85448         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
85449     );
85450     if( pWInfo==0 ) goto delete_from_cleanup;
85451     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
85452     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85453     if( db->flags & SQLITE_CountRows ){
85454       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85455     }
85456     sqlite3WhereEnd(pWInfo);
85457
85458     /* Delete every item whose key was written to the list during the
85459     ** database scan.  We have to delete items after the scan is complete
85460     ** because deleting an item can change the scan order.  */
85461     end = sqlite3VdbeMakeLabel(v);
85462
85463     /* Unless this is a view, open cursors for the table we are 
85464     ** deleting from and all its indices. If this is a view, then the
85465     ** only effect this statement has is to fire the INSTEAD OF 
85466     ** triggers.  */
85467     if( !isView ){
85468       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85469     }
85470
85471     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85472
85473     /* Delete the row */
85474 #ifndef SQLITE_OMIT_VIRTUALTABLE
85475     if( IsVirtual(pTab) ){
85476       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85477       sqlite3VtabMakeWritable(pParse, pTab);
85478       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85479       sqlite3VdbeChangeP5(v, OE_Abort);
85480       sqlite3MayAbort(pParse);
85481     }else
85482 #endif
85483     {
85484       int count = (pParse->nested==0);    /* True to count changes */
85485       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85486     }
85487
85488     /* End of the delete loop */
85489     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85490     sqlite3VdbeResolveLabel(v, end);
85491
85492     /* Close the cursors open on the table and its indexes. */
85493     if( !isView && !IsVirtual(pTab) ){
85494       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85495         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85496       }
85497       sqlite3VdbeAddOp1(v, OP_Close, iCur);
85498     }
85499   }
85500
85501   /* Update the sqlite_sequence table by storing the content of the
85502   ** maximum rowid counter values recorded while inserting into
85503   ** autoincrement tables.
85504   */
85505   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85506     sqlite3AutoincrementEnd(pParse);
85507   }
85508
85509   /* Return the number of rows that were deleted. If this routine is 
85510   ** generating code because of a call to sqlite3NestedParse(), do not
85511   ** invoke the callback function.
85512   */
85513   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85514     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85515     sqlite3VdbeSetNumCols(v, 1);
85516     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
85517   }
85518
85519 delete_from_cleanup:
85520   sqlite3AuthContextPop(&sContext);
85521   sqlite3SrcListDelete(db, pTabList);
85522   sqlite3ExprDelete(db, pWhere);
85523   return;
85524 }
85525 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85526 ** thely may interfere with compilation of other functions in this file
85527 ** (or in another file, if this file becomes part of the amalgamation).  */
85528 #ifdef isView
85529  #undef isView
85530 #endif
85531 #ifdef pTrigger
85532  #undef pTrigger
85533 #endif
85534
85535 /*
85536 ** This routine generates VDBE code that causes a single row of a
85537 ** single table to be deleted.
85538 **
85539 ** The VDBE must be in a particular state when this routine is called.
85540 ** These are the requirements:
85541 **
85542 **   1.  A read/write cursor pointing to pTab, the table containing the row
85543 **       to be deleted, must be opened as cursor number $iCur.
85544 **
85545 **   2.  Read/write cursors for all indices of pTab must be open as
85546 **       cursor number base+i for the i-th index.
85547 **
85548 **   3.  The record number of the row to be deleted must be stored in
85549 **       memory cell iRowid.
85550 **
85551 ** This routine generates code to remove both the table record and all 
85552 ** index entries that point to that record.
85553 */
85554 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
85555   Parse *pParse,     /* Parsing context */
85556   Table *pTab,       /* Table containing the row to be deleted */
85557   int iCur,          /* Cursor number for the table */
85558   int iRowid,        /* Memory cell that contains the rowid to delete */
85559   int count,         /* If non-zero, increment the row change counter */
85560   Trigger *pTrigger, /* List of triggers to (potentially) fire */
85561   int onconf         /* Default ON CONFLICT policy for triggers */
85562 ){
85563   Vdbe *v = pParse->pVdbe;        /* Vdbe */
85564   int iOld = 0;                   /* First register in OLD.* array */
85565   int iLabel;                     /* Label resolved to end of generated code */
85566
85567   /* Vdbe is guaranteed to have been allocated by this stage. */
85568   assert( v );
85569
85570   /* Seek cursor iCur to the row to delete. If this row no longer exists 
85571   ** (this can happen if a trigger program has already deleted it), do
85572   ** not attempt to delete it or fire any DELETE triggers.  */
85573   iLabel = sqlite3VdbeMakeLabel(v);
85574   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85575  
85576   /* If there are any triggers to fire, allocate a range of registers to
85577   ** use for the old.* references in the triggers.  */
85578   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85579     u32 mask;                     /* Mask of OLD.* columns in use */
85580     int iCol;                     /* Iterator used while populating OLD.* */
85581
85582     /* TODO: Could use temporary registers here. Also could attempt to
85583     ** avoid copying the contents of the rowid register.  */
85584     mask = sqlite3TriggerColmask(
85585         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85586     );
85587     mask |= sqlite3FkOldmask(pParse, pTab);
85588     iOld = pParse->nMem+1;
85589     pParse->nMem += (1 + pTab->nCol);
85590
85591     /* Populate the OLD.* pseudo-table register array. These values will be 
85592     ** used by any BEFORE and AFTER triggers that exist.  */
85593     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85594     for(iCol=0; iCol<pTab->nCol; iCol++){
85595       if( mask==0xffffffff || mask&(1<<iCol) ){
85596         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85597       }
85598     }
85599
85600     /* Invoke BEFORE DELETE trigger programs. */
85601     sqlite3CodeRowTrigger(pParse, pTrigger, 
85602         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
85603     );
85604
85605     /* Seek the cursor to the row to be deleted again. It may be that
85606     ** the BEFORE triggers coded above have already removed the row
85607     ** being deleted. Do not attempt to delete the row a second time, and 
85608     ** do not fire AFTER triggers.  */
85609     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85610
85611     /* Do FK processing. This call checks that any FK constraints that
85612     ** refer to this table (i.e. constraints attached to other tables) 
85613     ** are not violated by deleting this row.  */
85614     sqlite3FkCheck(pParse, pTab, iOld, 0);
85615   }
85616
85617   /* Delete the index and table entries. Skip this step if pTab is really
85618   ** a view (in which case the only effect of the DELETE statement is to
85619   ** fire the INSTEAD OF triggers).  */ 
85620   if( pTab->pSelect==0 ){
85621     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85622     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85623     if( count ){
85624       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85625     }
85626   }
85627
85628   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85629   ** handle rows (possibly in other tables) that refer via a foreign key
85630   ** to the row just deleted. */ 
85631   sqlite3FkActions(pParse, pTab, 0, iOld);
85632
85633   /* Invoke AFTER DELETE trigger programs. */
85634   sqlite3CodeRowTrigger(pParse, pTrigger, 
85635       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85636   );
85637
85638   /* Jump here if the row had already been deleted before any BEFORE
85639   ** trigger programs were invoked. Or if a trigger program throws a 
85640   ** RAISE(IGNORE) exception.  */
85641   sqlite3VdbeResolveLabel(v, iLabel);
85642 }
85643
85644 /*
85645 ** This routine generates VDBE code that causes the deletion of all
85646 ** index entries associated with a single row of a single table.
85647 **
85648 ** The VDBE must be in a particular state when this routine is called.
85649 ** These are the requirements:
85650 **
85651 **   1.  A read/write cursor pointing to pTab, the table containing the row
85652 **       to be deleted, must be opened as cursor number "iCur".
85653 **
85654 **   2.  Read/write cursors for all indices of pTab must be open as
85655 **       cursor number iCur+i for the i-th index.
85656 **
85657 **   3.  The "iCur" cursor must be pointing to the row that is to be
85658 **       deleted.
85659 */
85660 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
85661   Parse *pParse,     /* Parsing and code generating context */
85662   Table *pTab,       /* Table containing the row to be deleted */
85663   int iCur,          /* Cursor number for the table */
85664   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85665 ){
85666   int i;
85667   Index *pIdx;
85668   int r1;
85669
85670   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85671     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85672     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85673     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85674   }
85675 }
85676
85677 /*
85678 ** Generate code that will assemble an index key and put it in register
85679 ** regOut.  The key with be for index pIdx which is an index on pTab.
85680 ** iCur is the index of a cursor open on the pTab table and pointing to
85681 ** the entry that needs indexing.
85682 **
85683 ** Return a register number which is the first in a block of
85684 ** registers that holds the elements of the index key.  The
85685 ** block of registers has already been deallocated by the time
85686 ** this routine returns.
85687 */
85688 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
85689   Parse *pParse,     /* Parsing context */
85690   Index *pIdx,       /* The index for which to generate a key */
85691   int iCur,          /* Cursor number for the pIdx->pTable table */
85692   int regOut,        /* Write the new index key to this register */
85693   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85694 ){
85695   Vdbe *v = pParse->pVdbe;
85696   int j;
85697   Table *pTab = pIdx->pTable;
85698   int regBase;
85699   int nCol;
85700
85701   nCol = pIdx->nColumn;
85702   regBase = sqlite3GetTempRange(pParse, nCol+1);
85703   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85704   for(j=0; j<nCol; j++){
85705     int idx = pIdx->aiColumn[j];
85706     if( idx==pTab->iPKey ){
85707       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85708     }else{
85709       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85710       sqlite3ColumnDefault(v, pTab, idx, -1);
85711     }
85712   }
85713   if( doMakeRec ){
85714     const char *zAff;
85715     if( pTab->pSelect
85716      || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
85717     ){
85718       zAff = 0;
85719     }else{
85720       zAff = sqlite3IndexAffinityStr(v, pIdx);
85721     }
85722     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85723     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85724   }
85725   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
85726   return regBase;
85727 }
85728
85729 /************** End of delete.c **********************************************/
85730 /************** Begin file func.c ********************************************/
85731 /*
85732 ** 2002 February 23
85733 **
85734 ** The author disclaims copyright to this source code.  In place of
85735 ** a legal notice, here is a blessing:
85736 **
85737 **    May you do good and not evil.
85738 **    May you find forgiveness for yourself and forgive others.
85739 **    May you share freely, never taking more than you give.
85740 **
85741 *************************************************************************
85742 ** This file contains the C functions that implement various SQL
85743 ** functions of SQLite.  
85744 **
85745 ** There is only one exported symbol in this file - the function
85746 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
85747 ** All other code has file scope.
85748 */
85749 /* #include <stdlib.h> */
85750 /* #include <assert.h> */
85751
85752 /*
85753 ** Return the collating function associated with a function.
85754 */
85755 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
85756   return context->pColl;
85757 }
85758
85759 /*
85760 ** Indicate that the accumulator load should be skipped on this
85761 ** iteration of the aggregate loop.
85762 */
85763 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
85764   context->skipFlag = 1;
85765 }
85766
85767 /*
85768 ** Implementation of the non-aggregate min() and max() functions
85769 */
85770 static void minmaxFunc(
85771   sqlite3_context *context,
85772   int argc,
85773   sqlite3_value **argv
85774 ){
85775   int i;
85776   int mask;    /* 0 for min() or 0xffffffff for max() */
85777   int iBest;
85778   CollSeq *pColl;
85779
85780   assert( argc>1 );
85781   mask = sqlite3_user_data(context)==0 ? 0 : -1;
85782   pColl = sqlite3GetFuncCollSeq(context);
85783   assert( pColl );
85784   assert( mask==-1 || mask==0 );
85785   iBest = 0;
85786   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85787   for(i=1; i<argc; i++){
85788     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
85789     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85790       testcase( mask==0 );
85791       iBest = i;
85792     }
85793   }
85794   sqlite3_result_value(context, argv[iBest]);
85795 }
85796
85797 /*
85798 ** Return the type of the argument.
85799 */
85800 static void typeofFunc(
85801   sqlite3_context *context,
85802   int NotUsed,
85803   sqlite3_value **argv
85804 ){
85805   const char *z = 0;
85806   UNUSED_PARAMETER(NotUsed);
85807   switch( sqlite3_value_type(argv[0]) ){
85808     case SQLITE_INTEGER: z = "integer"; break;
85809     case SQLITE_TEXT:    z = "text";    break;
85810     case SQLITE_FLOAT:   z = "real";    break;
85811     case SQLITE_BLOB:    z = "blob";    break;
85812     default:             z = "null";    break;
85813   }
85814   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
85815 }
85816
85817
85818 /*
85819 ** Implementation of the length() function
85820 */
85821 static void lengthFunc(
85822   sqlite3_context *context,
85823   int argc,
85824   sqlite3_value **argv
85825 ){
85826   int len;
85827
85828   assert( argc==1 );
85829   UNUSED_PARAMETER(argc);
85830   switch( sqlite3_value_type(argv[0]) ){
85831     case SQLITE_BLOB:
85832     case SQLITE_INTEGER:
85833     case SQLITE_FLOAT: {
85834       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
85835       break;
85836     }
85837     case SQLITE_TEXT: {
85838       const unsigned char *z = sqlite3_value_text(argv[0]);
85839       if( z==0 ) return;
85840       len = 0;
85841       while( *z ){
85842         len++;
85843         SQLITE_SKIP_UTF8(z);
85844       }
85845       sqlite3_result_int(context, len);
85846       break;
85847     }
85848     default: {
85849       sqlite3_result_null(context);
85850       break;
85851     }
85852   }
85853 }
85854
85855 /*
85856 ** Implementation of the abs() function.
85857 **
85858 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
85859 ** the numeric argument X. 
85860 */
85861 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85862   assert( argc==1 );
85863   UNUSED_PARAMETER(argc);
85864   switch( sqlite3_value_type(argv[0]) ){
85865     case SQLITE_INTEGER: {
85866       i64 iVal = sqlite3_value_int64(argv[0]);
85867       if( iVal<0 ){
85868         if( (iVal<<1)==0 ){
85869           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
85870           ** abs(X) throws an integer overflow error since there is no
85871           ** equivalent positive 64-bit two complement value. */
85872           sqlite3_result_error(context, "integer overflow", -1);
85873           return;
85874         }
85875         iVal = -iVal;
85876       } 
85877       sqlite3_result_int64(context, iVal);
85878       break;
85879     }
85880     case SQLITE_NULL: {
85881       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
85882       sqlite3_result_null(context);
85883       break;
85884     }
85885     default: {
85886       /* Because sqlite3_value_double() returns 0.0 if the argument is not
85887       ** something that can be converted into a number, we have:
85888       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
85889       ** cannot be converted to a numeric value. 
85890       */
85891       double rVal = sqlite3_value_double(argv[0]);
85892       if( rVal<0 ) rVal = -rVal;
85893       sqlite3_result_double(context, rVal);
85894       break;
85895     }
85896   }
85897 }
85898
85899 /*
85900 ** Implementation of the instr() function.
85901 **
85902 ** instr(haystack,needle) finds the first occurrence of needle
85903 ** in haystack and returns the number of previous characters plus 1,
85904 ** or 0 if needle does not occur within haystack.
85905 **
85906 ** If both haystack and needle are BLOBs, then the result is one more than
85907 ** the number of bytes in haystack prior to the first occurrence of needle,
85908 ** or 0 if needle never occurs in haystack.
85909 */
85910 static void instrFunc(
85911   sqlite3_context *context,
85912   int argc,
85913   sqlite3_value **argv
85914 ){
85915   const unsigned char *zHaystack;
85916   const unsigned char *zNeedle;
85917   int nHaystack;
85918   int nNeedle;
85919   int typeHaystack, typeNeedle;
85920   int N = 1;
85921   int isText;
85922
85923   UNUSED_PARAMETER(argc);
85924   typeHaystack = sqlite3_value_type(argv[0]);
85925   typeNeedle = sqlite3_value_type(argv[1]);
85926   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
85927   nHaystack = sqlite3_value_bytes(argv[0]);
85928   nNeedle = sqlite3_value_bytes(argv[1]);
85929   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
85930     zHaystack = sqlite3_value_blob(argv[0]);
85931     zNeedle = sqlite3_value_blob(argv[1]);
85932     isText = 0;
85933   }else{
85934     zHaystack = sqlite3_value_text(argv[0]);
85935     zNeedle = sqlite3_value_text(argv[1]);
85936     isText = 1;
85937   }
85938   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
85939     N++;
85940     do{
85941       nHaystack--;
85942       zHaystack++;
85943     }while( isText && (zHaystack[0]&0xc0)==0x80 );
85944   }
85945   if( nNeedle>nHaystack ) N = 0;
85946   sqlite3_result_int(context, N);
85947 }
85948
85949 /*
85950 ** Implementation of the substr() function.
85951 **
85952 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
85953 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
85954 ** of x.  If x is text, then we actually count UTF-8 characters.
85955 ** If x is a blob, then we count bytes.
85956 **
85957 ** If p1 is negative, then we begin abs(p1) from the end of x[].
85958 **
85959 ** If p2 is negative, return the p2 characters preceeding p1.
85960 */
85961 static void substrFunc(
85962   sqlite3_context *context,
85963   int argc,
85964   sqlite3_value **argv
85965 ){
85966   const unsigned char *z;
85967   const unsigned char *z2;
85968   int len;
85969   int p0type;
85970   i64 p1, p2;
85971   int negP2 = 0;
85972
85973   assert( argc==3 || argc==2 );
85974   if( sqlite3_value_type(argv[1])==SQLITE_NULL
85975    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
85976   ){
85977     return;
85978   }
85979   p0type = sqlite3_value_type(argv[0]);
85980   p1 = sqlite3_value_int(argv[1]);
85981   if( p0type==SQLITE_BLOB ){
85982     len = sqlite3_value_bytes(argv[0]);
85983     z = sqlite3_value_blob(argv[0]);
85984     if( z==0 ) return;
85985     assert( len==sqlite3_value_bytes(argv[0]) );
85986   }else{
85987     z = sqlite3_value_text(argv[0]);
85988     if( z==0 ) return;
85989     len = 0;
85990     if( p1<0 ){
85991       for(z2=z; *z2; len++){
85992         SQLITE_SKIP_UTF8(z2);
85993       }
85994     }
85995   }
85996   if( argc==3 ){
85997     p2 = sqlite3_value_int(argv[2]);
85998     if( p2<0 ){
85999       p2 = -p2;
86000       negP2 = 1;
86001     }
86002   }else{
86003     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
86004   }
86005   if( p1<0 ){
86006     p1 += len;
86007     if( p1<0 ){
86008       p2 += p1;
86009       if( p2<0 ) p2 = 0;
86010       p1 = 0;
86011     }
86012   }else if( p1>0 ){
86013     p1--;
86014   }else if( p2>0 ){
86015     p2--;
86016   }
86017   if( negP2 ){
86018     p1 -= p2;
86019     if( p1<0 ){
86020       p2 += p1;
86021       p1 = 0;
86022     }
86023   }
86024   assert( p1>=0 && p2>=0 );
86025   if( p0type!=SQLITE_BLOB ){
86026     while( *z && p1 ){
86027       SQLITE_SKIP_UTF8(z);
86028       p1--;
86029     }
86030     for(z2=z; *z2 && p2; p2--){
86031       SQLITE_SKIP_UTF8(z2);
86032     }
86033     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
86034   }else{
86035     if( p1+p2>len ){
86036       p2 = len-p1;
86037       if( p2<0 ) p2 = 0;
86038     }
86039     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
86040   }
86041 }
86042
86043 /*
86044 ** Implementation of the round() function
86045 */
86046 #ifndef SQLITE_OMIT_FLOATING_POINT
86047 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86048   int n = 0;
86049   double r;
86050   char *zBuf;
86051   assert( argc==1 || argc==2 );
86052   if( argc==2 ){
86053     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
86054     n = sqlite3_value_int(argv[1]);
86055     if( n>30 ) n = 30;
86056     if( n<0 ) n = 0;
86057   }
86058   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86059   r = sqlite3_value_double(argv[0]);
86060   /* If Y==0 and X will fit in a 64-bit int,
86061   ** handle the rounding directly,
86062   ** otherwise use printf.
86063   */
86064   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86065     r = (double)((sqlite_int64)(r+0.5));
86066   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86067     r = -(double)((sqlite_int64)((-r)+0.5));
86068   }else{
86069     zBuf = sqlite3_mprintf("%.*f",n,r);
86070     if( zBuf==0 ){
86071       sqlite3_result_error_nomem(context);
86072       return;
86073     }
86074     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
86075     sqlite3_free(zBuf);
86076   }
86077   sqlite3_result_double(context, r);
86078 }
86079 #endif
86080
86081 /*
86082 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
86083 ** allocation fails, call sqlite3_result_error_nomem() to notify
86084 ** the database handle that malloc() has failed and return NULL.
86085 ** If nByte is larger than the maximum string or blob length, then
86086 ** raise an SQLITE_TOOBIG exception and return NULL.
86087 */
86088 static void *contextMalloc(sqlite3_context *context, i64 nByte){
86089   char *z;
86090   sqlite3 *db = sqlite3_context_db_handle(context);
86091   assert( nByte>0 );
86092   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
86093   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86094   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86095     sqlite3_result_error_toobig(context);
86096     z = 0;
86097   }else{
86098     z = sqlite3Malloc((int)nByte);
86099     if( !z ){
86100       sqlite3_result_error_nomem(context);
86101     }
86102   }
86103   return z;
86104 }
86105
86106 /*
86107 ** Implementation of the upper() and lower() SQL functions.
86108 */
86109 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86110   char *z1;
86111   const char *z2;
86112   int i, n;
86113   UNUSED_PARAMETER(argc);
86114   z2 = (char*)sqlite3_value_text(argv[0]);
86115   n = sqlite3_value_bytes(argv[0]);
86116   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86117   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86118   if( z2 ){
86119     z1 = contextMalloc(context, ((i64)n)+1);
86120     if( z1 ){
86121       for(i=0; i<n; i++){
86122         z1[i] = (char)sqlite3Toupper(z2[i]);
86123       }
86124       sqlite3_result_text(context, z1, n, sqlite3_free);
86125     }
86126   }
86127 }
86128 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86129   char *z1;
86130   const char *z2;
86131   int i, n;
86132   UNUSED_PARAMETER(argc);
86133   z2 = (char*)sqlite3_value_text(argv[0]);
86134   n = sqlite3_value_bytes(argv[0]);
86135   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86136   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86137   if( z2 ){
86138     z1 = contextMalloc(context, ((i64)n)+1);
86139     if( z1 ){
86140       for(i=0; i<n; i++){
86141         z1[i] = sqlite3Tolower(z2[i]);
86142       }
86143       sqlite3_result_text(context, z1, n, sqlite3_free);
86144     }
86145   }
86146 }
86147
86148 /*
86149 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
86150 ** that unused argument values do not have to be computed.  However, we
86151 ** still need some kind of function implementation for this routines in
86152 ** the function table.  That function implementation will never be called
86153 ** so it doesn't matter what the implementation is.  We might as well use
86154 ** the "version()" function as a substitute.
86155 */
86156 #define ifnullFunc versionFunc   /* Substitute function - never called */
86157
86158 /*
86159 ** Implementation of random().  Return a random integer.  
86160 */
86161 static void randomFunc(
86162   sqlite3_context *context,
86163   int NotUsed,
86164   sqlite3_value **NotUsed2
86165 ){
86166   sqlite_int64 r;
86167   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86168   sqlite3_randomness(sizeof(r), &r);
86169   if( r<0 ){
86170     /* We need to prevent a random number of 0x8000000000000000 
86171     ** (or -9223372036854775808) since when you do abs() of that
86172     ** number of you get the same value back again.  To do this
86173     ** in a way that is testable, mask the sign bit off of negative
86174     ** values, resulting in a positive value.  Then take the 
86175     ** 2s complement of that positive value.  The end result can
86176     ** therefore be no less than -9223372036854775807.
86177     */
86178     r = -(r & LARGEST_INT64);
86179   }
86180   sqlite3_result_int64(context, r);
86181 }
86182
86183 /*
86184 ** Implementation of randomblob(N).  Return a random blob
86185 ** that is N bytes long.
86186 */
86187 static void randomBlob(
86188   sqlite3_context *context,
86189   int argc,
86190   sqlite3_value **argv
86191 ){
86192   int n;
86193   unsigned char *p;
86194   assert( argc==1 );
86195   UNUSED_PARAMETER(argc);
86196   n = sqlite3_value_int(argv[0]);
86197   if( n<1 ){
86198     n = 1;
86199   }
86200   p = contextMalloc(context, n);
86201   if( p ){
86202     sqlite3_randomness(n, p);
86203     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
86204   }
86205 }
86206
86207 /*
86208 ** Implementation of the last_insert_rowid() SQL function.  The return
86209 ** value is the same as the sqlite3_last_insert_rowid() API function.
86210 */
86211 static void last_insert_rowid(
86212   sqlite3_context *context, 
86213   int NotUsed, 
86214   sqlite3_value **NotUsed2
86215 ){
86216   sqlite3 *db = sqlite3_context_db_handle(context);
86217   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86218   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86219   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
86220   ** function. */
86221   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
86222 }
86223
86224 /*
86225 ** Implementation of the changes() SQL function.
86226 **
86227 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
86228 ** around the sqlite3_changes() C/C++ function and hence follows the same
86229 ** rules for counting changes.
86230 */
86231 static void changes(
86232   sqlite3_context *context,
86233   int NotUsed,
86234   sqlite3_value **NotUsed2
86235 ){
86236   sqlite3 *db = sqlite3_context_db_handle(context);
86237   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86238   sqlite3_result_int(context, sqlite3_changes(db));
86239 }
86240
86241 /*
86242 ** Implementation of the total_changes() SQL function.  The return value is
86243 ** the same as the sqlite3_total_changes() API function.
86244 */
86245 static void total_changes(
86246   sqlite3_context *context,
86247   int NotUsed,
86248   sqlite3_value **NotUsed2
86249 ){
86250   sqlite3 *db = sqlite3_context_db_handle(context);
86251   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86252   /* IMP: R-52756-41993 This function is a wrapper around the
86253   ** sqlite3_total_changes() C/C++ interface. */
86254   sqlite3_result_int(context, sqlite3_total_changes(db));
86255 }
86256
86257 /*
86258 ** A structure defining how to do GLOB-style comparisons.
86259 */
86260 struct compareInfo {
86261   u8 matchAll;
86262   u8 matchOne;
86263   u8 matchSet;
86264   u8 noCase;
86265 };
86266
86267 /*
86268 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
86269 ** character is exactly one byte in size.  Also, all characters are
86270 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
86271 ** whereas only characters less than 0x80 do in ASCII.
86272 */
86273 #if defined(SQLITE_EBCDIC)
86274 # define sqlite3Utf8Read(A)    (*((*A)++))
86275 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
86276 #else
86277 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
86278 #endif
86279
86280 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86281 /* The correct SQL-92 behavior is for the LIKE operator to ignore
86282 ** case.  Thus  'a' LIKE 'A' would be true. */
86283 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86284 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86285 ** is case sensitive causing 'a' LIKE 'A' to be false */
86286 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86287
86288 /*
86289 ** Compare two UTF-8 strings for equality where the first string can
86290 ** potentially be a "glob" expression.  Return true (1) if they
86291 ** are the same and false (0) if they are different.
86292 **
86293 ** Globbing rules:
86294 **
86295 **      '*'       Matches any sequence of zero or more characters.
86296 **
86297 **      '?'       Matches exactly one character.
86298 **
86299 **     [...]      Matches one character from the enclosed list of
86300 **                characters.
86301 **
86302 **     [^...]     Matches one character not in the enclosed list.
86303 **
86304 ** With the [...] and [^...] matching, a ']' character can be included
86305 ** in the list by making it the first character after '[' or '^'.  A
86306 ** range of characters can be specified using '-'.  Example:
86307 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
86308 ** it the last character in the list.
86309 **
86310 ** This routine is usually quick, but can be N**2 in the worst case.
86311 **
86312 ** Hints: to match '*' or '?', put them in "[]".  Like this:
86313 **
86314 **         abc[*]xyz        Matches "abc*xyz" only
86315 */
86316 static int patternCompare(
86317   const u8 *zPattern,              /* The glob pattern */
86318   const u8 *zString,               /* The string to compare against the glob */
86319   const struct compareInfo *pInfo, /* Information about how to do the compare */
86320   u32 esc                          /* The escape character */
86321 ){
86322   u32 c, c2;
86323   int invert;
86324   int seen;
86325   u8 matchOne = pInfo->matchOne;
86326   u8 matchAll = pInfo->matchAll;
86327   u8 matchSet = pInfo->matchSet;
86328   u8 noCase = pInfo->noCase; 
86329   int prevEscape = 0;     /* True if the previous character was 'escape' */
86330
86331   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
86332     if( c==matchAll && !prevEscape ){
86333       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
86334                || c == matchOne ){
86335         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
86336           return 0;
86337         }
86338       }
86339       if( c==0 ){
86340         return 1;
86341       }else if( c==esc ){
86342         c = sqlite3Utf8Read(&zPattern);
86343         if( c==0 ){
86344           return 0;
86345         }
86346       }else if( c==matchSet ){
86347         assert( esc==0 );         /* This is GLOB, not LIKE */
86348         assert( matchSet<0x80 );  /* '[' is a single-byte character */
86349         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86350           SQLITE_SKIP_UTF8(zString);
86351         }
86352         return *zString!=0;
86353       }
86354       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
86355         if( noCase ){
86356           GlogUpperToLower(c2);
86357           GlogUpperToLower(c);
86358           while( c2 != 0 && c2 != c ){
86359             c2 = sqlite3Utf8Read(&zString);
86360             GlogUpperToLower(c2);
86361           }
86362         }else{
86363           while( c2 != 0 && c2 != c ){
86364             c2 = sqlite3Utf8Read(&zString);
86365           }
86366         }
86367         if( c2==0 ) return 0;
86368         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86369       }
86370       return 0;
86371     }else if( c==matchOne && !prevEscape ){
86372       if( sqlite3Utf8Read(&zString)==0 ){
86373         return 0;
86374       }
86375     }else if( c==matchSet ){
86376       u32 prior_c = 0;
86377       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86378       seen = 0;
86379       invert = 0;
86380       c = sqlite3Utf8Read(&zString);
86381       if( c==0 ) return 0;
86382       c2 = sqlite3Utf8Read(&zPattern);
86383       if( c2=='^' ){
86384         invert = 1;
86385         c2 = sqlite3Utf8Read(&zPattern);
86386       }
86387       if( c2==']' ){
86388         if( c==']' ) seen = 1;
86389         c2 = sqlite3Utf8Read(&zPattern);
86390       }
86391       while( c2 && c2!=']' ){
86392         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86393           c2 = sqlite3Utf8Read(&zPattern);
86394           if( c>=prior_c && c<=c2 ) seen = 1;
86395           prior_c = 0;
86396         }else{
86397           if( c==c2 ){
86398             seen = 1;
86399           }
86400           prior_c = c2;
86401         }
86402         c2 = sqlite3Utf8Read(&zPattern);
86403       }
86404       if( c2==0 || (seen ^ invert)==0 ){
86405         return 0;
86406       }
86407     }else if( esc==c && !prevEscape ){
86408       prevEscape = 1;
86409     }else{
86410       c2 = sqlite3Utf8Read(&zString);
86411       if( noCase ){
86412         GlogUpperToLower(c);
86413         GlogUpperToLower(c2);
86414       }
86415       if( c!=c2 ){
86416         return 0;
86417       }
86418       prevEscape = 0;
86419     }
86420   }
86421   return *zString==0;
86422 }
86423
86424 /*
86425 ** Count the number of times that the LIKE operator (or GLOB which is
86426 ** just a variation of LIKE) gets called.  This is used for testing
86427 ** only.
86428 */
86429 #ifdef SQLITE_TEST
86430 SQLITE_API int sqlite3_like_count = 0;
86431 #endif
86432
86433
86434 /*
86435 ** Implementation of the like() SQL function.  This function implements
86436 ** the build-in LIKE operator.  The first argument to the function is the
86437 ** pattern and the second argument is the string.  So, the SQL statements:
86438 **
86439 **       A LIKE B
86440 **
86441 ** is implemented as like(B,A).
86442 **
86443 ** This same function (with a different compareInfo structure) computes
86444 ** the GLOB operator.
86445 */
86446 static void likeFunc(
86447   sqlite3_context *context, 
86448   int argc, 
86449   sqlite3_value **argv
86450 ){
86451   const unsigned char *zA, *zB;
86452   u32 escape = 0;
86453   int nPat;
86454   sqlite3 *db = sqlite3_context_db_handle(context);
86455
86456   zB = sqlite3_value_text(argv[0]);
86457   zA = sqlite3_value_text(argv[1]);
86458
86459   /* Limit the length of the LIKE or GLOB pattern to avoid problems
86460   ** of deep recursion and N*N behavior in patternCompare().
86461   */
86462   nPat = sqlite3_value_bytes(argv[0]);
86463   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
86464   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86465   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
86466     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86467     return;
86468   }
86469   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
86470
86471   if( argc==3 ){
86472     /* The escape character string must consist of a single UTF-8 character.
86473     ** Otherwise, return an error.
86474     */
86475     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
86476     if( zEsc==0 ) return;
86477     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
86478       sqlite3_result_error(context, 
86479           "ESCAPE expression must be a single character", -1);
86480       return;
86481     }
86482     escape = sqlite3Utf8Read(&zEsc);
86483   }
86484   if( zA && zB ){
86485     struct compareInfo *pInfo = sqlite3_user_data(context);
86486 #ifdef SQLITE_TEST
86487     sqlite3_like_count++;
86488 #endif
86489     
86490     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86491   }
86492 }
86493
86494 /*
86495 ** Implementation of the NULLIF(x,y) function.  The result is the first
86496 ** argument if the arguments are different.  The result is NULL if the
86497 ** arguments are equal to each other.
86498 */
86499 static void nullifFunc(
86500   sqlite3_context *context,
86501   int NotUsed,
86502   sqlite3_value **argv
86503 ){
86504   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86505   UNUSED_PARAMETER(NotUsed);
86506   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
86507     sqlite3_result_value(context, argv[0]);
86508   }
86509 }
86510
86511 /*
86512 ** Implementation of the sqlite_version() function.  The result is the version
86513 ** of the SQLite library that is running.
86514 */
86515 static void versionFunc(
86516   sqlite3_context *context,
86517   int NotUsed,
86518   sqlite3_value **NotUsed2
86519 ){
86520   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86521   /* IMP: R-48699-48617 This function is an SQL wrapper around the
86522   ** sqlite3_libversion() C-interface. */
86523   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
86524 }
86525
86526 /*
86527 ** Implementation of the sqlite_source_id() function. The result is a string
86528 ** that identifies the particular version of the source code used to build
86529 ** SQLite.
86530 */
86531 static void sourceidFunc(
86532   sqlite3_context *context,
86533   int NotUsed,
86534   sqlite3_value **NotUsed2
86535 ){
86536   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86537   /* IMP: R-24470-31136 This function is an SQL wrapper around the
86538   ** sqlite3_sourceid() C interface. */
86539   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
86540 }
86541
86542 /*
86543 ** Implementation of the sqlite_log() function.  This is a wrapper around
86544 ** sqlite3_log().  The return value is NULL.  The function exists purely for
86545 ** its side-effects.
86546 */
86547 static void errlogFunc(
86548   sqlite3_context *context,
86549   int argc,
86550   sqlite3_value **argv
86551 ){
86552   UNUSED_PARAMETER(argc);
86553   UNUSED_PARAMETER(context);
86554   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
86555 }
86556
86557 /*
86558 ** Implementation of the sqlite_compileoption_used() function.
86559 ** The result is an integer that identifies if the compiler option
86560 ** was used to build SQLite.
86561 */
86562 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86563 static void compileoptionusedFunc(
86564   sqlite3_context *context,
86565   int argc,
86566   sqlite3_value **argv
86567 ){
86568   const char *zOptName;
86569   assert( argc==1 );
86570   UNUSED_PARAMETER(argc);
86571   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
86572   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
86573   ** function.
86574   */
86575   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
86576     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
86577   }
86578 }
86579 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86580
86581 /*
86582 ** Implementation of the sqlite_compileoption_get() function. 
86583 ** The result is a string that identifies the compiler options 
86584 ** used to build SQLite.
86585 */
86586 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86587 static void compileoptiongetFunc(
86588   sqlite3_context *context,
86589   int argc,
86590   sqlite3_value **argv
86591 ){
86592   int n;
86593   assert( argc==1 );
86594   UNUSED_PARAMETER(argc);
86595   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
86596   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
86597   */
86598   n = sqlite3_value_int(argv[0]);
86599   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
86600 }
86601 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86602
86603 /* Array for converting from half-bytes (nybbles) into ASCII hex
86604 ** digits. */
86605 static const char hexdigits[] = {
86606   '0', '1', '2', '3', '4', '5', '6', '7',
86607   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
86608 };
86609
86610 /*
86611 ** EXPERIMENTAL - This is not an official function.  The interface may
86612 ** change.  This function may disappear.  Do not write code that depends
86613 ** on this function.
86614 **
86615 ** Implementation of the QUOTE() function.  This function takes a single
86616 ** argument.  If the argument is numeric, the return value is the same as
86617 ** the argument.  If the argument is NULL, the return value is the string
86618 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
86619 ** single-quote escapes.
86620 */
86621 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86622   assert( argc==1 );
86623   UNUSED_PARAMETER(argc);
86624   switch( sqlite3_value_type(argv[0]) ){
86625     case SQLITE_FLOAT: {
86626       double r1, r2;
86627       char zBuf[50];
86628       r1 = sqlite3_value_double(argv[0]);
86629       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
86630       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
86631       if( r1!=r2 ){
86632         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
86633       }
86634       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
86635       break;
86636     }
86637     case SQLITE_INTEGER: {
86638       sqlite3_result_value(context, argv[0]);
86639       break;
86640     }
86641     case SQLITE_BLOB: {
86642       char *zText = 0;
86643       char const *zBlob = sqlite3_value_blob(argv[0]);
86644       int nBlob = sqlite3_value_bytes(argv[0]);
86645       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
86646       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
86647       if( zText ){
86648         int i;
86649         for(i=0; i<nBlob; i++){
86650           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86651           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86652         }
86653         zText[(nBlob*2)+2] = '\'';
86654         zText[(nBlob*2)+3] = '\0';
86655         zText[0] = 'X';
86656         zText[1] = '\'';
86657         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
86658         sqlite3_free(zText);
86659       }
86660       break;
86661     }
86662     case SQLITE_TEXT: {
86663       int i,j;
86664       u64 n;
86665       const unsigned char *zArg = sqlite3_value_text(argv[0]);
86666       char *z;
86667
86668       if( zArg==0 ) return;
86669       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86670       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86671       if( z ){
86672         z[0] = '\'';
86673         for(i=0, j=1; zArg[i]; i++){
86674           z[j++] = zArg[i];
86675           if( zArg[i]=='\'' ){
86676             z[j++] = '\'';
86677           }
86678         }
86679         z[j++] = '\'';
86680         z[j] = 0;
86681         sqlite3_result_text(context, z, j, sqlite3_free);
86682       }
86683       break;
86684     }
86685     default: {
86686       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
86687       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
86688       break;
86689     }
86690   }
86691 }
86692
86693 /*
86694 ** The hex() function.  Interpret the argument as a blob.  Return
86695 ** a hexadecimal rendering as text.
86696 */
86697 static void hexFunc(
86698   sqlite3_context *context,
86699   int argc,
86700   sqlite3_value **argv
86701 ){
86702   int i, n;
86703   const unsigned char *pBlob;
86704   char *zHex, *z;
86705   assert( argc==1 );
86706   UNUSED_PARAMETER(argc);
86707   pBlob = sqlite3_value_blob(argv[0]);
86708   n = sqlite3_value_bytes(argv[0]);
86709   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
86710   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86711   if( zHex ){
86712     for(i=0; i<n; i++, pBlob++){
86713       unsigned char c = *pBlob;
86714       *(z++) = hexdigits[(c>>4)&0xf];
86715       *(z++) = hexdigits[c&0xf];
86716     }
86717     *z = 0;
86718     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
86719   }
86720 }
86721
86722 /*
86723 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86724 */
86725 static void zeroblobFunc(
86726   sqlite3_context *context,
86727   int argc,
86728   sqlite3_value **argv
86729 ){
86730   i64 n;
86731   sqlite3 *db = sqlite3_context_db_handle(context);
86732   assert( argc==1 );
86733   UNUSED_PARAMETER(argc);
86734   n = sqlite3_value_int64(argv[0]);
86735   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
86736   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86737   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86738     sqlite3_result_error_toobig(context);
86739   }else{
86740     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86741   }
86742 }
86743
86744 /*
86745 ** The replace() function.  Three arguments are all strings: call
86746 ** them A, B, and C. The result is also a string which is derived
86747 ** from A by replacing every occurance of B with C.  The match
86748 ** must be exact.  Collating sequences are not used.
86749 */
86750 static void replaceFunc(
86751   sqlite3_context *context,
86752   int argc,
86753   sqlite3_value **argv
86754 ){
86755   const unsigned char *zStr;        /* The input string A */
86756   const unsigned char *zPattern;    /* The pattern string B */
86757   const unsigned char *zRep;        /* The replacement string C */
86758   unsigned char *zOut;              /* The output */
86759   int nStr;                /* Size of zStr */
86760   int nPattern;            /* Size of zPattern */
86761   int nRep;                /* Size of zRep */
86762   i64 nOut;                /* Maximum size of zOut */
86763   int loopLimit;           /* Last zStr[] that might match zPattern[] */
86764   int i, j;                /* Loop counters */
86765
86766   assert( argc==3 );
86767   UNUSED_PARAMETER(argc);
86768   zStr = sqlite3_value_text(argv[0]);
86769   if( zStr==0 ) return;
86770   nStr = sqlite3_value_bytes(argv[0]);
86771   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
86772   zPattern = sqlite3_value_text(argv[1]);
86773   if( zPattern==0 ){
86774     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
86775             || sqlite3_context_db_handle(context)->mallocFailed );
86776     return;
86777   }
86778   if( zPattern[0]==0 ){
86779     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
86780     sqlite3_result_value(context, argv[0]);
86781     return;
86782   }
86783   nPattern = sqlite3_value_bytes(argv[1]);
86784   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
86785   zRep = sqlite3_value_text(argv[2]);
86786   if( zRep==0 ) return;
86787   nRep = sqlite3_value_bytes(argv[2]);
86788   assert( zRep==sqlite3_value_text(argv[2]) );
86789   nOut = nStr + 1;
86790   assert( nOut<SQLITE_MAX_LENGTH );
86791   zOut = contextMalloc(context, (i64)nOut);
86792   if( zOut==0 ){
86793     return;
86794   }
86795   loopLimit = nStr - nPattern;  
86796   for(i=j=0; i<=loopLimit; i++){
86797     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
86798       zOut[j++] = zStr[i];
86799     }else{
86800       u8 *zOld;
86801       sqlite3 *db = sqlite3_context_db_handle(context);
86802       nOut += nRep - nPattern;
86803       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
86804       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
86805       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86806         sqlite3_result_error_toobig(context);
86807         sqlite3_free(zOut);
86808         return;
86809       }
86810       zOld = zOut;
86811       zOut = sqlite3_realloc(zOut, (int)nOut);
86812       if( zOut==0 ){
86813         sqlite3_result_error_nomem(context);
86814         sqlite3_free(zOld);
86815         return;
86816       }
86817       memcpy(&zOut[j], zRep, nRep);
86818       j += nRep;
86819       i += nPattern-1;
86820     }
86821   }
86822   assert( j+nStr-i+1==nOut );
86823   memcpy(&zOut[j], &zStr[i], nStr-i);
86824   j += nStr - i;
86825   assert( j<=nOut );
86826   zOut[j] = 0;
86827   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
86828 }
86829
86830 /*
86831 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
86832 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
86833 */
86834 static void trimFunc(
86835   sqlite3_context *context,
86836   int argc,
86837   sqlite3_value **argv
86838 ){
86839   const unsigned char *zIn;         /* Input string */
86840   const unsigned char *zCharSet;    /* Set of characters to trim */
86841   int nIn;                          /* Number of bytes in input */
86842   int flags;                        /* 1: trimleft  2: trimright  3: trim */
86843   int i;                            /* Loop counter */
86844   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
86845   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
86846   int nChar;                        /* Number of characters in zCharSet */
86847
86848   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
86849     return;
86850   }
86851   zIn = sqlite3_value_text(argv[0]);
86852   if( zIn==0 ) return;
86853   nIn = sqlite3_value_bytes(argv[0]);
86854   assert( zIn==sqlite3_value_text(argv[0]) );
86855   if( argc==1 ){
86856     static const unsigned char lenOne[] = { 1 };
86857     static unsigned char * const azOne[] = { (u8*)" " };
86858     nChar = 1;
86859     aLen = (u8*)lenOne;
86860     azChar = (unsigned char **)azOne;
86861     zCharSet = 0;
86862   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
86863     return;
86864   }else{
86865     const unsigned char *z;
86866     for(z=zCharSet, nChar=0; *z; nChar++){
86867       SQLITE_SKIP_UTF8(z);
86868     }
86869     if( nChar>0 ){
86870       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
86871       if( azChar==0 ){
86872         return;
86873       }
86874       aLen = (unsigned char*)&azChar[nChar];
86875       for(z=zCharSet, nChar=0; *z; nChar++){
86876         azChar[nChar] = (unsigned char *)z;
86877         SQLITE_SKIP_UTF8(z);
86878         aLen[nChar] = (u8)(z - azChar[nChar]);
86879       }
86880     }
86881   }
86882   if( nChar>0 ){
86883     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
86884     if( flags & 1 ){
86885       while( nIn>0 ){
86886         int len = 0;
86887         for(i=0; i<nChar; i++){
86888           len = aLen[i];
86889           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
86890         }
86891         if( i>=nChar ) break;
86892         zIn += len;
86893         nIn -= len;
86894       }
86895     }
86896     if( flags & 2 ){
86897       while( nIn>0 ){
86898         int len = 0;
86899         for(i=0; i<nChar; i++){
86900           len = aLen[i];
86901           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
86902         }
86903         if( i>=nChar ) break;
86904         nIn -= len;
86905       }
86906     }
86907     if( zCharSet ){
86908       sqlite3_free(azChar);
86909     }
86910   }
86911   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
86912 }
86913
86914
86915 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
86916 ** is only available if the SQLITE_SOUNDEX compile-time option is used
86917 ** when SQLite is built.
86918 */
86919 #ifdef SQLITE_SOUNDEX
86920 /*
86921 ** Compute the soundex encoding of a word.
86922 **
86923 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
86924 ** soundex encoding of the string X. 
86925 */
86926 static void soundexFunc(
86927   sqlite3_context *context,
86928   int argc,
86929   sqlite3_value **argv
86930 ){
86931   char zResult[8];
86932   const u8 *zIn;
86933   int i, j;
86934   static const unsigned char iCode[] = {
86935     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86936     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86937     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86938     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86939     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86940     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86941     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
86942     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
86943   };
86944   assert( argc==1 );
86945   zIn = (u8*)sqlite3_value_text(argv[0]);
86946   if( zIn==0 ) zIn = (u8*)"";
86947   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
86948   if( zIn[i] ){
86949     u8 prevcode = iCode[zIn[i]&0x7f];
86950     zResult[0] = sqlite3Toupper(zIn[i]);
86951     for(j=1; j<4 && zIn[i]; i++){
86952       int code = iCode[zIn[i]&0x7f];
86953       if( code>0 ){
86954         if( code!=prevcode ){
86955           prevcode = code;
86956           zResult[j++] = code + '0';
86957         }
86958       }else{
86959         prevcode = 0;
86960       }
86961     }
86962     while( j<4 ){
86963       zResult[j++] = '0';
86964     }
86965     zResult[j] = 0;
86966     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
86967   }else{
86968     /* IMP: R-64894-50321 The string "?000" is returned if the argument
86969     ** is NULL or contains no ASCII alphabetic characters. */
86970     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
86971   }
86972 }
86973 #endif /* SQLITE_SOUNDEX */
86974
86975 #ifndef SQLITE_OMIT_LOAD_EXTENSION
86976 /*
86977 ** A function that loads a shared-library extension then returns NULL.
86978 */
86979 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
86980   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
86981   const char *zProc;
86982   sqlite3 *db = sqlite3_context_db_handle(context);
86983   char *zErrMsg = 0;
86984
86985   if( argc==2 ){
86986     zProc = (const char *)sqlite3_value_text(argv[1]);
86987   }else{
86988     zProc = 0;
86989   }
86990   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
86991     sqlite3_result_error(context, zErrMsg, -1);
86992     sqlite3_free(zErrMsg);
86993   }
86994 }
86995 #endif
86996
86997
86998 /*
86999 ** An instance of the following structure holds the context of a
87000 ** sum() or avg() aggregate computation.
87001 */
87002 typedef struct SumCtx SumCtx;
87003 struct SumCtx {
87004   double rSum;      /* Floating point sum */
87005   i64 iSum;         /* Integer sum */   
87006   i64 cnt;          /* Number of elements summed */
87007   u8 overflow;      /* True if integer overflow seen */
87008   u8 approx;        /* True if non-integer value was input to the sum */
87009 };
87010
87011 /*
87012 ** Routines used to compute the sum, average, and total.
87013 **
87014 ** The SUM() function follows the (broken) SQL standard which means
87015 ** that it returns NULL if it sums over no inputs.  TOTAL returns
87016 ** 0.0 in that case.  In addition, TOTAL always returns a float where
87017 ** SUM might return an integer if it never encounters a floating point
87018 ** value.  TOTAL never fails, but SUM might through an exception if
87019 ** it overflows an integer.
87020 */
87021 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87022   SumCtx *p;
87023   int type;
87024   assert( argc==1 );
87025   UNUSED_PARAMETER(argc);
87026   p = sqlite3_aggregate_context(context, sizeof(*p));
87027   type = sqlite3_value_numeric_type(argv[0]);
87028   if( p && type!=SQLITE_NULL ){
87029     p->cnt++;
87030     if( type==SQLITE_INTEGER ){
87031       i64 v = sqlite3_value_int64(argv[0]);
87032       p->rSum += v;
87033       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
87034         p->overflow = 1;
87035       }
87036     }else{
87037       p->rSum += sqlite3_value_double(argv[0]);
87038       p->approx = 1;
87039     }
87040   }
87041 }
87042 static void sumFinalize(sqlite3_context *context){
87043   SumCtx *p;
87044   p = sqlite3_aggregate_context(context, 0);
87045   if( p && p->cnt>0 ){
87046     if( p->overflow ){
87047       sqlite3_result_error(context,"integer overflow",-1);
87048     }else if( p->approx ){
87049       sqlite3_result_double(context, p->rSum);
87050     }else{
87051       sqlite3_result_int64(context, p->iSum);
87052     }
87053   }
87054 }
87055 static void avgFinalize(sqlite3_context *context){
87056   SumCtx *p;
87057   p = sqlite3_aggregate_context(context, 0);
87058   if( p && p->cnt>0 ){
87059     sqlite3_result_double(context, p->rSum/(double)p->cnt);
87060   }
87061 }
87062 static void totalFinalize(sqlite3_context *context){
87063   SumCtx *p;
87064   p = sqlite3_aggregate_context(context, 0);
87065   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
87066   sqlite3_result_double(context, p ? p->rSum : (double)0);
87067 }
87068
87069 /*
87070 ** The following structure keeps track of state information for the
87071 ** count() aggregate function.
87072 */
87073 typedef struct CountCtx CountCtx;
87074 struct CountCtx {
87075   i64 n;
87076 };
87077
87078 /*
87079 ** Routines to implement the count() aggregate function.
87080 */
87081 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87082   CountCtx *p;
87083   p = sqlite3_aggregate_context(context, sizeof(*p));
87084   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
87085     p->n++;
87086   }
87087
87088 #ifndef SQLITE_OMIT_DEPRECATED
87089   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
87090   ** sure it still operates correctly, verify that its count agrees with our 
87091   ** internal count when using count(*) and when the total count can be
87092   ** expressed as a 32-bit integer. */
87093   assert( argc==1 || p==0 || p->n>0x7fffffff
87094           || p->n==sqlite3_aggregate_count(context) );
87095 #endif
87096 }   
87097 static void countFinalize(sqlite3_context *context){
87098   CountCtx *p;
87099   p = sqlite3_aggregate_context(context, 0);
87100   sqlite3_result_int64(context, p ? p->n : 0);
87101 }
87102
87103 /*
87104 ** Routines to implement min() and max() aggregate functions.
87105 */
87106 static void minmaxStep(
87107   sqlite3_context *context, 
87108   int NotUsed, 
87109   sqlite3_value **argv
87110 ){
87111   Mem *pArg  = (Mem *)argv[0];
87112   Mem *pBest;
87113   UNUSED_PARAMETER(NotUsed);
87114
87115   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
87116   if( !pBest ) return;
87117
87118   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87119     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
87120   }else if( pBest->flags ){
87121     int max;
87122     int cmp;
87123     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87124     /* This step function is used for both the min() and max() aggregates,
87125     ** the only difference between the two being that the sense of the
87126     ** comparison is inverted. For the max() aggregate, the
87127     ** sqlite3_user_data() function returns (void *)-1. For min() it
87128     ** returns (void *)db, where db is the sqlite3* database pointer.
87129     ** Therefore the next statement sets variable 'max' to 1 for the max()
87130     ** aggregate, or 0 for min().
87131     */
87132     max = sqlite3_user_data(context)!=0;
87133     cmp = sqlite3MemCompare(pBest, pArg, pColl);
87134     if( (max && cmp<0) || (!max && cmp>0) ){
87135       sqlite3VdbeMemCopy(pBest, pArg);
87136     }else{
87137       sqlite3SkipAccumulatorLoad(context);
87138     }
87139   }else{
87140     sqlite3VdbeMemCopy(pBest, pArg);
87141   }
87142 }
87143 static void minMaxFinalize(sqlite3_context *context){
87144   sqlite3_value *pRes;
87145   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
87146   if( pRes ){
87147     if( pRes->flags ){
87148       sqlite3_result_value(context, pRes);
87149     }
87150     sqlite3VdbeMemRelease(pRes);
87151   }
87152 }
87153
87154 /*
87155 ** group_concat(EXPR, ?SEPARATOR?)
87156 */
87157 static void groupConcatStep(
87158   sqlite3_context *context,
87159   int argc,
87160   sqlite3_value **argv
87161 ){
87162   const char *zVal;
87163   StrAccum *pAccum;
87164   const char *zSep;
87165   int nVal, nSep;
87166   assert( argc==1 || argc==2 );
87167   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87168   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
87169
87170   if( pAccum ){
87171     sqlite3 *db = sqlite3_context_db_handle(context);
87172     int firstTerm = pAccum->useMalloc==0;
87173     pAccum->useMalloc = 2;
87174     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
87175     if( !firstTerm ){
87176       if( argc==2 ){
87177         zSep = (char*)sqlite3_value_text(argv[1]);
87178         nSep = sqlite3_value_bytes(argv[1]);
87179       }else{
87180         zSep = ",";
87181         nSep = 1;
87182       }
87183       sqlite3StrAccumAppend(pAccum, zSep, nSep);
87184     }
87185     zVal = (char*)sqlite3_value_text(argv[0]);
87186     nVal = sqlite3_value_bytes(argv[0]);
87187     sqlite3StrAccumAppend(pAccum, zVal, nVal);
87188   }
87189 }
87190 static void groupConcatFinalize(sqlite3_context *context){
87191   StrAccum *pAccum;
87192   pAccum = sqlite3_aggregate_context(context, 0);
87193   if( pAccum ){
87194     if( pAccum->tooBig ){
87195       sqlite3_result_error_toobig(context);
87196     }else if( pAccum->mallocFailed ){
87197       sqlite3_result_error_nomem(context);
87198     }else{    
87199       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
87200                           sqlite3_free);
87201     }
87202   }
87203 }
87204
87205 /*
87206 ** This routine does per-connection function registration.  Most
87207 ** of the built-in functions above are part of the global function set.
87208 ** This routine only deals with those that are not global.
87209 */
87210 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
87211   int rc = sqlite3_overload_function(db, "MATCH", 2);
87212   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
87213   if( rc==SQLITE_NOMEM ){
87214     db->mallocFailed = 1;
87215   }
87216 }
87217
87218 /*
87219 ** Set the LIKEOPT flag on the 2-argument function with the given name.
87220 */
87221 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
87222   FuncDef *pDef;
87223   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
87224                              2, SQLITE_UTF8, 0);
87225   if( ALWAYS(pDef) ){
87226     pDef->flags = flagVal;
87227   }
87228 }
87229
87230 /*
87231 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
87232 ** parameter determines whether or not the LIKE operator is case
87233 ** sensitive.  GLOB is always case sensitive.
87234 */
87235 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
87236   struct compareInfo *pInfo;
87237   if( caseSensitive ){
87238     pInfo = (struct compareInfo*)&likeInfoAlt;
87239   }else{
87240     pInfo = (struct compareInfo*)&likeInfoNorm;
87241   }
87242   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87243   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87244   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
87245       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87246   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
87247   setLikeOptFlag(db, "like", 
87248       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
87249 }
87250
87251 /*
87252 ** pExpr points to an expression which implements a function.  If
87253 ** it is appropriate to apply the LIKE optimization to that function
87254 ** then set aWc[0] through aWc[2] to the wildcard characters and
87255 ** return TRUE.  If the function is not a LIKE-style function then
87256 ** return FALSE.
87257 */
87258 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87259   FuncDef *pDef;
87260   if( pExpr->op!=TK_FUNCTION 
87261    || !pExpr->x.pList 
87262    || pExpr->x.pList->nExpr!=2
87263   ){
87264     return 0;
87265   }
87266   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87267   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
87268                              sqlite3Strlen30(pExpr->u.zToken),
87269                              2, SQLITE_UTF8, 0);
87270   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
87271     return 0;
87272   }
87273
87274   /* The memcpy() statement assumes that the wildcard characters are
87275   ** the first three statements in the compareInfo structure.  The
87276   ** asserts() that follow verify that assumption
87277   */
87278   memcpy(aWc, pDef->pUserData, 3);
87279   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87280   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87281   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87282   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
87283   return 1;
87284 }
87285
87286 /*
87287 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
87288 ** to the global function hash table.  This occurs at start-time (as
87289 ** a consequence of calling sqlite3_initialize()).
87290 **
87291 ** After this routine runs
87292 */
87293 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
87294   /*
87295   ** The following array holds FuncDef structures for all of the functions
87296   ** defined in this file.
87297   **
87298   ** The array cannot be constant since changes are made to the
87299   ** FuncDef.pHash elements at start-time.  The elements of this array
87300   ** are read-only after initialization is complete.
87301   */
87302   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
87303     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87304     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87305     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87306     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87307     FUNCTION(trim,               1, 3, 0, trimFunc         ),
87308     FUNCTION(trim,               2, 3, 0, trimFunc         ),
87309     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87310     FUNCTION(min,                0, 0, 1, 0                ),
87311     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87312     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87313     FUNCTION(max,                0, 1, 1, 0                ),
87314     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87315     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
87316     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
87317     FUNCTION(instr,              2, 0, 0, instrFunc        ),
87318     FUNCTION(substr,             2, 0, 0, substrFunc       ),
87319     FUNCTION(substr,             3, 0, 0, substrFunc       ),
87320     FUNCTION(abs,                1, 0, 0, absFunc          ),
87321 #ifndef SQLITE_OMIT_FLOATING_POINT
87322     FUNCTION(round,              1, 0, 0, roundFunc        ),
87323     FUNCTION(round,              2, 0, 0, roundFunc        ),
87324 #endif
87325     FUNCTION(upper,              1, 0, 0, upperFunc        ),
87326     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87327     FUNCTION(coalesce,           1, 0, 0, 0                ),
87328     FUNCTION(coalesce,           0, 0, 0, 0                ),
87329     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87330     FUNCTION(hex,                1, 0, 0, hexFunc          ),
87331     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87332     FUNCTION(random,             0, 0, 0, randomFunc       ),
87333     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87334     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87335     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
87336     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
87337     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
87338 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87339     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87340     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87341 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87342     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87343     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87344     FUNCTION(changes,            0, 0, 0, changes          ),
87345     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87346     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87347     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87348   #ifdef SQLITE_SOUNDEX
87349     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87350   #endif
87351   #ifndef SQLITE_OMIT_LOAD_EXTENSION
87352     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87353     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87354   #endif
87355     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87356     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87357     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87358  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87359     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87360     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87361     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87362     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87363   
87364     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87365   #ifdef SQLITE_CASE_SENSITIVE_LIKE
87366     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87367     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87368   #else
87369     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
87370     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
87371   #endif
87372   };
87373
87374   int i;
87375   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87376   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87377
87378   for(i=0; i<ArraySize(aBuiltinFunc); i++){
87379     sqlite3FuncDefInsert(pHash, &aFunc[i]);
87380   }
87381   sqlite3RegisterDateTimeFunctions();
87382 #ifndef SQLITE_OMIT_ALTERTABLE
87383   sqlite3AlterFunctions();
87384 #endif
87385 }
87386
87387 /************** End of func.c ************************************************/
87388 /************** Begin file fkey.c ********************************************/
87389 /*
87390 **
87391 ** The author disclaims copyright to this source code.  In place of
87392 ** a legal notice, here is a blessing:
87393 **
87394 **    May you do good and not evil.
87395 **    May you find forgiveness for yourself and forgive others.
87396 **    May you share freely, never taking more than you give.
87397 **
87398 *************************************************************************
87399 ** This file contains code used by the compiler to add foreign key
87400 ** support to compiled SQL statements.
87401 */
87402
87403 #ifndef SQLITE_OMIT_FOREIGN_KEY
87404 #ifndef SQLITE_OMIT_TRIGGER
87405
87406 /*
87407 ** Deferred and Immediate FKs
87408 ** --------------------------
87409 **
87410 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
87411 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
87412 ** is returned and the current statement transaction rolled back. If a 
87413 ** deferred foreign key constraint is violated, no action is taken 
87414 ** immediately. However if the application attempts to commit the 
87415 ** transaction before fixing the constraint violation, the attempt fails.
87416 **
87417 ** Deferred constraints are implemented using a simple counter associated
87418 ** with the database handle. The counter is set to zero each time a 
87419 ** database transaction is opened. Each time a statement is executed 
87420 ** that causes a foreign key violation, the counter is incremented. Each
87421 ** time a statement is executed that removes an existing violation from
87422 ** the database, the counter is decremented. When the transaction is
87423 ** committed, the commit fails if the current value of the counter is
87424 ** greater than zero. This scheme has two big drawbacks:
87425 **
87426 **   * When a commit fails due to a deferred foreign key constraint, 
87427 **     there is no way to tell which foreign constraint is not satisfied,
87428 **     or which row it is not satisfied for.
87429 **
87430 **   * If the database contains foreign key violations when the 
87431 **     transaction is opened, this may cause the mechanism to malfunction.
87432 **
87433 ** Despite these problems, this approach is adopted as it seems simpler
87434 ** than the alternatives.
87435 **
87436 ** INSERT operations:
87437 **
87438 **   I.1) For each FK for which the table is the child table, search
87439 **        the parent table for a match. If none is found increment the
87440 **        constraint counter.
87441 **
87442 **   I.2) For each FK for which the table is the parent table, 
87443 **        search the child table for rows that correspond to the new
87444 **        row in the parent table. Decrement the counter for each row
87445 **        found (as the constraint is now satisfied).
87446 **
87447 ** DELETE operations:
87448 **
87449 **   D.1) For each FK for which the table is the child table, 
87450 **        search the parent table for a row that corresponds to the 
87451 **        deleted row in the child table. If such a row is not found, 
87452 **        decrement the counter.
87453 **
87454 **   D.2) For each FK for which the table is the parent table, search 
87455 **        the child table for rows that correspond to the deleted row 
87456 **        in the parent table. For each found increment the counter.
87457 **
87458 ** UPDATE operations:
87459 **
87460 **   An UPDATE command requires that all 4 steps above are taken, but only
87461 **   for FK constraints for which the affected columns are actually 
87462 **   modified (values must be compared at runtime).
87463 **
87464 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87465 ** This simplifies the implementation a bit.
87466 **
87467 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
87468 ** resolution is considered to delete rows before the new row is inserted.
87469 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
87470 ** is thrown, even if the FK constraint would be satisfied after the new 
87471 ** row is inserted.
87472 **
87473 ** Immediate constraints are usually handled similarly. The only difference 
87474 ** is that the counter used is stored as part of each individual statement
87475 ** object (struct Vdbe). If, after the statement has run, its immediate
87476 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
87477 ** and the statement transaction is rolled back. An exception is an INSERT
87478 ** statement that inserts a single row only (no triggers). In this case,
87479 ** instead of using a counter, an exception is thrown immediately if the
87480 ** INSERT violates a foreign key constraint. This is necessary as such
87481 ** an INSERT does not open a statement transaction.
87482 **
87483 ** TODO: How should dropping a table be handled? How should renaming a 
87484 ** table be handled?
87485 **
87486 **
87487 ** Query API Notes
87488 ** ---------------
87489 **
87490 ** Before coding an UPDATE or DELETE row operation, the code-generator
87491 ** for those two operations needs to know whether or not the operation
87492 ** requires any FK processing and, if so, which columns of the original
87493 ** row are required by the FK processing VDBE code (i.e. if FKs were
87494 ** implemented using triggers, which of the old.* columns would be 
87495 ** accessed). No information is required by the code-generator before
87496 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
87497 ** generation code to query for this information are:
87498 **
87499 **   sqlite3FkRequired() - Test to see if FK processing is required.
87500 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
87501 **
87502 **
87503 ** Externally accessible module functions
87504 ** --------------------------------------
87505 **
87506 **   sqlite3FkCheck()    - Check for foreign key violations.
87507 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87508 **   sqlite3FkDelete()   - Delete an FKey structure.
87509 */
87510
87511 /*
87512 ** VDBE Calling Convention
87513 ** -----------------------
87514 **
87515 ** Example:
87516 **
87517 **   For the following INSERT statement:
87518 **
87519 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87520 **     INSERT INTO t1 VALUES(1, 2, 3.1);
87521 **
87522 **   Register (x):        2    (type integer)
87523 **   Register (x+1):      1    (type integer)
87524 **   Register (x+2):      NULL (type NULL)
87525 **   Register (x+3):      3.1  (type real)
87526 */
87527
87528 /*
87529 ** A foreign key constraint requires that the key columns in the parent
87530 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87531 ** Given that pParent is the parent table for foreign key constraint pFKey, 
87532 ** search the schema a unique index on the parent key columns. 
87533 **
87534 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
87535 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
87536 ** is set to point to the unique index. 
87537 ** 
87538 ** If the parent key consists of a single column (the foreign key constraint
87539 ** is not a composite foreign key), output variable *paiCol is set to NULL.
87540 ** Otherwise, it is set to point to an allocated array of size N, where
87541 ** N is the number of columns in the parent key. The first element of the
87542 ** array is the index of the child table column that is mapped by the FK
87543 ** constraint to the parent table column stored in the left-most column
87544 ** of index *ppIdx. The second element of the array is the index of the
87545 ** child table column that corresponds to the second left-most column of
87546 ** *ppIdx, and so on.
87547 **
87548 ** If the required index cannot be found, either because:
87549 **
87550 **   1) The named parent key columns do not exist, or
87551 **
87552 **   2) The named parent key columns do exist, but are not subject to a
87553 **      UNIQUE or PRIMARY KEY constraint, or
87554 **
87555 **   3) No parent key columns were provided explicitly as part of the
87556 **      foreign key definition, and the parent table does not have a
87557 **      PRIMARY KEY, or
87558 **
87559 **   4) No parent key columns were provided explicitly as part of the
87560 **      foreign key definition, and the PRIMARY KEY of the parent table 
87561 **      consists of a a different number of columns to the child key in 
87562 **      the child table.
87563 **
87564 ** then non-zero is returned, and a "foreign key mismatch" error loaded
87565 ** into pParse. If an OOM error occurs, non-zero is returned and the
87566 ** pParse->db->mallocFailed flag is set.
87567 */
87568 static int locateFkeyIndex(
87569   Parse *pParse,                  /* Parse context to store any error in */
87570   Table *pParent,                 /* Parent table of FK constraint pFKey */
87571   FKey *pFKey,                    /* Foreign key to find index for */
87572   Index **ppIdx,                  /* OUT: Unique index on parent table */
87573   int **paiCol                    /* OUT: Map of index columns in pFKey */
87574 ){
87575   Index *pIdx = 0;                    /* Value to return via *ppIdx */
87576   int *aiCol = 0;                     /* Value to return via *paiCol */
87577   int nCol = pFKey->nCol;             /* Number of columns in parent key */
87578   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87579
87580   /* The caller is responsible for zeroing output parameters. */
87581   assert( ppIdx && *ppIdx==0 );
87582   assert( !paiCol || *paiCol==0 );
87583   assert( pParse );
87584
87585   /* If this is a non-composite (single column) foreign key, check if it 
87586   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
87587   ** and *paiCol set to zero and return early. 
87588   **
87589   ** Otherwise, for a composite foreign key (more than one column), allocate
87590   ** space for the aiCol array (returned via output parameter *paiCol).
87591   ** Non-composite foreign keys do not require the aiCol array.
87592   */
87593   if( nCol==1 ){
87594     /* The FK maps to the IPK if any of the following are true:
87595     **
87596     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
87597     **      mapped to the primary key of table pParent, or
87598     **   2) The FK is explicitly mapped to a column declared as INTEGER
87599     **      PRIMARY KEY.
87600     */
87601     if( pParent->iPKey>=0 ){
87602       if( !zKey ) return 0;
87603       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87604     }
87605   }else if( paiCol ){
87606     assert( nCol>1 );
87607     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
87608     if( !aiCol ) return 1;
87609     *paiCol = aiCol;
87610   }
87611
87612   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87613     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
87614       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87615       ** of columns. If each indexed column corresponds to a foreign key
87616       ** column of pFKey, then this index is a winner.  */
87617
87618       if( zKey==0 ){
87619         /* If zKey is NULL, then this foreign key is implicitly mapped to 
87620         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
87621         ** identified by the test (Index.autoIndex==2).  */
87622         if( pIdx->autoIndex==2 ){
87623           if( aiCol ){
87624             int i;
87625             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87626           }
87627           break;
87628         }
87629       }else{
87630         /* If zKey is non-NULL, then this foreign key was declared to
87631         ** map to an explicit list of columns in table pParent. Check if this
87632         ** index matches those columns. Also, check that the index uses
87633         ** the default collation sequences for each column. */
87634         int i, j;
87635         for(i=0; i<nCol; i++){
87636           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87637           char *zDfltColl;                  /* Def. collation for column */
87638           char *zIdxCol;                    /* Name of indexed column */
87639
87640           /* If the index uses a collation sequence that is different from
87641           ** the default collation sequence for the column, this index is
87642           ** unusable. Bail out early in this case.  */
87643           zDfltColl = pParent->aCol[iCol].zColl;
87644           if( !zDfltColl ){
87645             zDfltColl = "BINARY";
87646           }
87647           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
87648
87649           zIdxCol = pParent->aCol[iCol].zName;
87650           for(j=0; j<nCol; j++){
87651             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87652               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87653               break;
87654             }
87655           }
87656           if( j==nCol ) break;
87657         }
87658         if( i==nCol ) break;      /* pIdx is usable */
87659       }
87660     }
87661   }
87662
87663   if( !pIdx ){
87664     if( !pParse->disableTriggers ){
87665       sqlite3ErrorMsg(pParse, "foreign key mismatch");
87666     }
87667     sqlite3DbFree(pParse->db, aiCol);
87668     return 1;
87669   }
87670
87671   *ppIdx = pIdx;
87672   return 0;
87673 }
87674
87675 /*
87676 ** This function is called when a row is inserted into or deleted from the 
87677 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
87678 ** on the child table of pFKey, this function is invoked twice for each row
87679 ** affected - once to "delete" the old row, and then again to "insert" the
87680 ** new row.
87681 **
87682 ** Each time it is called, this function generates VDBE code to locate the
87683 ** row in the parent table that corresponds to the row being inserted into 
87684 ** or deleted from the child table. If the parent row can be found, no 
87685 ** special action is taken. Otherwise, if the parent row can *not* be
87686 ** found in the parent table:
87687 **
87688 **   Operation | FK type   | Action taken
87689 **   --------------------------------------------------------------------------
87690 **   INSERT      immediate   Increment the "immediate constraint counter".
87691 **
87692 **   DELETE      immediate   Decrement the "immediate constraint counter".
87693 **
87694 **   INSERT      deferred    Increment the "deferred constraint counter".
87695 **
87696 **   DELETE      deferred    Decrement the "deferred constraint counter".
87697 **
87698 ** These operations are identified in the comment at the top of this file 
87699 ** (fkey.c) as "I.1" and "D.1".
87700 */
87701 static void fkLookupParent(
87702   Parse *pParse,        /* Parse context */
87703   int iDb,              /* Index of database housing pTab */
87704   Table *pTab,          /* Parent table of FK pFKey */
87705   Index *pIdx,          /* Unique index on parent key columns in pTab */
87706   FKey *pFKey,          /* Foreign key constraint */
87707   int *aiCol,           /* Map from parent key columns to child table columns */
87708   int regData,          /* Address of array containing child table row */
87709   int nIncr,            /* Increment constraint counter by this */
87710   int isIgnore          /* If true, pretend pTab contains all NULL values */
87711 ){
87712   int i;                                    /* Iterator variable */
87713   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
87714   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87715   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
87716
87717   /* If nIncr is less than zero, then check at runtime if there are any
87718   ** outstanding constraints to resolve. If there are not, there is no need
87719   ** to check if deleting this row resolves any outstanding violations.
87720   **
87721   ** Check if any of the key columns in the child table row are NULL. If 
87722   ** any are, then the constraint is considered satisfied. No need to 
87723   ** search for a matching row in the parent table.  */
87724   if( nIncr<0 ){
87725     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87726   }
87727   for(i=0; i<pFKey->nCol; i++){
87728     int iReg = aiCol[i] + regData + 1;
87729     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87730   }
87731
87732   if( isIgnore==0 ){
87733     if( pIdx==0 ){
87734       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87735       ** column of the parent table (table pTab).  */
87736       int iMustBeInt;               /* Address of MustBeInt instruction */
87737       int regTemp = sqlite3GetTempReg(pParse);
87738   
87739       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
87740       ** apply the affinity of the parent key). If this fails, then there
87741       ** is no matching parent key. Before using MustBeInt, make a copy of
87742       ** the value. Otherwise, the value inserted into the child key column
87743       ** will have INTEGER affinity applied to it, which may not be correct.  */
87744       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87745       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87746   
87747       /* If the parent table is the same as the child table, and we are about
87748       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87749       ** then check if the row being inserted matches itself. If so, do not
87750       ** increment the constraint-counter.  */
87751       if( pTab==pFKey->pFrom && nIncr==1 ){
87752         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
87753       }
87754   
87755       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
87756       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
87757       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
87758       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
87759       sqlite3VdbeJumpHere(v, iMustBeInt);
87760       sqlite3ReleaseTempReg(pParse, regTemp);
87761     }else{
87762       int nCol = pFKey->nCol;
87763       int regTemp = sqlite3GetTempRange(pParse, nCol);
87764       int regRec = sqlite3GetTempReg(pParse);
87765       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
87766   
87767       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
87768       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
87769       for(i=0; i<nCol; i++){
87770         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
87771       }
87772   
87773       /* If the parent table is the same as the child table, and we are about
87774       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87775       ** then check if the row being inserted matches itself. If so, do not
87776       ** increment the constraint-counter. 
87777       **
87778       ** If any of the parent-key values are NULL, then the row cannot match 
87779       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
87780       ** of the parent-key values are NULL (at this point it is known that
87781       ** none of the child key values are).
87782       */
87783       if( pTab==pFKey->pFrom && nIncr==1 ){
87784         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
87785         for(i=0; i<nCol; i++){
87786           int iChild = aiCol[i]+1+regData;
87787           int iParent = pIdx->aiColumn[i]+1+regData;
87788           assert( aiCol[i]!=pTab->iPKey );
87789           if( pIdx->aiColumn[i]==pTab->iPKey ){
87790             /* The parent key is a composite key that includes the IPK column */
87791             iParent = regData;
87792           }
87793           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
87794           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
87795         }
87796         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
87797       }
87798   
87799       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
87800       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
87801       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
87802   
87803       sqlite3ReleaseTempReg(pParse, regRec);
87804       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
87805     }
87806   }
87807
87808   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
87809     /* Special case: If this is an INSERT statement that will insert exactly
87810     ** one row into the table, raise a constraint immediately instead of
87811     ** incrementing a counter. This is necessary as the VM code is being
87812     ** generated for will not open a statement transaction.  */
87813     assert( nIncr==1 );
87814     sqlite3HaltConstraint(
87815         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
87816     );
87817   }else{
87818     if( nIncr>0 && pFKey->isDeferred==0 ){
87819       sqlite3ParseToplevel(pParse)->mayAbort = 1;
87820     }
87821     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87822   }
87823
87824   sqlite3VdbeResolveLabel(v, iOk);
87825   sqlite3VdbeAddOp1(v, OP_Close, iCur);
87826 }
87827
87828 /*
87829 ** This function is called to generate code executed when a row is deleted
87830 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
87831 ** deferred, when a row is inserted into the same table. When generating
87832 ** code for an SQL UPDATE operation, this function may be called twice -
87833 ** once to "delete" the old row and once to "insert" the new row.
87834 **
87835 ** The code generated by this function scans through the rows in the child
87836 ** table that correspond to the parent table row being deleted or inserted.
87837 ** For each child row found, one of the following actions is taken:
87838 **
87839 **   Operation | FK type   | Action taken
87840 **   --------------------------------------------------------------------------
87841 **   DELETE      immediate   Increment the "immediate constraint counter".
87842 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87843 **                           throw a "foreign key constraint failed" exception.
87844 **
87845 **   INSERT      immediate   Decrement the "immediate constraint counter".
87846 **
87847 **   DELETE      deferred    Increment the "deferred constraint counter".
87848 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
87849 **                           throw a "foreign key constraint failed" exception.
87850 **
87851 **   INSERT      deferred    Decrement the "deferred constraint counter".
87852 **
87853 ** These operations are identified in the comment at the top of this file 
87854 ** (fkey.c) as "I.2" and "D.2".
87855 */
87856 static void fkScanChildren(
87857   Parse *pParse,                  /* Parse context */
87858   SrcList *pSrc,                  /* SrcList containing the table to scan */
87859   Table *pTab,
87860   Index *pIdx,                    /* Foreign key index */
87861   FKey *pFKey,                    /* Foreign key relationship */
87862   int *aiCol,                     /* Map from pIdx cols to child table cols */
87863   int regData,                    /* Referenced table data starts here */
87864   int nIncr                       /* Amount to increment deferred counter by */
87865 ){
87866   sqlite3 *db = pParse->db;       /* Database handle */
87867   int i;                          /* Iterator variable */
87868   Expr *pWhere = 0;               /* WHERE clause to scan with */
87869   NameContext sNameContext;       /* Context used to resolve WHERE clause */
87870   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
87871   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
87872   Vdbe *v = sqlite3GetVdbe(pParse);
87873
87874   assert( !pIdx || pIdx->pTable==pTab );
87875
87876   if( nIncr<0 ){
87877     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
87878   }
87879
87880   /* Create an Expr object representing an SQL expression like:
87881   **
87882   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
87883   **
87884   ** The collation sequence used for the comparison should be that of
87885   ** the parent key columns. The affinity of the parent key column should
87886   ** be applied to each child key value before the comparison takes place.
87887   */
87888   for(i=0; i<pFKey->nCol; i++){
87889     Expr *pLeft;                  /* Value from parent table row */
87890     Expr *pRight;                 /* Column ref to child table */
87891     Expr *pEq;                    /* Expression (pLeft = pRight) */
87892     int iCol;                     /* Index of column in child table */ 
87893     const char *zCol;             /* Name of column in child table */
87894
87895     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
87896     if( pLeft ){
87897       /* Set the collation sequence and affinity of the LHS of each TK_EQ
87898       ** expression to the parent key column defaults.  */
87899       if( pIdx ){
87900         Column *pCol;
87901         const char *zColl;
87902         iCol = pIdx->aiColumn[i];
87903         pCol = &pTab->aCol[iCol];
87904         if( pTab->iPKey==iCol ) iCol = -1;
87905         pLeft->iTable = regData+iCol+1;
87906         pLeft->affinity = pCol->affinity;
87907         zColl = pCol->zColl;
87908         if( zColl==0 ) zColl = db->pDfltColl->zName;
87909         pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
87910       }else{
87911         pLeft->iTable = regData;
87912         pLeft->affinity = SQLITE_AFF_INTEGER;
87913       }
87914     }
87915     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
87916     assert( iCol>=0 );
87917     zCol = pFKey->pFrom->aCol[iCol].zName;
87918     pRight = sqlite3Expr(db, TK_ID, zCol);
87919     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
87920     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87921   }
87922
87923   /* If the child table is the same as the parent table, and this scan
87924   ** is taking place as part of a DELETE operation (operation D.2), omit the
87925   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
87926   ** clause, where $rowid is the rowid of the row being deleted.  */
87927   if( pTab==pFKey->pFrom && nIncr>0 ){
87928     Expr *pEq;                    /* Expression (pLeft = pRight) */
87929     Expr *pLeft;                  /* Value from parent table row */
87930     Expr *pRight;                 /* Column ref to child table */
87931     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
87932     pRight = sqlite3Expr(db, TK_COLUMN, 0);
87933     if( pLeft && pRight ){
87934       pLeft->iTable = regData;
87935       pLeft->affinity = SQLITE_AFF_INTEGER;
87936       pRight->iTable = pSrc->a[0].iCursor;
87937       pRight->iColumn = -1;
87938     }
87939     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
87940     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87941   }
87942
87943   /* Resolve the references in the WHERE clause. */
87944   memset(&sNameContext, 0, sizeof(NameContext));
87945   sNameContext.pSrcList = pSrc;
87946   sNameContext.pParse = pParse;
87947   sqlite3ResolveExprNames(&sNameContext, pWhere);
87948
87949   /* Create VDBE to loop through the entries in pSrc that match the WHERE
87950   ** clause. If the constraint is not deferred, throw an exception for
87951   ** each row found. Otherwise, for deferred constraints, increment the
87952   ** deferred constraint counter by nIncr for each row selected.  */
87953   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
87954   if( nIncr>0 && pFKey->isDeferred==0 ){
87955     sqlite3ParseToplevel(pParse)->mayAbort = 1;
87956   }
87957   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
87958   if( pWInfo ){
87959     sqlite3WhereEnd(pWInfo);
87960   }
87961
87962   /* Clean up the WHERE clause constructed above. */
87963   sqlite3ExprDelete(db, pWhere);
87964   if( iFkIfZero ){
87965     sqlite3VdbeJumpHere(v, iFkIfZero);
87966   }
87967 }
87968
87969 /*
87970 ** This function returns a pointer to the head of a linked list of FK
87971 ** constraints for which table pTab is the parent table. For example,
87972 ** given the following schema:
87973 **
87974 **   CREATE TABLE t1(a PRIMARY KEY);
87975 **   CREATE TABLE t2(b REFERENCES t1(a);
87976 **
87977 ** Calling this function with table "t1" as an argument returns a pointer
87978 ** to the FKey structure representing the foreign key constraint on table
87979 ** "t2". Calling this function with "t2" as the argument would return a
87980 ** NULL pointer (as there are no FK constraints for which t2 is the parent
87981 ** table).
87982 */
87983 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
87984   int nName = sqlite3Strlen30(pTab->zName);
87985   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
87986 }
87987
87988 /*
87989 ** The second argument is a Trigger structure allocated by the 
87990 ** fkActionTrigger() routine. This function deletes the Trigger structure
87991 ** and all of its sub-components.
87992 **
87993 ** The Trigger structure or any of its sub-components may be allocated from
87994 ** the lookaside buffer belonging to database handle dbMem.
87995 */
87996 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
87997   if( p ){
87998     TriggerStep *pStep = p->step_list;
87999     sqlite3ExprDelete(dbMem, pStep->pWhere);
88000     sqlite3ExprListDelete(dbMem, pStep->pExprList);
88001     sqlite3SelectDelete(dbMem, pStep->pSelect);
88002     sqlite3ExprDelete(dbMem, p->pWhen);
88003     sqlite3DbFree(dbMem, p);
88004   }
88005 }
88006
88007 /*
88008 ** This function is called to generate code that runs when table pTab is
88009 ** being dropped from the database. The SrcList passed as the second argument
88010 ** to this function contains a single entry guaranteed to resolve to
88011 ** table pTab.
88012 **
88013 ** Normally, no code is required. However, if either
88014 **
88015 **   (a) The table is the parent table of a FK constraint, or
88016 **   (b) The table is the child table of a deferred FK constraint and it is
88017 **       determined at runtime that there are outstanding deferred FK 
88018 **       constraint violations in the database,
88019 **
88020 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88021 ** the table from the database. Triggers are disabled while running this
88022 ** DELETE, but foreign key actions are not.
88023 */
88024 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88025   sqlite3 *db = pParse->db;
88026   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88027     int iSkip = 0;
88028     Vdbe *v = sqlite3GetVdbe(pParse);
88029
88030     assert( v );                  /* VDBE has already been allocated */
88031     if( sqlite3FkReferences(pTab)==0 ){
88032       /* Search for a deferred foreign key constraint for which this table
88033       ** is the child table. If one cannot be found, return without 
88034       ** generating any VDBE code. If one can be found, then jump over
88035       ** the entire DELETE if there are no outstanding deferred constraints
88036       ** when this statement is run.  */
88037       FKey *p;
88038       for(p=pTab->pFKey; p; p=p->pNextFrom){
88039         if( p->isDeferred ) break;
88040       }
88041       if( !p ) return;
88042       iSkip = sqlite3VdbeMakeLabel(v);
88043       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88044     }
88045
88046     pParse->disableTriggers = 1;
88047     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
88048     pParse->disableTriggers = 0;
88049
88050     /* If the DELETE has generated immediate foreign key constraint 
88051     ** violations, halt the VDBE and return an error at this point, before
88052     ** any modifications to the schema are made. This is because statement
88053     ** transactions are not able to rollback schema changes.  */
88054     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
88055     sqlite3HaltConstraint(
88056         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88057     );
88058
88059     if( iSkip ){
88060       sqlite3VdbeResolveLabel(v, iSkip);
88061     }
88062   }
88063 }
88064
88065 /*
88066 ** This function is called when inserting, deleting or updating a row of
88067 ** table pTab to generate VDBE code to perform foreign key constraint 
88068 ** processing for the operation.
88069 **
88070 ** For a DELETE operation, parameter regOld is passed the index of the
88071 ** first register in an array of (pTab->nCol+1) registers containing the
88072 ** rowid of the row being deleted, followed by each of the column values
88073 ** of the row being deleted, from left to right. Parameter regNew is passed
88074 ** zero in this case.
88075 **
88076 ** For an INSERT operation, regOld is passed zero and regNew is passed the
88077 ** first register of an array of (pTab->nCol+1) registers containing the new
88078 ** row data.
88079 **
88080 ** For an UPDATE operation, this function is called twice. Once before
88081 ** the original record is deleted from the table using the calling convention
88082 ** described for DELETE. Then again after the original record is deleted
88083 ** but before the new record is inserted using the INSERT convention. 
88084 */
88085 SQLITE_PRIVATE void sqlite3FkCheck(
88086   Parse *pParse,                  /* Parse context */
88087   Table *pTab,                    /* Row is being deleted from this table */ 
88088   int regOld,                     /* Previous row data is stored here */
88089   int regNew                      /* New row data is stored here */
88090 ){
88091   sqlite3 *db = pParse->db;       /* Database handle */
88092   FKey *pFKey;                    /* Used to iterate through FKs */
88093   int iDb;                        /* Index of database containing pTab */
88094   const char *zDb;                /* Name of database containing pTab */
88095   int isIgnoreErrors = pParse->disableTriggers;
88096
88097   /* Exactly one of regOld and regNew should be non-zero. */
88098   assert( (regOld==0)!=(regNew==0) );
88099
88100   /* If foreign-keys are disabled, this function is a no-op. */
88101   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
88102
88103   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88104   zDb = db->aDb[iDb].zName;
88105
88106   /* Loop through all the foreign key constraints for which pTab is the
88107   ** child table (the table that the foreign key definition is part of).  */
88108   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88109     Table *pTo;                   /* Parent table of foreign key pFKey */
88110     Index *pIdx = 0;              /* Index on key columns in pTo */
88111     int *aiFree = 0;
88112     int *aiCol;
88113     int iCol;
88114     int i;
88115     int isIgnore = 0;
88116
88117     /* Find the parent table of this foreign key. Also find a unique index 
88118     ** on the parent key columns in the parent table. If either of these 
88119     ** schema items cannot be located, set an error in pParse and return 
88120     ** early.  */
88121     if( pParse->disableTriggers ){
88122       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
88123     }else{
88124       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
88125     }
88126     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88127       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88128       if( !isIgnoreErrors || db->mallocFailed ) return;
88129       if( pTo==0 ){
88130         /* If isIgnoreErrors is true, then a table is being dropped. In this
88131         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88132         ** before actually dropping it in order to check FK constraints.
88133         ** If the parent table of an FK constraint on the current table is
88134         ** missing, behave as if it is empty. i.e. decrement the relevant
88135         ** FK counter for each row of the current table with non-NULL keys.
88136         */
88137         Vdbe *v = sqlite3GetVdbe(pParse);
88138         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88139         for(i=0; i<pFKey->nCol; i++){
88140           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88141           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88142         }
88143         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88144       }
88145       continue;
88146     }
88147     assert( pFKey->nCol==1 || (aiFree && pIdx) );
88148
88149     if( aiFree ){
88150       aiCol = aiFree;
88151     }else{
88152       iCol = pFKey->aCol[0].iFrom;
88153       aiCol = &iCol;
88154     }
88155     for(i=0; i<pFKey->nCol; i++){
88156       if( aiCol[i]==pTab->iPKey ){
88157         aiCol[i] = -1;
88158       }
88159 #ifndef SQLITE_OMIT_AUTHORIZATION
88160       /* Request permission to read the parent key columns. If the 
88161       ** authorization callback returns SQLITE_IGNORE, behave as if any
88162       ** values read from the parent table are NULL. */
88163       if( db->xAuth ){
88164         int rcauth;
88165         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88166         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88167         isIgnore = (rcauth==SQLITE_IGNORE);
88168       }
88169 #endif
88170     }
88171
88172     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
88173     ** a cursor to use to search the unique index on the parent key columns 
88174     ** in the parent table.  */
88175     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88176     pParse->nTab++;
88177
88178     if( regOld!=0 ){
88179       /* A row is being removed from the child table. Search for the parent.
88180       ** If the parent does not exist, removing the child row resolves an 
88181       ** outstanding foreign key constraint violation. */
88182       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88183     }
88184     if( regNew!=0 ){
88185       /* A row is being added to the child table. If a parent row cannot
88186       ** be found, adding the child row has violated the FK constraint. */ 
88187       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88188     }
88189
88190     sqlite3DbFree(db, aiFree);
88191   }
88192
88193   /* Loop through all the foreign key constraints that refer to this table */
88194   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88195     Index *pIdx = 0;              /* Foreign key index for pFKey */
88196     SrcList *pSrc;
88197     int *aiCol = 0;
88198
88199     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88200       assert( regOld==0 && regNew!=0 );
88201       /* Inserting a single row into a parent table cannot cause an immediate
88202       ** foreign key violation. So do nothing in this case.  */
88203       continue;
88204     }
88205
88206     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88207       if( !isIgnoreErrors || db->mallocFailed ) return;
88208       continue;
88209     }
88210     assert( aiCol || pFKey->nCol==1 );
88211
88212     /* Create a SrcList structure containing a single table (the table 
88213     ** the foreign key that refers to this table is attached to). This
88214     ** is required for the sqlite3WhereXXX() interface.  */
88215     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88216     if( pSrc ){
88217       struct SrcList_item *pItem = pSrc->a;
88218       pItem->pTab = pFKey->pFrom;
88219       pItem->zName = pFKey->pFrom->zName;
88220       pItem->pTab->nRef++;
88221       pItem->iCursor = pParse->nTab++;
88222   
88223       if( regNew!=0 ){
88224         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88225       }
88226       if( regOld!=0 ){
88227         /* If there is a RESTRICT action configured for the current operation
88228         ** on the parent table of this FK, then throw an exception 
88229         ** immediately if the FK constraint is violated, even if this is a
88230         ** deferred trigger. That's what RESTRICT means. To defer checking
88231         ** the constraint, the FK should specify NO ACTION (represented
88232         ** using OE_None). NO ACTION is the default.  */
88233         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88234       }
88235       pItem->zName = 0;
88236       sqlite3SrcListDelete(db, pSrc);
88237     }
88238     sqlite3DbFree(db, aiCol);
88239   }
88240 }
88241
88242 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88243
88244 /*
88245 ** This function is called before generating code to update or delete a 
88246 ** row contained in table pTab.
88247 */
88248 SQLITE_PRIVATE u32 sqlite3FkOldmask(
88249   Parse *pParse,                  /* Parse context */
88250   Table *pTab                     /* Table being modified */
88251 ){
88252   u32 mask = 0;
88253   if( pParse->db->flags&SQLITE_ForeignKeys ){
88254     FKey *p;
88255     int i;
88256     for(p=pTab->pFKey; p; p=p->pNextFrom){
88257       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88258     }
88259     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88260       Index *pIdx = 0;
88261       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
88262       if( pIdx ){
88263         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88264       }
88265     }
88266   }
88267   return mask;
88268 }
88269
88270 /*
88271 ** This function is called before generating code to update or delete a 
88272 ** row contained in table pTab. If the operation is a DELETE, then
88273 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88274 ** to an array of size N, where N is the number of columns in table pTab.
88275 ** If the i'th column is not modified by the UPDATE, then the corresponding 
88276 ** entry in the aChange[] array is set to -1. If the column is modified,
88277 ** the value is 0 or greater. Parameter chngRowid is set to true if the
88278 ** UPDATE statement modifies the rowid fields of the table.
88279 **
88280 ** If any foreign key processing will be required, this function returns
88281 ** true. If there is no foreign key related processing, this function 
88282 ** returns false.
88283 */
88284 SQLITE_PRIVATE int sqlite3FkRequired(
88285   Parse *pParse,                  /* Parse context */
88286   Table *pTab,                    /* Table being modified */
88287   int *aChange,                   /* Non-NULL for UPDATE operations */
88288   int chngRowid                   /* True for UPDATE that affects rowid */
88289 ){
88290   if( pParse->db->flags&SQLITE_ForeignKeys ){
88291     if( !aChange ){
88292       /* A DELETE operation. Foreign key processing is required if the 
88293       ** table in question is either the child or parent table for any 
88294       ** foreign key constraint.  */
88295       return (sqlite3FkReferences(pTab) || pTab->pFKey);
88296     }else{
88297       /* This is an UPDATE. Foreign key processing is only required if the
88298       ** operation modifies one or more child or parent key columns. */
88299       int i;
88300       FKey *p;
88301
88302       /* Check if any child key columns are being modified. */
88303       for(p=pTab->pFKey; p; p=p->pNextFrom){
88304         for(i=0; i<p->nCol; i++){
88305           int iChildKey = p->aCol[i].iFrom;
88306           if( aChange[iChildKey]>=0 ) return 1;
88307           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88308         }
88309       }
88310
88311       /* Check if any parent key columns are being modified. */
88312       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88313         for(i=0; i<p->nCol; i++){
88314           char *zKey = p->aCol[i].zCol;
88315           int iKey;
88316           for(iKey=0; iKey<pTab->nCol; iKey++){
88317             Column *pCol = &pTab->aCol[iKey];
88318             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
88319                       : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
88320               if( aChange[iKey]>=0 ) return 1;
88321               if( iKey==pTab->iPKey && chngRowid ) return 1;
88322             }
88323           }
88324         }
88325       }
88326     }
88327   }
88328   return 0;
88329 }
88330
88331 /*
88332 ** This function is called when an UPDATE or DELETE operation is being 
88333 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
88334 ** If the current operation is an UPDATE, then the pChanges parameter is
88335 ** passed a pointer to the list of columns being modified. If it is a
88336 ** DELETE, pChanges is passed a NULL pointer.
88337 **
88338 ** It returns a pointer to a Trigger structure containing a trigger
88339 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88340 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88341 ** returned (these actions require no special handling by the triggers
88342 ** sub-system, code for them is created by fkScanChildren()).
88343 **
88344 ** For example, if pFKey is the foreign key and pTab is table "p" in 
88345 ** the following schema:
88346 **
88347 **   CREATE TABLE p(pk PRIMARY KEY);
88348 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88349 **
88350 ** then the returned trigger structure is equivalent to:
88351 **
88352 **   CREATE TRIGGER ... DELETE ON p BEGIN
88353 **     DELETE FROM c WHERE ck = old.pk;
88354 **   END;
88355 **
88356 ** The returned pointer is cached as part of the foreign key object. It
88357 ** is eventually freed along with the rest of the foreign key object by 
88358 ** sqlite3FkDelete().
88359 */
88360 static Trigger *fkActionTrigger(
88361   Parse *pParse,                  /* Parse context */
88362   Table *pTab,                    /* Table being updated or deleted from */
88363   FKey *pFKey,                    /* Foreign key to get action for */
88364   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88365 ){
88366   sqlite3 *db = pParse->db;       /* Database handle */
88367   int action;                     /* One of OE_None, OE_Cascade etc. */
88368   Trigger *pTrigger;              /* Trigger definition to return */
88369   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88370
88371   action = pFKey->aAction[iAction];
88372   pTrigger = pFKey->apTrigger[iAction];
88373
88374   if( action!=OE_None && !pTrigger ){
88375     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88376     char const *zFrom;            /* Name of child table */
88377     int nFrom;                    /* Length in bytes of zFrom */
88378     Index *pIdx = 0;              /* Parent key index for this FK */
88379     int *aiCol = 0;               /* child table cols -> parent key cols */
88380     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88381     Expr *pWhere = 0;             /* WHERE clause of trigger step */
88382     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88383     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88384     int i;                        /* Iterator variable */
88385     Expr *pWhen = 0;              /* WHEN clause for the trigger */
88386
88387     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88388     assert( aiCol || pFKey->nCol==1 );
88389
88390     for(i=0; i<pFKey->nCol; i++){
88391       Token tOld = { "old", 3 };  /* Literal "old" token */
88392       Token tNew = { "new", 3 };  /* Literal "new" token */
88393       Token tFromCol;             /* Name of column in child table */
88394       Token tToCol;               /* Name of column in parent table */
88395       int iFromCol;               /* Idx of column in child table */
88396       Expr *pEq;                  /* tFromCol = OLD.tToCol */
88397
88398       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88399       assert( iFromCol>=0 );
88400       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88401       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88402
88403       tToCol.n = sqlite3Strlen30(tToCol.z);
88404       tFromCol.n = sqlite3Strlen30(tFromCol.z);
88405
88406       /* Create the expression "OLD.zToCol = zFromCol". It is important
88407       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88408       ** that the affinity and collation sequence associated with the
88409       ** parent table are used for the comparison. */
88410       pEq = sqlite3PExpr(pParse, TK_EQ,
88411           sqlite3PExpr(pParse, TK_DOT, 
88412             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88413             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88414           , 0),
88415           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88416       , 0);
88417       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88418
88419       /* For ON UPDATE, construct the next term of the WHEN clause.
88420       ** The final WHEN clause will be like this:
88421       **
88422       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88423       */
88424       if( pChanges ){
88425         pEq = sqlite3PExpr(pParse, TK_IS,
88426             sqlite3PExpr(pParse, TK_DOT, 
88427               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88428               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88429               0),
88430             sqlite3PExpr(pParse, TK_DOT, 
88431               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88432               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88433               0),
88434             0);
88435         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
88436       }
88437   
88438       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88439         Expr *pNew;
88440         if( action==OE_Cascade ){
88441           pNew = sqlite3PExpr(pParse, TK_DOT, 
88442             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88443             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88444           , 0);
88445         }else if( action==OE_SetDflt ){
88446           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88447           if( pDflt ){
88448             pNew = sqlite3ExprDup(db, pDflt, 0);
88449           }else{
88450             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88451           }
88452         }else{
88453           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88454         }
88455         pList = sqlite3ExprListAppend(pParse, pList, pNew);
88456         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
88457       }
88458     }
88459     sqlite3DbFree(db, aiCol);
88460
88461     zFrom = pFKey->pFrom->zName;
88462     nFrom = sqlite3Strlen30(zFrom);
88463
88464     if( action==OE_Restrict ){
88465       Token tFrom;
88466       Expr *pRaise; 
88467
88468       tFrom.z = zFrom;
88469       tFrom.n = nFrom;
88470       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
88471       if( pRaise ){
88472         pRaise->affinity = OE_Abort;
88473       }
88474       pSelect = sqlite3SelectNew(pParse, 
88475           sqlite3ExprListAppend(pParse, 0, pRaise),
88476           sqlite3SrcListAppend(db, 0, &tFrom, 0),
88477           pWhere,
88478           0, 0, 0, 0, 0, 0
88479       );
88480       pWhere = 0;
88481     }
88482
88483     /* Disable lookaside memory allocation */
88484     enableLookaside = db->lookaside.bEnabled;
88485     db->lookaside.bEnabled = 0;
88486
88487     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
88488         sizeof(Trigger) +         /* struct Trigger */
88489         sizeof(TriggerStep) +     /* Single step in trigger program */
88490         nFrom + 1                 /* Space for pStep->target.z */
88491     );
88492     if( pTrigger ){
88493       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88494       pStep->target.z = (char *)&pStep[1];
88495       pStep->target.n = nFrom;
88496       memcpy((char *)pStep->target.z, zFrom, nFrom);
88497   
88498       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88499       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
88500       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88501       if( pWhen ){
88502         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88503         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88504       }
88505     }
88506
88507     /* Re-enable the lookaside buffer, if it was disabled earlier. */
88508     db->lookaside.bEnabled = enableLookaside;
88509
88510     sqlite3ExprDelete(db, pWhere);
88511     sqlite3ExprDelete(db, pWhen);
88512     sqlite3ExprListDelete(db, pList);
88513     sqlite3SelectDelete(db, pSelect);
88514     if( db->mallocFailed==1 ){
88515       fkTriggerDelete(db, pTrigger);
88516       return 0;
88517     }
88518     assert( pStep!=0 );
88519
88520     switch( action ){
88521       case OE_Restrict:
88522         pStep->op = TK_SELECT; 
88523         break;
88524       case OE_Cascade: 
88525         if( !pChanges ){ 
88526           pStep->op = TK_DELETE; 
88527           break; 
88528         }
88529       default:
88530         pStep->op = TK_UPDATE;
88531     }
88532     pStep->pTrig = pTrigger;
88533     pTrigger->pSchema = pTab->pSchema;
88534     pTrigger->pTabSchema = pTab->pSchema;
88535     pFKey->apTrigger[iAction] = pTrigger;
88536     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88537   }
88538
88539   return pTrigger;
88540 }
88541
88542 /*
88543 ** This function is called when deleting or updating a row to implement
88544 ** any required CASCADE, SET NULL or SET DEFAULT actions.
88545 */
88546 SQLITE_PRIVATE void sqlite3FkActions(
88547   Parse *pParse,                  /* Parse context */
88548   Table *pTab,                    /* Table being updated or deleted from */
88549   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88550   int regOld                      /* Address of array containing old row */
88551 ){
88552   /* If foreign-key support is enabled, iterate through all FKs that 
88553   ** refer to table pTab. If there is an action associated with the FK 
88554   ** for this operation (either update or delete), invoke the associated 
88555   ** trigger sub-program.  */
88556   if( pParse->db->flags&SQLITE_ForeignKeys ){
88557     FKey *pFKey;                  /* Iterator variable */
88558     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88559       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88560       if( pAction ){
88561         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88562       }
88563     }
88564   }
88565 }
88566
88567 #endif /* ifndef SQLITE_OMIT_TRIGGER */
88568
88569 /*
88570 ** Free all memory associated with foreign key definitions attached to
88571 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88572 ** hash table.
88573 */
88574 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
88575   FKey *pFKey;                    /* Iterator variable */
88576   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88577
88578   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
88579   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88580
88581     /* Remove the FK from the fkeyHash hash table. */
88582     if( !db || db->pnBytesFreed==0 ){
88583       if( pFKey->pPrevTo ){
88584         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88585       }else{
88586         void *p = (void *)pFKey->pNextTo;
88587         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88588         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
88589       }
88590       if( pFKey->pNextTo ){
88591         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88592       }
88593     }
88594
88595     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88596     ** classified as either immediate or deferred.
88597     */
88598     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88599
88600     /* Delete any triggers created to implement actions for this FK. */
88601 #ifndef SQLITE_OMIT_TRIGGER
88602     fkTriggerDelete(db, pFKey->apTrigger[0]);
88603     fkTriggerDelete(db, pFKey->apTrigger[1]);
88604 #endif
88605
88606     pNext = pFKey->pNextFrom;
88607     sqlite3DbFree(db, pFKey);
88608   }
88609 }
88610 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
88611
88612 /************** End of fkey.c ************************************************/
88613 /************** Begin file insert.c ******************************************/
88614 /*
88615 ** 2001 September 15
88616 **
88617 ** The author disclaims copyright to this source code.  In place of
88618 ** a legal notice, here is a blessing:
88619 **
88620 **    May you do good and not evil.
88621 **    May you find forgiveness for yourself and forgive others.
88622 **    May you share freely, never taking more than you give.
88623 **
88624 *************************************************************************
88625 ** This file contains C code routines that are called by the parser
88626 ** to handle INSERT statements in SQLite.
88627 */
88628
88629 /*
88630 ** Generate code that will open a table for reading.
88631 */
88632 SQLITE_PRIVATE void sqlite3OpenTable(
88633   Parse *p,       /* Generate code into this VDBE */
88634   int iCur,       /* The cursor number of the table */
88635   int iDb,        /* The database index in sqlite3.aDb[] */
88636   Table *pTab,    /* The table to be opened */
88637   int opcode      /* OP_OpenRead or OP_OpenWrite */
88638 ){
88639   Vdbe *v;
88640   assert( !IsVirtual(pTab) );
88641   v = sqlite3GetVdbe(p);
88642   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88643   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88644   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88645   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
88646   VdbeComment((v, "%s", pTab->zName));
88647 }
88648
88649 /*
88650 ** Return a pointer to the column affinity string associated with index
88651 ** pIdx. A column affinity string has one character for each column in 
88652 ** the table, according to the affinity of the column:
88653 **
88654 **  Character      Column affinity
88655 **  ------------------------------
88656 **  'a'            TEXT
88657 **  'b'            NONE
88658 **  'c'            NUMERIC
88659 **  'd'            INTEGER
88660 **  'e'            REAL
88661 **
88662 ** An extra 'd' is appended to the end of the string to cover the
88663 ** rowid that appears as the last column in every index.
88664 **
88665 ** Memory for the buffer containing the column index affinity string
88666 ** is managed along with the rest of the Index structure. It will be
88667 ** released when sqlite3DeleteIndex() is called.
88668 */
88669 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
88670   if( !pIdx->zColAff ){
88671     /* The first time a column affinity string for a particular index is
88672     ** required, it is allocated and populated here. It is then stored as
88673     ** a member of the Index structure for subsequent use.
88674     **
88675     ** The column affinity string will eventually be deleted by
88676     ** sqliteDeleteIndex() when the Index structure itself is cleaned
88677     ** up.
88678     */
88679     int n;
88680     Table *pTab = pIdx->pTable;
88681     sqlite3 *db = sqlite3VdbeDb(v);
88682     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
88683     if( !pIdx->zColAff ){
88684       db->mallocFailed = 1;
88685       return 0;
88686     }
88687     for(n=0; n<pIdx->nColumn; n++){
88688       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88689     }
88690     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
88691     pIdx->zColAff[n] = 0;
88692   }
88693  
88694   return pIdx->zColAff;
88695 }
88696
88697 /*
88698 ** Set P4 of the most recently inserted opcode to a column affinity
88699 ** string for table pTab. A column affinity string has one character
88700 ** for each column indexed by the index, according to the affinity of the
88701 ** column:
88702 **
88703 **  Character      Column affinity
88704 **  ------------------------------
88705 **  'a'            TEXT
88706 **  'b'            NONE
88707 **  'c'            NUMERIC
88708 **  'd'            INTEGER
88709 **  'e'            REAL
88710 */
88711 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
88712   /* The first time a column affinity string for a particular table
88713   ** is required, it is allocated and populated here. It is then 
88714   ** stored as a member of the Table structure for subsequent use.
88715   **
88716   ** The column affinity string will eventually be deleted by
88717   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
88718   */
88719   if( !pTab->zColAff ){
88720     char *zColAff;
88721     int i;
88722     sqlite3 *db = sqlite3VdbeDb(v);
88723
88724     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
88725     if( !zColAff ){
88726       db->mallocFailed = 1;
88727       return;
88728     }
88729
88730     for(i=0; i<pTab->nCol; i++){
88731       zColAff[i] = pTab->aCol[i].affinity;
88732     }
88733     zColAff[pTab->nCol] = '\0';
88734
88735     pTab->zColAff = zColAff;
88736   }
88737
88738   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88739 }
88740
88741 /*
88742 ** Return non-zero if the table pTab in database iDb or any of its indices
88743 ** have been opened at any point in the VDBE program beginning at location
88744 ** iStartAddr throught the end of the program.  This is used to see if 
88745 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
88746 ** run without using temporary table for the results of the SELECT. 
88747 */
88748 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
88749   Vdbe *v = sqlite3GetVdbe(p);
88750   int i;
88751   int iEnd = sqlite3VdbeCurrentAddr(v);
88752 #ifndef SQLITE_OMIT_VIRTUALTABLE
88753   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
88754 #endif
88755
88756   for(i=iStartAddr; i<iEnd; i++){
88757     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
88758     assert( pOp!=0 );
88759     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
88760       Index *pIndex;
88761       int tnum = pOp->p2;
88762       if( tnum==pTab->tnum ){
88763         return 1;
88764       }
88765       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
88766         if( tnum==pIndex->tnum ){
88767           return 1;
88768         }
88769       }
88770     }
88771 #ifndef SQLITE_OMIT_VIRTUALTABLE
88772     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
88773       assert( pOp->p4.pVtab!=0 );
88774       assert( pOp->p4type==P4_VTAB );
88775       return 1;
88776     }
88777 #endif
88778   }
88779   return 0;
88780 }
88781
88782 #ifndef SQLITE_OMIT_AUTOINCREMENT
88783 /*
88784 ** Locate or create an AutoincInfo structure associated with table pTab
88785 ** which is in database iDb.  Return the register number for the register
88786 ** that holds the maximum rowid.
88787 **
88788 ** There is at most one AutoincInfo structure per table even if the
88789 ** same table is autoincremented multiple times due to inserts within
88790 ** triggers.  A new AutoincInfo structure is created if this is the
88791 ** first use of table pTab.  On 2nd and subsequent uses, the original
88792 ** AutoincInfo structure is used.
88793 **
88794 ** Three memory locations are allocated:
88795 **
88796 **   (1)  Register to hold the name of the pTab table.
88797 **   (2)  Register to hold the maximum ROWID of pTab.
88798 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
88799 **
88800 ** The 2nd register is the one that is returned.  That is all the
88801 ** insert routine needs to know about.
88802 */
88803 static int autoIncBegin(
88804   Parse *pParse,      /* Parsing context */
88805   int iDb,            /* Index of the database holding pTab */
88806   Table *pTab         /* The table we are writing to */
88807 ){
88808   int memId = 0;      /* Register holding maximum rowid */
88809   if( pTab->tabFlags & TF_Autoincrement ){
88810     Parse *pToplevel = sqlite3ParseToplevel(pParse);
88811     AutoincInfo *pInfo;
88812
88813     pInfo = pToplevel->pAinc;
88814     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
88815     if( pInfo==0 ){
88816       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
88817       if( pInfo==0 ) return 0;
88818       pInfo->pNext = pToplevel->pAinc;
88819       pToplevel->pAinc = pInfo;
88820       pInfo->pTab = pTab;
88821       pInfo->iDb = iDb;
88822       pToplevel->nMem++;                  /* Register to hold name of table */
88823       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
88824       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
88825     }
88826     memId = pInfo->regCtr;
88827   }
88828   return memId;
88829 }
88830
88831 /*
88832 ** This routine generates code that will initialize all of the
88833 ** register used by the autoincrement tracker.  
88834 */
88835 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
88836   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
88837   sqlite3 *db = pParse->db;  /* The database connection */
88838   Db *pDb;                   /* Database only autoinc table */
88839   int memId;                 /* Register holding max rowid */
88840   int addr;                  /* A VDBE address */
88841   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
88842
88843   /* This routine is never called during trigger-generation.  It is
88844   ** only called from the top-level */
88845   assert( pParse->pTriggerTab==0 );
88846   assert( pParse==sqlite3ParseToplevel(pParse) );
88847
88848   assert( v );   /* We failed long ago if this is not so */
88849   for(p = pParse->pAinc; p; p = p->pNext){
88850     pDb = &db->aDb[p->iDb];
88851     memId = p->regCtr;
88852     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
88853     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
88854     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
88855     addr = sqlite3VdbeCurrentAddr(v);
88856     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
88857     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
88858     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
88859     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
88860     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88861     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88862     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
88863     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
88864     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
88865     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
88866     sqlite3VdbeAddOp0(v, OP_Close);
88867   }
88868 }
88869
88870 /*
88871 ** Update the maximum rowid for an autoincrement calculation.
88872 **
88873 ** This routine should be called when the top of the stack holds a
88874 ** new rowid that is about to be inserted.  If that new rowid is
88875 ** larger than the maximum rowid in the memId memory cell, then the
88876 ** memory cell is updated.  The stack is unchanged.
88877 */
88878 static void autoIncStep(Parse *pParse, int memId, int regRowid){
88879   if( memId>0 ){
88880     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
88881   }
88882 }
88883
88884 /*
88885 ** This routine generates the code needed to write autoincrement
88886 ** maximum rowid values back into the sqlite_sequence register.
88887 ** Every statement that might do an INSERT into an autoincrement
88888 ** table (either directly or through triggers) needs to call this
88889 ** routine just before the "exit" code.
88890 */
88891 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
88892   AutoincInfo *p;
88893   Vdbe *v = pParse->pVdbe;
88894   sqlite3 *db = pParse->db;
88895
88896   assert( v );
88897   for(p = pParse->pAinc; p; p = p->pNext){
88898     Db *pDb = &db->aDb[p->iDb];
88899     int j1, j2, j3, j4, j5;
88900     int iRec;
88901     int memId = p->regCtr;
88902
88903     iRec = sqlite3GetTempReg(pParse);
88904     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
88905     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
88906     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
88907     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
88908     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
88909     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
88910     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
88911     sqlite3VdbeJumpHere(v, j2);
88912     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
88913     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
88914     sqlite3VdbeJumpHere(v, j4);
88915     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
88916     sqlite3VdbeJumpHere(v, j1);
88917     sqlite3VdbeJumpHere(v, j5);
88918     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
88919     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
88920     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88921     sqlite3VdbeAddOp0(v, OP_Close);
88922     sqlite3ReleaseTempReg(pParse, iRec);
88923   }
88924 }
88925 #else
88926 /*
88927 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
88928 ** above are all no-ops
88929 */
88930 # define autoIncBegin(A,B,C) (0)
88931 # define autoIncStep(A,B,C)
88932 #endif /* SQLITE_OMIT_AUTOINCREMENT */
88933
88934
88935 /*
88936 ** Generate code for a co-routine that will evaluate a subquery one
88937 ** row at a time.
88938 **
88939 ** The pSelect parameter is the subquery that the co-routine will evaluation.
88940 ** Information about the location of co-routine and the registers it will use
88941 ** is returned by filling in the pDest object.
88942 **
88943 ** Registers are allocated as follows:
88944 **
88945 **   pDest->iSDParm      The register holding the next entry-point of the
88946 **                       co-routine.  Run the co-routine to its next breakpoint
88947 **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
88948 **
88949 **   pDest->iSDParm+1    The register holding the "completed" flag for the
88950 **                       co-routine. This register is 0 if the previous Yield
88951 **                       generated a new result row, or 1 if the subquery
88952 **                       has completed.  If the Yield is called again
88953 **                       after this register becomes 1, then the VDBE will
88954 **                       halt with an SQLITE_INTERNAL error.
88955 **
88956 **   pDest->iSdst        First result register.
88957 **
88958 **   pDest->nSdst        Number of result registers.
88959 **
88960 ** This routine handles all of the register allocation and fills in the
88961 ** pDest structure appropriately.
88962 **
88963 ** Here is a schematic of the generated code assuming that X is the 
88964 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
88965 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
88966 ** registers that hold the result set, reg[pDest->iSdst] through
88967 ** reg[pDest->iSdst+pDest->nSdst-1]:
88968 **
88969 **         X <- A
88970 **         EOF <- 0
88971 **         goto B
88972 **      A: setup for the SELECT
88973 **         loop rows in the SELECT
88974 **           load results into registers R..S
88975 **           yield X
88976 **         end loop
88977 **         cleanup after the SELECT
88978 **         EOF <- 1
88979 **         yield X
88980 **         halt-error
88981 **      B:
88982 **
88983 ** To use this subroutine, the caller generates code as follows:
88984 **
88985 **         [ Co-routine generated by this subroutine, shown above ]
88986 **      S: yield X
88987 **         if EOF goto E
88988 **         if skip this row, goto C
88989 **         if terminate loop, goto E
88990 **         deal with this row
88991 **      C: goto S
88992 **      E:
88993 */
88994 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
88995   int regYield;       /* Register holding co-routine entry-point */
88996   int regEof;         /* Register holding co-routine completion flag */
88997   int addrTop;        /* Top of the co-routine */
88998   int j1;             /* Jump instruction */
88999   int rc;             /* Result code */
89000   Vdbe *v;            /* VDBE under construction */
89001
89002   regYield = ++pParse->nMem;
89003   regEof = ++pParse->nMem;
89004   v = sqlite3GetVdbe(pParse);
89005   addrTop = sqlite3VdbeCurrentAddr(v);
89006   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
89007   VdbeComment((v, "Co-routine entry point"));
89008   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
89009   VdbeComment((v, "Co-routine completion flag"));
89010   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
89011   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89012   rc = sqlite3Select(pParse, pSelect, pDest);
89013   assert( pParse->nErr==0 || rc );
89014   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
89015   if( rc ) return rc;
89016   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
89017   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
89018   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
89019   VdbeComment((v, "End of coroutine"));
89020   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
89021   return rc;
89022 }
89023
89024
89025
89026 /* Forward declaration */
89027 static int xferOptimization(
89028   Parse *pParse,        /* Parser context */
89029   Table *pDest,         /* The table we are inserting into */
89030   Select *pSelect,      /* A SELECT statement to use as the data source */
89031   int onError,          /* How to handle constraint errors */
89032   int iDbDest           /* The database of pDest */
89033 );
89034
89035 /*
89036 ** This routine is call to handle SQL of the following forms:
89037 **
89038 **    insert into TABLE (IDLIST) values(EXPRLIST)
89039 **    insert into TABLE (IDLIST) select
89040 **
89041 ** The IDLIST following the table name is always optional.  If omitted,
89042 ** then a list of all columns for the table is substituted.  The IDLIST
89043 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
89044 **
89045 ** The pList parameter holds EXPRLIST in the first form of the INSERT
89046 ** statement above, and pSelect is NULL.  For the second form, pList is
89047 ** NULL and pSelect is a pointer to the select statement used to generate
89048 ** data for the insert.
89049 **
89050 ** The code generated follows one of four templates.  For a simple
89051 ** select with data coming from a VALUES clause, the code executes
89052 ** once straight down through.  Pseudo-code follows (we call this
89053 ** the "1st template"):
89054 **
89055 **         open write cursor to <table> and its indices
89056 **         puts VALUES clause expressions onto the stack
89057 **         write the resulting record into <table>
89058 **         cleanup
89059 **
89060 ** The three remaining templates assume the statement is of the form
89061 **
89062 **   INSERT INTO <table> SELECT ...
89063 **
89064 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89065 ** in other words if the SELECT pulls all columns from a single table
89066 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89067 ** if <table2> and <table1> are distinct tables but have identical
89068 ** schemas, including all the same indices, then a special optimization
89069 ** is invoked that copies raw records from <table2> over to <table1>.
89070 ** See the xferOptimization() function for the implementation of this
89071 ** template.  This is the 2nd template.
89072 **
89073 **         open a write cursor to <table>
89074 **         open read cursor on <table2>
89075 **         transfer all records in <table2> over to <table>
89076 **         close cursors
89077 **         foreach index on <table>
89078 **           open a write cursor on the <table> index
89079 **           open a read cursor on the corresponding <table2> index
89080 **           transfer all records from the read to the write cursors
89081 **           close cursors
89082 **         end foreach
89083 **
89084 ** The 3rd template is for when the second template does not apply
89085 ** and the SELECT clause does not read from <table> at any time.
89086 ** The generated code follows this template:
89087 **
89088 **         EOF <- 0
89089 **         X <- A
89090 **         goto B
89091 **      A: setup for the SELECT
89092 **         loop over the rows in the SELECT
89093 **           load values into registers R..R+n
89094 **           yield X
89095 **         end loop
89096 **         cleanup after the SELECT
89097 **         EOF <- 1
89098 **         yield X
89099 **         goto A
89100 **      B: open write cursor to <table> and its indices
89101 **      C: yield X
89102 **         if EOF goto D
89103 **         insert the select result into <table> from R..R+n
89104 **         goto C
89105 **      D: cleanup
89106 **
89107 ** The 4th template is used if the insert statement takes its
89108 ** values from a SELECT but the data is being inserted into a table
89109 ** that is also read as part of the SELECT.  In the third form,
89110 ** we have to use a intermediate table to store the results of
89111 ** the select.  The template is like this:
89112 **
89113 **         EOF <- 0
89114 **         X <- A
89115 **         goto B
89116 **      A: setup for the SELECT
89117 **         loop over the tables in the SELECT
89118 **           load value into register R..R+n
89119 **           yield X
89120 **         end loop
89121 **         cleanup after the SELECT
89122 **         EOF <- 1
89123 **         yield X
89124 **         halt-error
89125 **      B: open temp table
89126 **      L: yield X
89127 **         if EOF goto M
89128 **         insert row from R..R+n into temp table
89129 **         goto L
89130 **      M: open write cursor to <table> and its indices
89131 **         rewind temp table
89132 **      C: loop over rows of intermediate table
89133 **           transfer values form intermediate table into <table>
89134 **         end loop
89135 **      D: cleanup
89136 */
89137 SQLITE_PRIVATE void sqlite3Insert(
89138   Parse *pParse,        /* Parser context */
89139   SrcList *pTabList,    /* Name of table into which we are inserting */
89140   ExprList *pList,      /* List of values to be inserted */
89141   Select *pSelect,      /* A SELECT statement to use as the data source */
89142   IdList *pColumn,      /* Column names corresponding to IDLIST. */
89143   int onError           /* How to handle constraint errors */
89144 ){
89145   sqlite3 *db;          /* The main database structure */
89146   Table *pTab;          /* The table to insert into.  aka TABLE */
89147   char *zTab;           /* Name of the table into which we are inserting */
89148   const char *zDb;      /* Name of the database holding this table */
89149   int i, j, idx;        /* Loop counters */
89150   Vdbe *v;              /* Generate code into this virtual machine */
89151   Index *pIdx;          /* For looping over indices of the table */
89152   int nColumn;          /* Number of columns in the data */
89153   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89154   int baseCur = 0;      /* VDBE Cursor number for pTab */
89155   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89156   int endOfLoop;        /* Label for the end of the insertion loop */
89157   int useTempTable = 0; /* Store SELECT results in intermediate table */
89158   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89159   int addrInsTop = 0;   /* Jump to label "D" */
89160   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89161   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89162   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89163   int iDb;              /* Index of database holding TABLE */
89164   Db *pDb;              /* The database containing table being inserted into */
89165   int appendFlag = 0;   /* True if the insert is likely to be an append */
89166
89167   /* Register allocations */
89168   int regFromSelect = 0;/* Base register for data coming from SELECT */
89169   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89170   int regRowCount = 0;  /* Memory cell used for the row counter */
89171   int regIns;           /* Block of regs holding rowid+data being inserted */
89172   int regRowid;         /* registers holding insert rowid */
89173   int regData;          /* register holding first column to insert */
89174   int regEof = 0;       /* Register recording end of SELECT data */
89175   int *aRegIdx = 0;     /* One register allocated to each index */
89176
89177 #ifndef SQLITE_OMIT_TRIGGER
89178   int isView;                 /* True if attempting to insert into a view */
89179   Trigger *pTrigger;          /* List of triggers on pTab, if required */
89180   int tmask;                  /* Mask of trigger times */
89181 #endif
89182
89183   db = pParse->db;
89184   memset(&dest, 0, sizeof(dest));
89185   if( pParse->nErr || db->mallocFailed ){
89186     goto insert_cleanup;
89187   }
89188
89189   /* Locate the table into which we will be inserting new information.
89190   */
89191   assert( pTabList->nSrc==1 );
89192   zTab = pTabList->a[0].zName;
89193   if( NEVER(zTab==0) ) goto insert_cleanup;
89194   pTab = sqlite3SrcListLookup(pParse, pTabList);
89195   if( pTab==0 ){
89196     goto insert_cleanup;
89197   }
89198   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89199   assert( iDb<db->nDb );
89200   pDb = &db->aDb[iDb];
89201   zDb = pDb->zName;
89202   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
89203     goto insert_cleanup;
89204   }
89205
89206   /* Figure out if we have any triggers and if the table being
89207   ** inserted into is a view
89208   */
89209 #ifndef SQLITE_OMIT_TRIGGER
89210   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89211   isView = pTab->pSelect!=0;
89212 #else
89213 # define pTrigger 0
89214 # define tmask 0
89215 # define isView 0
89216 #endif
89217 #ifdef SQLITE_OMIT_VIEW
89218 # undef isView
89219 # define isView 0
89220 #endif
89221   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89222
89223   /* If pTab is really a view, make sure it has been initialized.
89224   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
89225   ** module table).
89226   */
89227   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89228     goto insert_cleanup;
89229   }
89230
89231   /* Ensure that:
89232   *  (a) the table is not read-only, 
89233   *  (b) that if it is a view then ON INSERT triggers exist
89234   */
89235   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
89236     goto insert_cleanup;
89237   }
89238
89239   /* Allocate a VDBE
89240   */
89241   v = sqlite3GetVdbe(pParse);
89242   if( v==0 ) goto insert_cleanup;
89243   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89244   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89245
89246 #ifndef SQLITE_OMIT_XFER_OPT
89247   /* If the statement is of the form
89248   **
89249   **       INSERT INTO <table1> SELECT * FROM <table2>;
89250   **
89251   ** Then special optimizations can be applied that make the transfer
89252   ** very fast and which reduce fragmentation of indices.
89253   **
89254   ** This is the 2nd template.
89255   */
89256   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89257     assert( !pTrigger );
89258     assert( pList==0 );
89259     goto insert_end;
89260   }
89261 #endif /* SQLITE_OMIT_XFER_OPT */
89262
89263   /* If this is an AUTOINCREMENT table, look up the sequence number in the
89264   ** sqlite_sequence table and store it in memory cell regAutoinc.
89265   */
89266   regAutoinc = autoIncBegin(pParse, iDb, pTab);
89267
89268   /* Figure out how many columns of data are supplied.  If the data
89269   ** is coming from a SELECT statement, then generate a co-routine that
89270   ** produces a single row of the SELECT on each invocation.  The
89271   ** co-routine is the common header to the 3rd and 4th templates.
89272   */
89273   if( pSelect ){
89274     /* Data is coming from a SELECT.  Generate a co-routine to run that
89275     ** SELECT. */
89276     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
89277     if( rc ) goto insert_cleanup;
89278
89279     regEof = dest.iSDParm + 1;
89280     regFromSelect = dest.iSdst;
89281     assert( pSelect->pEList );
89282     nColumn = pSelect->pEList->nExpr;
89283     assert( dest.nSdst==nColumn );
89284
89285     /* Set useTempTable to TRUE if the result of the SELECT statement
89286     ** should be written into a temporary table (template 4).  Set to
89287     ** FALSE if each* row of the SELECT can be written directly into
89288     ** the destination table (template 3).
89289     **
89290     ** A temp table must be used if the table being updated is also one
89291     ** of the tables being read by the SELECT statement.  Also use a 
89292     ** temp table in the case of row triggers.
89293     */
89294     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89295       useTempTable = 1;
89296     }
89297
89298     if( useTempTable ){
89299       /* Invoke the coroutine to extract information from the SELECT
89300       ** and add it to a transient table srcTab.  The code generated
89301       ** here is from the 4th template:
89302       **
89303       **      B: open temp table
89304       **      L: yield X
89305       **         if EOF goto M
89306       **         insert row from R..R+n into temp table
89307       **         goto L
89308       **      M: ...
89309       */
89310       int regRec;          /* Register to hold packed record */
89311       int regTempRowid;    /* Register to hold temp table ROWID */
89312       int addrTop;         /* Label "L" */
89313       int addrIf;          /* Address of jump to M */
89314
89315       srcTab = pParse->nTab++;
89316       regRec = sqlite3GetTempReg(pParse);
89317       regTempRowid = sqlite3GetTempReg(pParse);
89318       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89319       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89320       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
89321       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89322       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89323       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89324       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89325       sqlite3VdbeJumpHere(v, addrIf);
89326       sqlite3ReleaseTempReg(pParse, regRec);
89327       sqlite3ReleaseTempReg(pParse, regTempRowid);
89328     }
89329   }else{
89330     /* This is the case if the data for the INSERT is coming from a VALUES
89331     ** clause
89332     */
89333     NameContext sNC;
89334     memset(&sNC, 0, sizeof(sNC));
89335     sNC.pParse = pParse;
89336     srcTab = -1;
89337     assert( useTempTable==0 );
89338     nColumn = pList ? pList->nExpr : 0;
89339     for(i=0; i<nColumn; i++){
89340       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89341         goto insert_cleanup;
89342       }
89343     }
89344   }
89345
89346   /* Make sure the number of columns in the source data matches the number
89347   ** of columns to be inserted into the table.
89348   */
89349   if( IsVirtual(pTab) ){
89350     for(i=0; i<pTab->nCol; i++){
89351       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89352     }
89353   }
89354   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89355     sqlite3ErrorMsg(pParse, 
89356        "table %S has %d columns but %d values were supplied",
89357        pTabList, 0, pTab->nCol-nHidden, nColumn);
89358     goto insert_cleanup;
89359   }
89360   if( pColumn!=0 && nColumn!=pColumn->nId ){
89361     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89362     goto insert_cleanup;
89363   }
89364
89365   /* If the INSERT statement included an IDLIST term, then make sure
89366   ** all elements of the IDLIST really are columns of the table and 
89367   ** remember the column indices.
89368   **
89369   ** If the table has an INTEGER PRIMARY KEY column and that column
89370   ** is named in the IDLIST, then record in the keyColumn variable
89371   ** the index into IDLIST of the primary key column.  keyColumn is
89372   ** the index of the primary key as it appears in IDLIST, not as
89373   ** is appears in the original table.  (The index of the primary
89374   ** key in the original table is pTab->iPKey.)
89375   */
89376   if( pColumn ){
89377     for(i=0; i<pColumn->nId; i++){
89378       pColumn->a[i].idx = -1;
89379     }
89380     for(i=0; i<pColumn->nId; i++){
89381       for(j=0; j<pTab->nCol; j++){
89382         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89383           pColumn->a[i].idx = j;
89384           if( j==pTab->iPKey ){
89385             keyColumn = i;
89386           }
89387           break;
89388         }
89389       }
89390       if( j>=pTab->nCol ){
89391         if( sqlite3IsRowid(pColumn->a[i].zName) ){
89392           keyColumn = i;
89393         }else{
89394           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
89395               pTabList, 0, pColumn->a[i].zName);
89396           pParse->checkSchema = 1;
89397           goto insert_cleanup;
89398         }
89399       }
89400     }
89401   }
89402
89403   /* If there is no IDLIST term but the table has an integer primary
89404   ** key, the set the keyColumn variable to the primary key column index
89405   ** in the original table definition.
89406   */
89407   if( pColumn==0 && nColumn>0 ){
89408     keyColumn = pTab->iPKey;
89409   }
89410     
89411   /* Initialize the count of rows to be inserted
89412   */
89413   if( db->flags & SQLITE_CountRows ){
89414     regRowCount = ++pParse->nMem;
89415     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89416   }
89417
89418   /* If this is not a view, open the table and and all indices */
89419   if( !isView ){
89420     int nIdx;
89421
89422     baseCur = pParse->nTab;
89423     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89424     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89425     if( aRegIdx==0 ){
89426       goto insert_cleanup;
89427     }
89428     for(i=0; i<nIdx; i++){
89429       aRegIdx[i] = ++pParse->nMem;
89430     }
89431   }
89432
89433   /* This is the top of the main insertion loop */
89434   if( useTempTable ){
89435     /* This block codes the top of loop only.  The complete loop is the
89436     ** following pseudocode (template 4):
89437     **
89438     **         rewind temp table
89439     **      C: loop over rows of intermediate table
89440     **           transfer values form intermediate table into <table>
89441     **         end loop
89442     **      D: ...
89443     */
89444     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
89445     addrCont = sqlite3VdbeCurrentAddr(v);
89446   }else if( pSelect ){
89447     /* This block codes the top of loop only.  The complete loop is the
89448     ** following pseudocode (template 3):
89449     **
89450     **      C: yield X
89451     **         if EOF goto D
89452     **         insert the select result into <table> from R..R+n
89453     **         goto C
89454     **      D: ...
89455     */
89456     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89457     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
89458   }
89459
89460   /* Allocate registers for holding the rowid of the new row,
89461   ** the content of the new row, and the assemblied row record.
89462   */
89463   regRowid = regIns = pParse->nMem+1;
89464   pParse->nMem += pTab->nCol + 1;
89465   if( IsVirtual(pTab) ){
89466     regRowid++;
89467     pParse->nMem++;
89468   }
89469   regData = regRowid+1;
89470
89471   /* Run the BEFORE and INSTEAD OF triggers, if there are any
89472   */
89473   endOfLoop = sqlite3VdbeMakeLabel(v);
89474   if( tmask & TRIGGER_BEFORE ){
89475     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
89476
89477     /* build the NEW.* reference row.  Note that if there is an INTEGER
89478     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89479     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89480     ** we do not know what the unique ID will be (because the insert has
89481     ** not happened yet) so we substitute a rowid of -1
89482     */
89483     if( keyColumn<0 ){
89484       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89485     }else{
89486       int j1;
89487       if( useTempTable ){
89488         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89489       }else{
89490         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89491         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89492       }
89493       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89494       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89495       sqlite3VdbeJumpHere(v, j1);
89496       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89497     }
89498
89499     /* Cannot have triggers on a virtual table. If it were possible,
89500     ** this block would have to account for hidden column.
89501     */
89502     assert( !IsVirtual(pTab) );
89503
89504     /* Create the new column data
89505     */
89506     for(i=0; i<pTab->nCol; i++){
89507       if( pColumn==0 ){
89508         j = i;
89509       }else{
89510         for(j=0; j<pColumn->nId; j++){
89511           if( pColumn->a[j].idx==i ) break;
89512         }
89513       }
89514       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89515         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89516       }else if( useTempTable ){
89517         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
89518       }else{
89519         assert( pSelect==0 ); /* Otherwise useTempTable is true */
89520         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89521       }
89522     }
89523
89524     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89525     ** do not attempt any conversions before assembling the record.
89526     ** If this is a real table, attempt conversions as required by the
89527     ** table column affinities.
89528     */
89529     if( !isView ){
89530       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89531       sqlite3TableAffinityStr(v, pTab);
89532     }
89533
89534     /* Fire BEFORE or INSTEAD OF triggers */
89535     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
89536         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89537
89538     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89539   }
89540
89541   /* Push the record number for the new entry onto the stack.  The
89542   ** record number is a randomly generate integer created by NewRowid
89543   ** except when the table has an INTEGER PRIMARY KEY column, in which
89544   ** case the record number is the same as that column. 
89545   */
89546   if( !isView ){
89547     if( IsVirtual(pTab) ){
89548       /* The row that the VUpdate opcode will delete: none */
89549       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
89550     }
89551     if( keyColumn>=0 ){
89552       if( useTempTable ){
89553         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89554       }else if( pSelect ){
89555         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89556       }else{
89557         VdbeOp *pOp;
89558         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89559         pOp = sqlite3VdbeGetOp(v, -1);
89560         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89561           appendFlag = 1;
89562           pOp->opcode = OP_NewRowid;
89563           pOp->p1 = baseCur;
89564           pOp->p2 = regRowid;
89565           pOp->p3 = regAutoinc;
89566         }
89567       }
89568       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89569       ** to generate a unique primary key value.
89570       */
89571       if( !appendFlag ){
89572         int j1;
89573         if( !IsVirtual(pTab) ){
89574           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
89575           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89576           sqlite3VdbeJumpHere(v, j1);
89577         }else{
89578           j1 = sqlite3VdbeCurrentAddr(v);
89579           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89580         }
89581         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89582       }
89583     }else if( IsVirtual(pTab) ){
89584       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
89585     }else{
89586       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89587       appendFlag = 1;
89588     }
89589     autoIncStep(pParse, regAutoinc, regRowid);
89590
89591     /* Push onto the stack, data for all columns of the new entry, beginning
89592     ** with the first column.
89593     */
89594     nHidden = 0;
89595     for(i=0; i<pTab->nCol; i++){
89596       int iRegStore = regRowid+1+i;
89597       if( i==pTab->iPKey ){
89598         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89599         ** Whenever this column is read, the record number will be substituted
89600         ** in its place.  So will fill this column with a NULL to avoid
89601         ** taking up data space with information that will never be used. */
89602         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89603         continue;
89604       }
89605       if( pColumn==0 ){
89606         if( IsHiddenColumn(&pTab->aCol[i]) ){
89607           assert( IsVirtual(pTab) );
89608           j = -1;
89609           nHidden++;
89610         }else{
89611           j = i - nHidden;
89612         }
89613       }else{
89614         for(j=0; j<pColumn->nId; j++){
89615           if( pColumn->a[j].idx==i ) break;
89616         }
89617       }
89618       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89619         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89620       }else if( useTempTable ){
89621         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
89622       }else if( pSelect ){
89623         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89624       }else{
89625         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89626       }
89627     }
89628
89629     /* Generate code to check constraints and generate index keys and
89630     ** do the insertion.
89631     */
89632 #ifndef SQLITE_OMIT_VIRTUALTABLE
89633     if( IsVirtual(pTab) ){
89634       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89635       sqlite3VtabMakeWritable(pParse, pTab);
89636       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89637       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89638       sqlite3MayAbort(pParse);
89639     }else
89640 #endif
89641     {
89642       int isReplace;    /* Set to true if constraints may cause a replace */
89643       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89644           keyColumn>=0, 0, onError, endOfLoop, &isReplace
89645       );
89646       sqlite3FkCheck(pParse, pTab, 0, regIns);
89647       sqlite3CompleteInsertion(
89648           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89649       );
89650     }
89651   }
89652
89653   /* Update the count of rows that are inserted
89654   */
89655   if( (db->flags & SQLITE_CountRows)!=0 ){
89656     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89657   }
89658
89659   if( pTrigger ){
89660     /* Code AFTER triggers */
89661     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
89662         pTab, regData-2-pTab->nCol, onError, endOfLoop);
89663   }
89664
89665   /* The bottom of the main insertion loop, if the data source
89666   ** is a SELECT statement.
89667   */
89668   sqlite3VdbeResolveLabel(v, endOfLoop);
89669   if( useTempTable ){
89670     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89671     sqlite3VdbeJumpHere(v, addrInsTop);
89672     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
89673   }else if( pSelect ){
89674     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89675     sqlite3VdbeJumpHere(v, addrInsTop);
89676   }
89677
89678   if( !IsVirtual(pTab) && !isView ){
89679     /* Close all tables opened */
89680     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
89681     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89682       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
89683     }
89684   }
89685
89686 insert_end:
89687   /* Update the sqlite_sequence table by storing the content of the
89688   ** maximum rowid counter values recorded while inserting into
89689   ** autoincrement tables.
89690   */
89691   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89692     sqlite3AutoincrementEnd(pParse);
89693   }
89694
89695   /*
89696   ** Return the number of rows inserted. If this routine is 
89697   ** generating code because of a call to sqlite3NestedParse(), do not
89698   ** invoke the callback function.
89699   */
89700   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89701     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
89702     sqlite3VdbeSetNumCols(v, 1);
89703     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
89704   }
89705
89706 insert_cleanup:
89707   sqlite3SrcListDelete(db, pTabList);
89708   sqlite3ExprListDelete(db, pList);
89709   sqlite3SelectDelete(db, pSelect);
89710   sqlite3IdListDelete(db, pColumn);
89711   sqlite3DbFree(db, aRegIdx);
89712 }
89713
89714 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89715 ** thely may interfere with compilation of other functions in this file
89716 ** (or in another file, if this file becomes part of the amalgamation).  */
89717 #ifdef isView
89718  #undef isView
89719 #endif
89720 #ifdef pTrigger
89721  #undef pTrigger
89722 #endif
89723 #ifdef tmask
89724  #undef tmask
89725 #endif
89726
89727
89728 /*
89729 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89730 **
89731 ** The input is a range of consecutive registers as follows:
89732 **
89733 **    1.  The rowid of the row after the update.
89734 **
89735 **    2.  The data in the first column of the entry after the update.
89736 **
89737 **    i.  Data from middle columns...
89738 **
89739 **    N.  The data in the last column of the entry after the update.
89740 **
89741 ** The regRowid parameter is the index of the register containing (1).
89742 **
89743 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89744 ** the address of a register containing the rowid before the update takes
89745 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89746 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
89747 ** indicates that the rowid was explicitly specified as part of the
89748 ** INSERT statement. If rowidChng is false, it means that  the rowid is
89749 ** computed automatically in an insert or that the rowid value is not 
89750 ** modified by an update.
89751 **
89752 ** The code generated by this routine store new index entries into
89753 ** registers identified by aRegIdx[].  No index entry is created for
89754 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
89755 ** the same as the order of indices on the linked list of indices
89756 ** attached to the table.
89757 **
89758 ** This routine also generates code to check constraints.  NOT NULL,
89759 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
89760 ** then the appropriate action is performed.  There are five possible
89761 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
89762 **
89763 **  Constraint type  Action       What Happens
89764 **  ---------------  ----------   ----------------------------------------
89765 **  any              ROLLBACK     The current transaction is rolled back and
89766 **                                sqlite3_exec() returns immediately with a
89767 **                                return code of SQLITE_CONSTRAINT.
89768 **
89769 **  any              ABORT        Back out changes from the current command
89770 **                                only (do not do a complete rollback) then
89771 **                                cause sqlite3_exec() to return immediately
89772 **                                with SQLITE_CONSTRAINT.
89773 **
89774 **  any              FAIL         Sqlite3_exec() returns immediately with a
89775 **                                return code of SQLITE_CONSTRAINT.  The
89776 **                                transaction is not rolled back and any
89777 **                                prior changes are retained.
89778 **
89779 **  any              IGNORE       The record number and data is popped from
89780 **                                the stack and there is an immediate jump
89781 **                                to label ignoreDest.
89782 **
89783 **  NOT NULL         REPLACE      The NULL value is replace by the default
89784 **                                value for that column.  If the default value
89785 **                                is NULL, the action is the same as ABORT.
89786 **
89787 **  UNIQUE           REPLACE      The other row that conflicts with the row
89788 **                                being inserted is removed.
89789 **
89790 **  CHECK            REPLACE      Illegal.  The results in an exception.
89791 **
89792 ** Which action to take is determined by the overrideError parameter.
89793 ** Or if overrideError==OE_Default, then the pParse->onError parameter
89794 ** is used.  Or if pParse->onError==OE_Default then the onError value
89795 ** for the constraint is used.
89796 **
89797 ** The calling routine must open a read/write cursor for pTab with
89798 ** cursor number "baseCur".  All indices of pTab must also have open
89799 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
89800 ** Except, if there is no possibility of a REPLACE action then
89801 ** cursors do not need to be open for indices where aRegIdx[i]==0.
89802 */
89803 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
89804   Parse *pParse,      /* The parser context */
89805   Table *pTab,        /* the table into which we are inserting */
89806   int baseCur,        /* Index of a read/write cursor pointing at pTab */
89807   int regRowid,       /* Index of the range of input registers */
89808   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
89809   int rowidChng,      /* True if the rowid might collide with existing entry */
89810   int isUpdate,       /* True for UPDATE, False for INSERT */
89811   int overrideError,  /* Override onError to this if not OE_Default */
89812   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
89813   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
89814 ){
89815   int i;              /* loop counter */
89816   Vdbe *v;            /* VDBE under constrution */
89817   int nCol;           /* Number of columns */
89818   int onError;        /* Conflict resolution strategy */
89819   int j1;             /* Addresss of jump instruction */
89820   int j2 = 0, j3;     /* Addresses of jump instructions */
89821   int regData;        /* Register containing first data column */
89822   int iCur;           /* Table cursor number */
89823   Index *pIdx;         /* Pointer to one of the indices */
89824   sqlite3 *db;         /* Database connection */
89825   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
89826   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
89827
89828   db = pParse->db;
89829   v = sqlite3GetVdbe(pParse);
89830   assert( v!=0 );
89831   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
89832   nCol = pTab->nCol;
89833   regData = regRowid + 1;
89834
89835   /* Test all NOT NULL constraints.
89836   */
89837   for(i=0; i<nCol; i++){
89838     if( i==pTab->iPKey ){
89839       continue;
89840     }
89841     onError = pTab->aCol[i].notNull;
89842     if( onError==OE_None ) continue;
89843     if( overrideError!=OE_Default ){
89844       onError = overrideError;
89845     }else if( onError==OE_Default ){
89846       onError = OE_Abort;
89847     }
89848     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
89849       onError = OE_Abort;
89850     }
89851     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
89852         || onError==OE_Ignore || onError==OE_Replace );
89853     switch( onError ){
89854       case OE_Abort:
89855         sqlite3MayAbort(pParse);
89856       case OE_Rollback:
89857       case OE_Fail: {
89858         char *zMsg;
89859         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
89860                                   SQLITE_CONSTRAINT, onError, regData+i);
89861         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
89862                               pTab->zName, pTab->aCol[i].zName);
89863         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
89864         break;
89865       }
89866       case OE_Ignore: {
89867         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
89868         break;
89869       }
89870       default: {
89871         assert( onError==OE_Replace );
89872         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
89873         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
89874         sqlite3VdbeJumpHere(v, j1);
89875         break;
89876       }
89877     }
89878   }
89879
89880   /* Test all CHECK constraints
89881   */
89882 #ifndef SQLITE_OMIT_CHECK
89883   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
89884     ExprList *pCheck = pTab->pCheck;
89885     pParse->ckBase = regData;
89886     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
89887     for(i=0; i<pCheck->nExpr; i++){
89888       int allOk = sqlite3VdbeMakeLabel(v);
89889       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
89890       if( onError==OE_Ignore ){
89891         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89892       }else{
89893         char *zConsName = pCheck->a[i].zName;
89894         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
89895         if( zConsName ){
89896           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
89897         }else{
89898           zConsName = 0;
89899         }
89900         sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);
89901       }
89902       sqlite3VdbeResolveLabel(v, allOk);
89903     }
89904   }
89905 #endif /* !defined(SQLITE_OMIT_CHECK) */
89906
89907   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
89908   ** of the new record does not previously exist.  Except, if this
89909   ** is an UPDATE and the primary key is not changing, that is OK.
89910   */
89911   if( rowidChng ){
89912     onError = pTab->keyConf;
89913     if( overrideError!=OE_Default ){
89914       onError = overrideError;
89915     }else if( onError==OE_Default ){
89916       onError = OE_Abort;
89917     }
89918     
89919     if( isUpdate ){
89920       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
89921     }
89922     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
89923     switch( onError ){
89924       default: {
89925         onError = OE_Abort;
89926         /* Fall thru into the next case */
89927       }
89928       case OE_Rollback:
89929       case OE_Abort:
89930       case OE_Fail: {
89931         sqlite3HaltConstraint(
89932           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
89933         break;
89934       }
89935       case OE_Replace: {
89936         /* If there are DELETE triggers on this table and the
89937         ** recursive-triggers flag is set, call GenerateRowDelete() to
89938         ** remove the conflicting row from the table. This will fire
89939         ** the triggers and remove both the table and index b-tree entries.
89940         **
89941         ** Otherwise, if there are no triggers or the recursive-triggers
89942         ** flag is not set, but the table has one or more indexes, call 
89943         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
89944         ** only. The table b-tree entry will be replaced by the new entry 
89945         ** when it is inserted.  
89946         **
89947         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
89948         ** also invoke MultiWrite() to indicate that this VDBE may require
89949         ** statement rollback (if the statement is aborted after the delete
89950         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
89951         ** but being more selective here allows statements like:
89952         **
89953         **   REPLACE INTO t(rowid) VALUES($newrowid)
89954         **
89955         ** to run without a statement journal if there are no indexes on the
89956         ** table.
89957         */
89958         Trigger *pTrigger = 0;
89959         if( db->flags&SQLITE_RecTriggers ){
89960           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89961         }
89962         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
89963           sqlite3MultiWrite(pParse);
89964           sqlite3GenerateRowDelete(
89965               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
89966           );
89967         }else if( pTab->pIndex ){
89968           sqlite3MultiWrite(pParse);
89969           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
89970         }
89971         seenReplace = 1;
89972         break;
89973       }
89974       case OE_Ignore: {
89975         assert( seenReplace==0 );
89976         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
89977         break;
89978       }
89979     }
89980     sqlite3VdbeJumpHere(v, j3);
89981     if( isUpdate ){
89982       sqlite3VdbeJumpHere(v, j2);
89983     }
89984   }
89985
89986   /* Test all UNIQUE constraints by creating entries for each UNIQUE
89987   ** index and making sure that duplicate entries do not already exist.
89988   ** Add the new records to the indices as we go.
89989   */
89990   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
89991     int regIdx;
89992     int regR;
89993
89994     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
89995
89996     /* Create a key for accessing the index entry */
89997     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
89998     for(i=0; i<pIdx->nColumn; i++){
89999       int idx = pIdx->aiColumn[i];
90000       if( idx==pTab->iPKey ){
90001         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90002       }else{
90003         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
90004       }
90005     }
90006     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90007     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
90008     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
90009     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
90010
90011     /* Find out what action to take in case there is an indexing conflict */
90012     onError = pIdx->onError;
90013     if( onError==OE_None ){ 
90014       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90015       continue;  /* pIdx is not a UNIQUE index */
90016     }
90017     if( overrideError!=OE_Default ){
90018       onError = overrideError;
90019     }else if( onError==OE_Default ){
90020       onError = OE_Abort;
90021     }
90022     if( seenReplace ){
90023       if( onError==OE_Ignore ) onError = OE_Replace;
90024       else if( onError==OE_Fail ) onError = OE_Abort;
90025     }
90026     
90027     /* Check to see if the new index entry will be unique */
90028     regR = sqlite3GetTempReg(pParse);
90029     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
90030     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
90031                            regR, SQLITE_INT_TO_PTR(regIdx),
90032                            P4_INT32);
90033     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90034
90035     /* Generate code that executes if the new index entry is not unique */
90036     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90037         || onError==OE_Ignore || onError==OE_Replace );
90038     switch( onError ){
90039       case OE_Rollback:
90040       case OE_Abort:
90041       case OE_Fail: {
90042         int j;
90043         StrAccum errMsg;
90044         const char *zSep;
90045         char *zErr;
90046
90047         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
90048         errMsg.db = db;
90049         zSep = pIdx->nColumn>1 ? "columns " : "column ";
90050         for(j=0; j<pIdx->nColumn; j++){
90051           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90052           sqlite3StrAccumAppend(&errMsg, zSep, -1);
90053           zSep = ", ";
90054           sqlite3StrAccumAppend(&errMsg, zCol, -1);
90055         }
90056         sqlite3StrAccumAppend(&errMsg,
90057             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90058         zErr = sqlite3StrAccumFinish(&errMsg);
90059         sqlite3HaltConstraint(pParse, onError, zErr, 0);
90060         sqlite3DbFree(errMsg.db, zErr);
90061         break;
90062       }
90063       case OE_Ignore: {
90064         assert( seenReplace==0 );
90065         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90066         break;
90067       }
90068       default: {
90069         Trigger *pTrigger = 0;
90070         assert( onError==OE_Replace );
90071         sqlite3MultiWrite(pParse);
90072         if( db->flags&SQLITE_RecTriggers ){
90073           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90074         }
90075         sqlite3GenerateRowDelete(
90076             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90077         );
90078         seenReplace = 1;
90079         break;
90080       }
90081     }
90082     sqlite3VdbeJumpHere(v, j3);
90083     sqlite3ReleaseTempReg(pParse, regR);
90084   }
90085   
90086   if( pbMayReplace ){
90087     *pbMayReplace = seenReplace;
90088   }
90089 }
90090
90091 /*
90092 ** This routine generates code to finish the INSERT or UPDATE operation
90093 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
90094 ** A consecutive range of registers starting at regRowid contains the
90095 ** rowid and the content to be inserted.
90096 **
90097 ** The arguments to this routine should be the same as the first six
90098 ** arguments to sqlite3GenerateConstraintChecks.
90099 */
90100 SQLITE_PRIVATE void sqlite3CompleteInsertion(
90101   Parse *pParse,      /* The parser context */
90102   Table *pTab,        /* the table into which we are inserting */
90103   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90104   int regRowid,       /* Range of content */
90105   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90106   int isUpdate,       /* True for UPDATE, False for INSERT */
90107   int appendBias,     /* True if this is likely to be an append */
90108   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90109 ){
90110   int i;
90111   Vdbe *v;
90112   int nIdx;
90113   Index *pIdx;
90114   u8 pik_flags;
90115   int regData;
90116   int regRec;
90117
90118   v = sqlite3GetVdbe(pParse);
90119   assert( v!=0 );
90120   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90121   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90122   for(i=nIdx-1; i>=0; i--){
90123     if( aRegIdx[i]==0 ) continue;
90124     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90125     if( useSeekResult ){
90126       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90127     }
90128   }
90129   regData = regRowid + 1;
90130   regRec = sqlite3GetTempReg(pParse);
90131   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90132   sqlite3TableAffinityStr(v, pTab);
90133   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90134   if( pParse->nested ){
90135     pik_flags = 0;
90136   }else{
90137     pik_flags = OPFLAG_NCHANGE;
90138     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90139   }
90140   if( appendBias ){
90141     pik_flags |= OPFLAG_APPEND;
90142   }
90143   if( useSeekResult ){
90144     pik_flags |= OPFLAG_USESEEKRESULT;
90145   }
90146   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90147   if( !pParse->nested ){
90148     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90149   }
90150   sqlite3VdbeChangeP5(v, pik_flags);
90151 }
90152
90153 /*
90154 ** Generate code that will open cursors for a table and for all
90155 ** indices of that table.  The "baseCur" parameter is the cursor number used
90156 ** for the table.  Indices are opened on subsequent cursors.
90157 **
90158 ** Return the number of indices on the table.
90159 */
90160 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
90161   Parse *pParse,   /* Parsing context */
90162   Table *pTab,     /* Table to be opened */
90163   int baseCur,     /* Cursor number assigned to the table */
90164   int op           /* OP_OpenRead or OP_OpenWrite */
90165 ){
90166   int i;
90167   int iDb;
90168   Index *pIdx;
90169   Vdbe *v;
90170
90171   if( IsVirtual(pTab) ) return 0;
90172   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90173   v = sqlite3GetVdbe(pParse);
90174   assert( v!=0 );
90175   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
90176   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90177     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
90178     assert( pIdx->pSchema==pTab->pSchema );
90179     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90180                       (char*)pKey, P4_KEYINFO_HANDOFF);
90181     VdbeComment((v, "%s", pIdx->zName));
90182   }
90183   if( pParse->nTab<baseCur+i ){
90184     pParse->nTab = baseCur+i;
90185   }
90186   return i-1;
90187 }
90188
90189
90190 #ifdef SQLITE_TEST
90191 /*
90192 ** The following global variable is incremented whenever the
90193 ** transfer optimization is used.  This is used for testing
90194 ** purposes only - to make sure the transfer optimization really
90195 ** is happening when it is suppose to.
90196 */
90197 SQLITE_API int sqlite3_xferopt_count;
90198 #endif /* SQLITE_TEST */
90199
90200
90201 #ifndef SQLITE_OMIT_XFER_OPT
90202 /*
90203 ** Check to collation names to see if they are compatible.
90204 */
90205 static int xferCompatibleCollation(const char *z1, const char *z2){
90206   if( z1==0 ){
90207     return z2==0;
90208   }
90209   if( z2==0 ){
90210     return 0;
90211   }
90212   return sqlite3StrICmp(z1, z2)==0;
90213 }
90214
90215
90216 /*
90217 ** Check to see if index pSrc is compatible as a source of data
90218 ** for index pDest in an insert transfer optimization.  The rules
90219 ** for a compatible index:
90220 **
90221 **    *   The index is over the same set of columns
90222 **    *   The same DESC and ASC markings occurs on all columns
90223 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90224 **    *   The same collating sequence on each column
90225 */
90226 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90227   int i;
90228   assert( pDest && pSrc );
90229   assert( pDest->pTable!=pSrc->pTable );
90230   if( pDest->nColumn!=pSrc->nColumn ){
90231     return 0;   /* Different number of columns */
90232   }
90233   if( pDest->onError!=pSrc->onError ){
90234     return 0;   /* Different conflict resolution strategies */
90235   }
90236   for(i=0; i<pSrc->nColumn; i++){
90237     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90238       return 0;   /* Different columns indexed */
90239     }
90240     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90241       return 0;   /* Different sort orders */
90242     }
90243     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90244       return 0;   /* Different collating sequences */
90245     }
90246   }
90247
90248   /* If no test above fails then the indices must be compatible */
90249   return 1;
90250 }
90251
90252 /*
90253 ** Attempt the transfer optimization on INSERTs of the form
90254 **
90255 **     INSERT INTO tab1 SELECT * FROM tab2;
90256 **
90257 ** The xfer optimization transfers raw records from tab2 over to tab1.  
90258 ** Columns are not decoded and reassemblied, which greatly improves
90259 ** performance.  Raw index records are transferred in the same way.
90260 **
90261 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
90262 ** There are lots of rules for determining compatibility - see comments
90263 ** embedded in the code for details.
90264 **
90265 ** This routine returns TRUE if the optimization is guaranteed to be used.
90266 ** Sometimes the xfer optimization will only work if the destination table
90267 ** is empty - a factor that can only be determined at run-time.  In that
90268 ** case, this routine generates code for the xfer optimization but also
90269 ** does a test to see if the destination table is empty and jumps over the
90270 ** xfer optimization code if the test fails.  In that case, this routine
90271 ** returns FALSE so that the caller will know to go ahead and generate
90272 ** an unoptimized transfer.  This routine also returns FALSE if there
90273 ** is no chance that the xfer optimization can be applied.
90274 **
90275 ** This optimization is particularly useful at making VACUUM run faster.
90276 */
90277 static int xferOptimization(
90278   Parse *pParse,        /* Parser context */
90279   Table *pDest,         /* The table we are inserting into */
90280   Select *pSelect,      /* A SELECT statement to use as the data source */
90281   int onError,          /* How to handle constraint errors */
90282   int iDbDest           /* The database of pDest */
90283 ){
90284   ExprList *pEList;                /* The result set of the SELECT */
90285   Table *pSrc;                     /* The table in the FROM clause of SELECT */
90286   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90287   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90288   int i;                           /* Loop counter */
90289   int iDbSrc;                      /* The database of pSrc */
90290   int iSrc, iDest;                 /* Cursors from source and destination */
90291   int addr1, addr2;                /* Loop addresses */
90292   int emptyDestTest;               /* Address of test for empty pDest */
90293   int emptySrcTest;                /* Address of test for empty pSrc */
90294   Vdbe *v;                         /* The VDBE we are building */
90295   KeyInfo *pKey;                   /* Key information for an index */
90296   int regAutoinc;                  /* Memory register used by AUTOINC */
90297   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90298   int regData, regRowid;           /* Registers holding data and rowid */
90299
90300   if( pSelect==0 ){
90301     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90302   }
90303   if( sqlite3TriggerList(pParse, pDest) ){
90304     return 0;   /* tab1 must not have triggers */
90305   }
90306 #ifndef SQLITE_OMIT_VIRTUALTABLE
90307   if( pDest->tabFlags & TF_Virtual ){
90308     return 0;   /* tab1 must not be a virtual table */
90309   }
90310 #endif
90311   if( onError==OE_Default ){
90312     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
90313     if( onError==OE_Default ) onError = OE_Abort;
90314   }
90315   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90316   if( pSelect->pSrc->nSrc!=1 ){
90317     return 0;   /* FROM clause must have exactly one term */
90318   }
90319   if( pSelect->pSrc->a[0].pSelect ){
90320     return 0;   /* FROM clause cannot contain a subquery */
90321   }
90322   if( pSelect->pWhere ){
90323     return 0;   /* SELECT may not have a WHERE clause */
90324   }
90325   if( pSelect->pOrderBy ){
90326     return 0;   /* SELECT may not have an ORDER BY clause */
90327   }
90328   /* Do not need to test for a HAVING clause.  If HAVING is present but
90329   ** there is no ORDER BY, we will get an error. */
90330   if( pSelect->pGroupBy ){
90331     return 0;   /* SELECT may not have a GROUP BY clause */
90332   }
90333   if( pSelect->pLimit ){
90334     return 0;   /* SELECT may not have a LIMIT clause */
90335   }
90336   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90337   if( pSelect->pPrior ){
90338     return 0;   /* SELECT may not be a compound query */
90339   }
90340   if( pSelect->selFlags & SF_Distinct ){
90341     return 0;   /* SELECT may not be DISTINCT */
90342   }
90343   pEList = pSelect->pEList;
90344   assert( pEList!=0 );
90345   if( pEList->nExpr!=1 ){
90346     return 0;   /* The result set must have exactly one column */
90347   }
90348   assert( pEList->a[0].pExpr );
90349   if( pEList->a[0].pExpr->op!=TK_ALL ){
90350     return 0;   /* The result set must be the special operator "*" */
90351   }
90352
90353   /* At this point we have established that the statement is of the
90354   ** correct syntactic form to participate in this optimization.  Now
90355   ** we have to check the semantics.
90356   */
90357   pItem = pSelect->pSrc->a;
90358   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
90359   if( pSrc==0 ){
90360     return 0;   /* FROM clause does not contain a real table */
90361   }
90362   if( pSrc==pDest ){
90363     return 0;   /* tab1 and tab2 may not be the same table */
90364   }
90365 #ifndef SQLITE_OMIT_VIRTUALTABLE
90366   if( pSrc->tabFlags & TF_Virtual ){
90367     return 0;   /* tab2 must not be a virtual table */
90368   }
90369 #endif
90370   if( pSrc->pSelect ){
90371     return 0;   /* tab2 may not be a view */
90372   }
90373   if( pDest->nCol!=pSrc->nCol ){
90374     return 0;   /* Number of columns must be the same in tab1 and tab2 */
90375   }
90376   if( pDest->iPKey!=pSrc->iPKey ){
90377     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90378   }
90379   for(i=0; i<pDest->nCol; i++){
90380     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90381       return 0;    /* Affinity must be the same on all columns */
90382     }
90383     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90384       return 0;    /* Collating sequence must be the same on all columns */
90385     }
90386     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90387       return 0;    /* tab2 must be NOT NULL if tab1 is */
90388     }
90389   }
90390   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90391     if( pDestIdx->onError!=OE_None ){
90392       destHasUniqueIdx = 1;
90393     }
90394     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90395       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90396     }
90397     if( pSrcIdx==0 ){
90398       return 0;    /* pDestIdx has no corresponding index in pSrc */
90399     }
90400   }
90401 #ifndef SQLITE_OMIT_CHECK
90402   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
90403     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90404   }
90405 #endif
90406 #ifndef SQLITE_OMIT_FOREIGN_KEY
90407   /* Disallow the transfer optimization if the destination table constains
90408   ** any foreign key constraints.  This is more restrictive than necessary.
90409   ** But the main beneficiary of the transfer optimization is the VACUUM 
90410   ** command, and the VACUUM command disables foreign key constraints.  So
90411   ** the extra complication to make this rule less restrictive is probably
90412   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90413   */
90414   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90415     return 0;
90416   }
90417 #endif
90418   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
90419     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
90420   }
90421
90422   /* If we get this far, it means that the xfer optimization is at
90423   ** least a possibility, though it might only work if the destination
90424   ** table (tab1) is initially empty.
90425   */
90426 #ifdef SQLITE_TEST
90427   sqlite3_xferopt_count++;
90428 #endif
90429   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
90430   v = sqlite3GetVdbe(pParse);
90431   sqlite3CodeVerifySchema(pParse, iDbSrc);
90432   iSrc = pParse->nTab++;
90433   iDest = pParse->nTab++;
90434   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90435   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90436   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
90437    || destHasUniqueIdx                              /* (2) */
90438    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
90439   ){
90440     /* In some circumstances, we are able to run the xfer optimization
90441     ** only if the destination table is initially empty.  This code makes
90442     ** that determination.  Conditions under which the destination must
90443     ** be empty:
90444     **
90445     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
90446     **     (If the destination is not initially empty, the rowid fields
90447     **     of index entries might need to change.)
90448     **
90449     ** (2) The destination has a unique index.  (The xfer optimization 
90450     **     is unable to test uniqueness.)
90451     **
90452     ** (3) onError is something other than OE_Abort and OE_Rollback.
90453     */
90454     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90455     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90456     sqlite3VdbeJumpHere(v, addr1);
90457   }else{
90458     emptyDestTest = 0;
90459   }
90460   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90461   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90462   regData = sqlite3GetTempReg(pParse);
90463   regRowid = sqlite3GetTempReg(pParse);
90464   if( pDest->iPKey>=0 ){
90465     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90466     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90467     sqlite3HaltConstraint(
90468         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90469     sqlite3VdbeJumpHere(v, addr2);
90470     autoIncStep(pParse, regAutoinc, regRowid);
90471   }else if( pDest->pIndex==0 ){
90472     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90473   }else{
90474     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90475     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90476   }
90477   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90478   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90479   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90480   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
90481   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90482   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90483     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90484       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90485     }
90486     assert( pSrcIdx );
90487     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90488     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90489     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
90490     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90491                       (char*)pKey, P4_KEYINFO_HANDOFF);
90492     VdbeComment((v, "%s", pSrcIdx->zName));
90493     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
90494     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90495                       (char*)pKey, P4_KEYINFO_HANDOFF);
90496     VdbeComment((v, "%s", pDestIdx->zName));
90497     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90498     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90499     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90500     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90501     sqlite3VdbeJumpHere(v, addr1);
90502   }
90503   sqlite3VdbeJumpHere(v, emptySrcTest);
90504   sqlite3ReleaseTempReg(pParse, regRowid);
90505   sqlite3ReleaseTempReg(pParse, regData);
90506   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90507   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90508   if( emptyDestTest ){
90509     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
90510     sqlite3VdbeJumpHere(v, emptyDestTest);
90511     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90512     return 0;
90513   }else{
90514     return 1;
90515   }
90516 }
90517 #endif /* SQLITE_OMIT_XFER_OPT */
90518
90519 /************** End of insert.c **********************************************/
90520 /************** Begin file legacy.c ******************************************/
90521 /*
90522 ** 2001 September 15
90523 **
90524 ** The author disclaims copyright to this source code.  In place of
90525 ** a legal notice, here is a blessing:
90526 **
90527 **    May you do good and not evil.
90528 **    May you find forgiveness for yourself and forgive others.
90529 **    May you share freely, never taking more than you give.
90530 **
90531 *************************************************************************
90532 ** Main file for the SQLite library.  The routines in this file
90533 ** implement the programmer interface to the library.  Routines in
90534 ** other files are for internal use by SQLite and should not be
90535 ** accessed by users of the library.
90536 */
90537
90538
90539 /*
90540 ** Execute SQL code.  Return one of the SQLITE_ success/failure
90541 ** codes.  Also write an error message into memory obtained from
90542 ** malloc() and make *pzErrMsg point to that message.
90543 **
90544 ** If the SQL is a query, then for each row in the query result
90545 ** the xCallback() function is called.  pArg becomes the first
90546 ** argument to xCallback().  If xCallback=NULL then no callback
90547 ** is invoked, even for queries.
90548 */
90549 SQLITE_API int sqlite3_exec(
90550   sqlite3 *db,                /* The database on which the SQL executes */
90551   const char *zSql,           /* The SQL to be executed */
90552   sqlite3_callback xCallback, /* Invoke this callback routine */
90553   void *pArg,                 /* First argument to xCallback() */
90554   char **pzErrMsg             /* Write error messages here */
90555 ){
90556   int rc = SQLITE_OK;         /* Return code */
90557   const char *zLeftover;      /* Tail of unprocessed SQL */
90558   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
90559   char **azCols = 0;          /* Names of result columns */
90560   int nRetry = 0;             /* Number of retry attempts */
90561   int callbackIsInit;         /* True if callback data is initialized */
90562
90563   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90564   if( zSql==0 ) zSql = "";
90565
90566   sqlite3_mutex_enter(db->mutex);
90567   sqlite3Error(db, SQLITE_OK, 0);
90568   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90569     int nCol;
90570     char **azVals = 0;
90571
90572     pStmt = 0;
90573     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90574     assert( rc==SQLITE_OK || pStmt==0 );
90575     if( rc!=SQLITE_OK ){
90576       continue;
90577     }
90578     if( !pStmt ){
90579       /* this happens for a comment or white-space */
90580       zSql = zLeftover;
90581       continue;
90582     }
90583
90584     callbackIsInit = 0;
90585     nCol = sqlite3_column_count(pStmt);
90586
90587     while( 1 ){
90588       int i;
90589       rc = sqlite3_step(pStmt);
90590
90591       /* Invoke the callback function if required */
90592       if( xCallback && (SQLITE_ROW==rc || 
90593           (SQLITE_DONE==rc && !callbackIsInit
90594                            && db->flags&SQLITE_NullCallback)) ){
90595         if( !callbackIsInit ){
90596           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90597           if( azCols==0 ){
90598             goto exec_out;
90599           }
90600           for(i=0; i<nCol; i++){
90601             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
90602             /* sqlite3VdbeSetColName() installs column names as UTF8
90603             ** strings so there is no way for sqlite3_column_name() to fail. */
90604             assert( azCols[i]!=0 );
90605           }
90606           callbackIsInit = 1;
90607         }
90608         if( rc==SQLITE_ROW ){
90609           azVals = &azCols[nCol];
90610           for(i=0; i<nCol; i++){
90611             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
90612             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
90613               db->mallocFailed = 1;
90614               goto exec_out;
90615             }
90616           }
90617         }
90618         if( xCallback(pArg, nCol, azVals, azCols) ){
90619           rc = SQLITE_ABORT;
90620           sqlite3VdbeFinalize((Vdbe *)pStmt);
90621           pStmt = 0;
90622           sqlite3Error(db, SQLITE_ABORT, 0);
90623           goto exec_out;
90624         }
90625       }
90626
90627       if( rc!=SQLITE_ROW ){
90628         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
90629         pStmt = 0;
90630         if( rc!=SQLITE_SCHEMA ){
90631           nRetry = 0;
90632           zSql = zLeftover;
90633           while( sqlite3Isspace(zSql[0]) ) zSql++;
90634         }
90635         break;
90636       }
90637     }
90638
90639     sqlite3DbFree(db, azCols);
90640     azCols = 0;
90641   }
90642
90643 exec_out:
90644   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
90645   sqlite3DbFree(db, azCols);
90646
90647   rc = sqlite3ApiExit(db, rc);
90648   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
90649     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
90650     *pzErrMsg = sqlite3Malloc(nErrMsg);
90651     if( *pzErrMsg ){
90652       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
90653     }else{
90654       rc = SQLITE_NOMEM;
90655       sqlite3Error(db, SQLITE_NOMEM, 0);
90656     }
90657   }else if( pzErrMsg ){
90658     *pzErrMsg = 0;
90659   }
90660
90661   assert( (rc&db->errMask)==rc );
90662   sqlite3_mutex_leave(db->mutex);
90663   return rc;
90664 }
90665
90666 /************** End of legacy.c **********************************************/
90667 /************** Begin file loadext.c *****************************************/
90668 /*
90669 ** 2006 June 7
90670 **
90671 ** The author disclaims copyright to this source code.  In place of
90672 ** a legal notice, here is a blessing:
90673 **
90674 **    May you do good and not evil.
90675 **    May you find forgiveness for yourself and forgive others.
90676 **    May you share freely, never taking more than you give.
90677 **
90678 *************************************************************************
90679 ** This file contains code used to dynamically load extensions into
90680 ** the SQLite library.
90681 */
90682
90683 #ifndef SQLITE_CORE
90684   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
90685 #endif
90686 /************** Include sqlite3ext.h in the middle of loadext.c **************/
90687 /************** Begin file sqlite3ext.h **************************************/
90688 /*
90689 ** 2006 June 7
90690 **
90691 ** The author disclaims copyright to this source code.  In place of
90692 ** a legal notice, here is a blessing:
90693 **
90694 **    May you do good and not evil.
90695 **    May you find forgiveness for yourself and forgive others.
90696 **    May you share freely, never taking more than you give.
90697 **
90698 *************************************************************************
90699 ** This header file defines the SQLite interface for use by
90700 ** shared libraries that want to be imported as extensions into
90701 ** an SQLite instance.  Shared libraries that intend to be loaded
90702 ** as extensions by SQLite should #include this file instead of 
90703 ** sqlite3.h.
90704 */
90705 #ifndef _SQLITE3EXT_H_
90706 #define _SQLITE3EXT_H_
90707
90708 typedef struct sqlite3_api_routines sqlite3_api_routines;
90709
90710 /*
90711 ** The following structure holds pointers to all of the SQLite API
90712 ** routines.
90713 **
90714 ** WARNING:  In order to maintain backwards compatibility, add new
90715 ** interfaces to the end of this structure only.  If you insert new
90716 ** interfaces in the middle of this structure, then older different
90717 ** versions of SQLite will not be able to load each others' shared
90718 ** libraries!
90719 */
90720 struct sqlite3_api_routines {
90721   void * (*aggregate_context)(sqlite3_context*,int nBytes);
90722   int  (*aggregate_count)(sqlite3_context*);
90723   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
90724   int  (*bind_double)(sqlite3_stmt*,int,double);
90725   int  (*bind_int)(sqlite3_stmt*,int,int);
90726   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
90727   int  (*bind_null)(sqlite3_stmt*,int);
90728   int  (*bind_parameter_count)(sqlite3_stmt*);
90729   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
90730   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
90731   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
90732   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
90733   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
90734   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
90735   int  (*busy_timeout)(sqlite3*,int ms);
90736   int  (*changes)(sqlite3*);
90737   int  (*close)(sqlite3*);
90738   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
90739                            int eTextRep,const char*));
90740   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
90741                              int eTextRep,const void*));
90742   const void * (*column_blob)(sqlite3_stmt*,int iCol);
90743   int  (*column_bytes)(sqlite3_stmt*,int iCol);
90744   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
90745   int  (*column_count)(sqlite3_stmt*pStmt);
90746   const char * (*column_database_name)(sqlite3_stmt*,int);
90747   const void * (*column_database_name16)(sqlite3_stmt*,int);
90748   const char * (*column_decltype)(sqlite3_stmt*,int i);
90749   const void * (*column_decltype16)(sqlite3_stmt*,int);
90750   double  (*column_double)(sqlite3_stmt*,int iCol);
90751   int  (*column_int)(sqlite3_stmt*,int iCol);
90752   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
90753   const char * (*column_name)(sqlite3_stmt*,int);
90754   const void * (*column_name16)(sqlite3_stmt*,int);
90755   const char * (*column_origin_name)(sqlite3_stmt*,int);
90756   const void * (*column_origin_name16)(sqlite3_stmt*,int);
90757   const char * (*column_table_name)(sqlite3_stmt*,int);
90758   const void * (*column_table_name16)(sqlite3_stmt*,int);
90759   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
90760   const void * (*column_text16)(sqlite3_stmt*,int iCol);
90761   int  (*column_type)(sqlite3_stmt*,int iCol);
90762   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
90763   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
90764   int  (*complete)(const char*sql);
90765   int  (*complete16)(const void*sql);
90766   int  (*create_collation)(sqlite3*,const char*,int,void*,
90767                            int(*)(void*,int,const void*,int,const void*));
90768   int  (*create_collation16)(sqlite3*,const void*,int,void*,
90769                              int(*)(void*,int,const void*,int,const void*));
90770   int  (*create_function)(sqlite3*,const char*,int,int,void*,
90771                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90772                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90773                           void (*xFinal)(sqlite3_context*));
90774   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
90775                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90776                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90777                             void (*xFinal)(sqlite3_context*));
90778   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
90779   int  (*data_count)(sqlite3_stmt*pStmt);
90780   sqlite3 * (*db_handle)(sqlite3_stmt*);
90781   int (*declare_vtab)(sqlite3*,const char*);
90782   int  (*enable_shared_cache)(int);
90783   int  (*errcode)(sqlite3*db);
90784   const char * (*errmsg)(sqlite3*);
90785   const void * (*errmsg16)(sqlite3*);
90786   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
90787   int  (*expired)(sqlite3_stmt*);
90788   int  (*finalize)(sqlite3_stmt*pStmt);
90789   void  (*free)(void*);
90790   void  (*free_table)(char**result);
90791   int  (*get_autocommit)(sqlite3*);
90792   void * (*get_auxdata)(sqlite3_context*,int);
90793   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
90794   int  (*global_recover)(void);
90795   void  (*interruptx)(sqlite3*);
90796   sqlite_int64  (*last_insert_rowid)(sqlite3*);
90797   const char * (*libversion)(void);
90798   int  (*libversion_number)(void);
90799   void *(*malloc)(int);
90800   char * (*mprintf)(const char*,...);
90801   int  (*open)(const char*,sqlite3**);
90802   int  (*open16)(const void*,sqlite3**);
90803   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
90804   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
90805   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
90806   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
90807   void *(*realloc)(void*,int);
90808   int  (*reset)(sqlite3_stmt*pStmt);
90809   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
90810   void  (*result_double)(sqlite3_context*,double);
90811   void  (*result_error)(sqlite3_context*,const char*,int);
90812   void  (*result_error16)(sqlite3_context*,const void*,int);
90813   void  (*result_int)(sqlite3_context*,int);
90814   void  (*result_int64)(sqlite3_context*,sqlite_int64);
90815   void  (*result_null)(sqlite3_context*);
90816   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
90817   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
90818   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
90819   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
90820   void  (*result_value)(sqlite3_context*,sqlite3_value*);
90821   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
90822   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
90823                          const char*,const char*),void*);
90824   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
90825   char * (*snprintf)(int,char*,const char*,...);
90826   int  (*step)(sqlite3_stmt*);
90827   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
90828                                 char const**,char const**,int*,int*,int*);
90829   void  (*thread_cleanup)(void);
90830   int  (*total_changes)(sqlite3*);
90831   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
90832   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
90833   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
90834                                          sqlite_int64),void*);
90835   void * (*user_data)(sqlite3_context*);
90836   const void * (*value_blob)(sqlite3_value*);
90837   int  (*value_bytes)(sqlite3_value*);
90838   int  (*value_bytes16)(sqlite3_value*);
90839   double  (*value_double)(sqlite3_value*);
90840   int  (*value_int)(sqlite3_value*);
90841   sqlite_int64  (*value_int64)(sqlite3_value*);
90842   int  (*value_numeric_type)(sqlite3_value*);
90843   const unsigned char * (*value_text)(sqlite3_value*);
90844   const void * (*value_text16)(sqlite3_value*);
90845   const void * (*value_text16be)(sqlite3_value*);
90846   const void * (*value_text16le)(sqlite3_value*);
90847   int  (*value_type)(sqlite3_value*);
90848   char *(*vmprintf)(const char*,va_list);
90849   /* Added ??? */
90850   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
90851   /* Added by 3.3.13 */
90852   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
90853   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
90854   int (*clear_bindings)(sqlite3_stmt*);
90855   /* Added by 3.4.1 */
90856   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
90857                           void (*xDestroy)(void *));
90858   /* Added by 3.5.0 */
90859   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
90860   int (*blob_bytes)(sqlite3_blob*);
90861   int (*blob_close)(sqlite3_blob*);
90862   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
90863                    int,sqlite3_blob**);
90864   int (*blob_read)(sqlite3_blob*,void*,int,int);
90865   int (*blob_write)(sqlite3_blob*,const void*,int,int);
90866   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
90867                              int(*)(void*,int,const void*,int,const void*),
90868                              void(*)(void*));
90869   int (*file_control)(sqlite3*,const char*,int,void*);
90870   sqlite3_int64 (*memory_highwater)(int);
90871   sqlite3_int64 (*memory_used)(void);
90872   sqlite3_mutex *(*mutex_alloc)(int);
90873   void (*mutex_enter)(sqlite3_mutex*);
90874   void (*mutex_free)(sqlite3_mutex*);
90875   void (*mutex_leave)(sqlite3_mutex*);
90876   int (*mutex_try)(sqlite3_mutex*);
90877   int (*open_v2)(const char*,sqlite3**,int,const char*);
90878   int (*release_memory)(int);
90879   void (*result_error_nomem)(sqlite3_context*);
90880   void (*result_error_toobig)(sqlite3_context*);
90881   int (*sleep)(int);
90882   void (*soft_heap_limit)(int);
90883   sqlite3_vfs *(*vfs_find)(const char*);
90884   int (*vfs_register)(sqlite3_vfs*,int);
90885   int (*vfs_unregister)(sqlite3_vfs*);
90886   int (*xthreadsafe)(void);
90887   void (*result_zeroblob)(sqlite3_context*,int);
90888   void (*result_error_code)(sqlite3_context*,int);
90889   int (*test_control)(int, ...);
90890   void (*randomness)(int,void*);
90891   sqlite3 *(*context_db_handle)(sqlite3_context*);
90892   int (*extended_result_codes)(sqlite3*,int);
90893   int (*limit)(sqlite3*,int,int);
90894   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
90895   const char *(*sql)(sqlite3_stmt*);
90896   int (*status)(int,int*,int*,int);
90897   int (*backup_finish)(sqlite3_backup*);
90898   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
90899   int (*backup_pagecount)(sqlite3_backup*);
90900   int (*backup_remaining)(sqlite3_backup*);
90901   int (*backup_step)(sqlite3_backup*,int);
90902   const char *(*compileoption_get)(int);
90903   int (*compileoption_used)(const char*);
90904   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
90905                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
90906                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
90907                             void (*xFinal)(sqlite3_context*),
90908                             void(*xDestroy)(void*));
90909   int (*db_config)(sqlite3*,int,...);
90910   sqlite3_mutex *(*db_mutex)(sqlite3*);
90911   int (*db_status)(sqlite3*,int,int*,int*,int);
90912   int (*extended_errcode)(sqlite3*);
90913   void (*log)(int,const char*,...);
90914   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
90915   const char *(*sourceid)(void);
90916   int (*stmt_status)(sqlite3_stmt*,int,int);
90917   int (*strnicmp)(const char*,const char*,int);
90918   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
90919   int (*wal_autocheckpoint)(sqlite3*,int);
90920   int (*wal_checkpoint)(sqlite3*,const char*);
90921   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
90922   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
90923   int (*vtab_config)(sqlite3*,int op,...);
90924   int (*vtab_on_conflict)(sqlite3*);
90925 };
90926
90927 /*
90928 ** The following macros redefine the API routines so that they are
90929 ** redirected throught the global sqlite3_api structure.
90930 **
90931 ** This header file is also used by the loadext.c source file
90932 ** (part of the main SQLite library - not an extension) so that
90933 ** it can get access to the sqlite3_api_routines structure
90934 ** definition.  But the main library does not want to redefine
90935 ** the API.  So the redefinition macros are only valid if the
90936 ** SQLITE_CORE macros is undefined.
90937 */
90938 #ifndef SQLITE_CORE
90939 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
90940 #ifndef SQLITE_OMIT_DEPRECATED
90941 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
90942 #endif
90943 #define sqlite3_bind_blob              sqlite3_api->bind_blob
90944 #define sqlite3_bind_double            sqlite3_api->bind_double
90945 #define sqlite3_bind_int               sqlite3_api->bind_int
90946 #define sqlite3_bind_int64             sqlite3_api->bind_int64
90947 #define sqlite3_bind_null              sqlite3_api->bind_null
90948 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
90949 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
90950 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
90951 #define sqlite3_bind_text              sqlite3_api->bind_text
90952 #define sqlite3_bind_text16            sqlite3_api->bind_text16
90953 #define sqlite3_bind_value             sqlite3_api->bind_value
90954 #define sqlite3_busy_handler           sqlite3_api->busy_handler
90955 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
90956 #define sqlite3_changes                sqlite3_api->changes
90957 #define sqlite3_close                  sqlite3_api->close
90958 #define sqlite3_collation_needed       sqlite3_api->collation_needed
90959 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
90960 #define sqlite3_column_blob            sqlite3_api->column_blob
90961 #define sqlite3_column_bytes           sqlite3_api->column_bytes
90962 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
90963 #define sqlite3_column_count           sqlite3_api->column_count
90964 #define sqlite3_column_database_name   sqlite3_api->column_database_name
90965 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
90966 #define sqlite3_column_decltype        sqlite3_api->column_decltype
90967 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
90968 #define sqlite3_column_double          sqlite3_api->column_double
90969 #define sqlite3_column_int             sqlite3_api->column_int
90970 #define sqlite3_column_int64           sqlite3_api->column_int64
90971 #define sqlite3_column_name            sqlite3_api->column_name
90972 #define sqlite3_column_name16          sqlite3_api->column_name16
90973 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
90974 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
90975 #define sqlite3_column_table_name      sqlite3_api->column_table_name
90976 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
90977 #define sqlite3_column_text            sqlite3_api->column_text
90978 #define sqlite3_column_text16          sqlite3_api->column_text16
90979 #define sqlite3_column_type            sqlite3_api->column_type
90980 #define sqlite3_column_value           sqlite3_api->column_value
90981 #define sqlite3_commit_hook            sqlite3_api->commit_hook
90982 #define sqlite3_complete               sqlite3_api->complete
90983 #define sqlite3_complete16             sqlite3_api->complete16
90984 #define sqlite3_create_collation       sqlite3_api->create_collation
90985 #define sqlite3_create_collation16     sqlite3_api->create_collation16
90986 #define sqlite3_create_function        sqlite3_api->create_function
90987 #define sqlite3_create_function16      sqlite3_api->create_function16
90988 #define sqlite3_create_module          sqlite3_api->create_module
90989 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
90990 #define sqlite3_data_count             sqlite3_api->data_count
90991 #define sqlite3_db_handle              sqlite3_api->db_handle
90992 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
90993 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
90994 #define sqlite3_errcode                sqlite3_api->errcode
90995 #define sqlite3_errmsg                 sqlite3_api->errmsg
90996 #define sqlite3_errmsg16               sqlite3_api->errmsg16
90997 #define sqlite3_exec                   sqlite3_api->exec
90998 #ifndef SQLITE_OMIT_DEPRECATED
90999 #define sqlite3_expired                sqlite3_api->expired
91000 #endif
91001 #define sqlite3_finalize               sqlite3_api->finalize
91002 #define sqlite3_free                   sqlite3_api->free
91003 #define sqlite3_free_table             sqlite3_api->free_table
91004 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
91005 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
91006 #define sqlite3_get_table              sqlite3_api->get_table
91007 #ifndef SQLITE_OMIT_DEPRECATED
91008 #define sqlite3_global_recover         sqlite3_api->global_recover
91009 #endif
91010 #define sqlite3_interrupt              sqlite3_api->interruptx
91011 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
91012 #define sqlite3_libversion             sqlite3_api->libversion
91013 #define sqlite3_libversion_number      sqlite3_api->libversion_number
91014 #define sqlite3_malloc                 sqlite3_api->malloc
91015 #define sqlite3_mprintf                sqlite3_api->mprintf
91016 #define sqlite3_open                   sqlite3_api->open
91017 #define sqlite3_open16                 sqlite3_api->open16
91018 #define sqlite3_prepare                sqlite3_api->prepare
91019 #define sqlite3_prepare16              sqlite3_api->prepare16
91020 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91021 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91022 #define sqlite3_profile                sqlite3_api->profile
91023 #define sqlite3_progress_handler       sqlite3_api->progress_handler
91024 #define sqlite3_realloc                sqlite3_api->realloc
91025 #define sqlite3_reset                  sqlite3_api->reset
91026 #define sqlite3_result_blob            sqlite3_api->result_blob
91027 #define sqlite3_result_double          sqlite3_api->result_double
91028 #define sqlite3_result_error           sqlite3_api->result_error
91029 #define sqlite3_result_error16         sqlite3_api->result_error16
91030 #define sqlite3_result_int             sqlite3_api->result_int
91031 #define sqlite3_result_int64           sqlite3_api->result_int64
91032 #define sqlite3_result_null            sqlite3_api->result_null
91033 #define sqlite3_result_text            sqlite3_api->result_text
91034 #define sqlite3_result_text16          sqlite3_api->result_text16
91035 #define sqlite3_result_text16be        sqlite3_api->result_text16be
91036 #define sqlite3_result_text16le        sqlite3_api->result_text16le
91037 #define sqlite3_result_value           sqlite3_api->result_value
91038 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
91039 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
91040 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
91041 #define sqlite3_snprintf               sqlite3_api->snprintf
91042 #define sqlite3_step                   sqlite3_api->step
91043 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
91044 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
91045 #define sqlite3_total_changes          sqlite3_api->total_changes
91046 #define sqlite3_trace                  sqlite3_api->trace
91047 #ifndef SQLITE_OMIT_DEPRECATED
91048 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
91049 #endif
91050 #define sqlite3_update_hook            sqlite3_api->update_hook
91051 #define sqlite3_user_data              sqlite3_api->user_data
91052 #define sqlite3_value_blob             sqlite3_api->value_blob
91053 #define sqlite3_value_bytes            sqlite3_api->value_bytes
91054 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
91055 #define sqlite3_value_double           sqlite3_api->value_double
91056 #define sqlite3_value_int              sqlite3_api->value_int
91057 #define sqlite3_value_int64            sqlite3_api->value_int64
91058 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
91059 #define sqlite3_value_text             sqlite3_api->value_text
91060 #define sqlite3_value_text16           sqlite3_api->value_text16
91061 #define sqlite3_value_text16be         sqlite3_api->value_text16be
91062 #define sqlite3_value_text16le         sqlite3_api->value_text16le
91063 #define sqlite3_value_type             sqlite3_api->value_type
91064 #define sqlite3_vmprintf               sqlite3_api->vmprintf
91065 #define sqlite3_overload_function      sqlite3_api->overload_function
91066 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91067 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91068 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
91069 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
91070 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
91071 #define sqlite3_blob_close             sqlite3_api->blob_close
91072 #define sqlite3_blob_open              sqlite3_api->blob_open
91073 #define sqlite3_blob_read              sqlite3_api->blob_read
91074 #define sqlite3_blob_write             sqlite3_api->blob_write
91075 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
91076 #define sqlite3_file_control           sqlite3_api->file_control
91077 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
91078 #define sqlite3_memory_used            sqlite3_api->memory_used
91079 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
91080 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
91081 #define sqlite3_mutex_free             sqlite3_api->mutex_free
91082 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
91083 #define sqlite3_mutex_try              sqlite3_api->mutex_try
91084 #define sqlite3_open_v2                sqlite3_api->open_v2
91085 #define sqlite3_release_memory         sqlite3_api->release_memory
91086 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
91087 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
91088 #define sqlite3_sleep                  sqlite3_api->sleep
91089 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
91090 #define sqlite3_vfs_find               sqlite3_api->vfs_find
91091 #define sqlite3_vfs_register           sqlite3_api->vfs_register
91092 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
91093 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
91094 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
91095 #define sqlite3_result_error_code      sqlite3_api->result_error_code
91096 #define sqlite3_test_control           sqlite3_api->test_control
91097 #define sqlite3_randomness             sqlite3_api->randomness
91098 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
91099 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
91100 #define sqlite3_limit                  sqlite3_api->limit
91101 #define sqlite3_next_stmt              sqlite3_api->next_stmt
91102 #define sqlite3_sql                    sqlite3_api->sql
91103 #define sqlite3_status                 sqlite3_api->status
91104 #define sqlite3_backup_finish          sqlite3_api->backup_finish
91105 #define sqlite3_backup_init            sqlite3_api->backup_init
91106 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
91107 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
91108 #define sqlite3_backup_step            sqlite3_api->backup_step
91109 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
91110 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
91111 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
91112 #define sqlite3_db_config              sqlite3_api->db_config
91113 #define sqlite3_db_mutex               sqlite3_api->db_mutex
91114 #define sqlite3_db_status              sqlite3_api->db_status
91115 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
91116 #define sqlite3_log                    sqlite3_api->log
91117 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
91118 #define sqlite3_sourceid               sqlite3_api->sourceid
91119 #define sqlite3_stmt_status            sqlite3_api->stmt_status
91120 #define sqlite3_strnicmp               sqlite3_api->strnicmp
91121 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
91122 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
91123 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
91124 #define sqlite3_wal_hook               sqlite3_api->wal_hook
91125 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
91126 #define sqlite3_vtab_config            sqlite3_api->vtab_config
91127 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
91128 #endif /* SQLITE_CORE */
91129
91130 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
91131 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
91132
91133 #endif /* _SQLITE3EXT_H_ */
91134
91135 /************** End of sqlite3ext.h ******************************************/
91136 /************** Continuing where we left off in loadext.c ********************/
91137 /* #include <string.h> */
91138
91139 #ifndef SQLITE_OMIT_LOAD_EXTENSION
91140
91141 /*
91142 ** Some API routines are omitted when various features are
91143 ** excluded from a build of SQLite.  Substitute a NULL pointer
91144 ** for any missing APIs.
91145 */
91146 #ifndef SQLITE_ENABLE_COLUMN_METADATA
91147 # define sqlite3_column_database_name   0
91148 # define sqlite3_column_database_name16 0
91149 # define sqlite3_column_table_name      0
91150 # define sqlite3_column_table_name16    0
91151 # define sqlite3_column_origin_name     0
91152 # define sqlite3_column_origin_name16   0
91153 # define sqlite3_table_column_metadata  0
91154 #endif
91155
91156 #ifdef SQLITE_OMIT_AUTHORIZATION
91157 # define sqlite3_set_authorizer         0
91158 #endif
91159
91160 #ifdef SQLITE_OMIT_UTF16
91161 # define sqlite3_bind_text16            0
91162 # define sqlite3_collation_needed16     0
91163 # define sqlite3_column_decltype16      0
91164 # define sqlite3_column_name16          0
91165 # define sqlite3_column_text16          0
91166 # define sqlite3_complete16             0
91167 # define sqlite3_create_collation16     0
91168 # define sqlite3_create_function16      0
91169 # define sqlite3_errmsg16               0
91170 # define sqlite3_open16                 0
91171 # define sqlite3_prepare16              0
91172 # define sqlite3_prepare16_v2           0
91173 # define sqlite3_result_error16         0
91174 # define sqlite3_result_text16          0
91175 # define sqlite3_result_text16be        0
91176 # define sqlite3_result_text16le        0
91177 # define sqlite3_value_text16           0
91178 # define sqlite3_value_text16be         0
91179 # define sqlite3_value_text16le         0
91180 # define sqlite3_column_database_name16 0
91181 # define sqlite3_column_table_name16    0
91182 # define sqlite3_column_origin_name16   0
91183 #endif
91184
91185 #ifdef SQLITE_OMIT_COMPLETE
91186 # define sqlite3_complete 0
91187 # define sqlite3_complete16 0
91188 #endif
91189
91190 #ifdef SQLITE_OMIT_DECLTYPE
91191 # define sqlite3_column_decltype16      0
91192 # define sqlite3_column_decltype        0
91193 #endif
91194
91195 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
91196 # define sqlite3_progress_handler 0
91197 #endif
91198
91199 #ifdef SQLITE_OMIT_VIRTUALTABLE
91200 # define sqlite3_create_module 0
91201 # define sqlite3_create_module_v2 0
91202 # define sqlite3_declare_vtab 0
91203 # define sqlite3_vtab_config 0
91204 # define sqlite3_vtab_on_conflict 0
91205 #endif
91206
91207 #ifdef SQLITE_OMIT_SHARED_CACHE
91208 # define sqlite3_enable_shared_cache 0
91209 #endif
91210
91211 #ifdef SQLITE_OMIT_TRACE
91212 # define sqlite3_profile       0
91213 # define sqlite3_trace         0
91214 #endif
91215
91216 #ifdef SQLITE_OMIT_GET_TABLE
91217 # define sqlite3_free_table    0
91218 # define sqlite3_get_table     0
91219 #endif
91220
91221 #ifdef SQLITE_OMIT_INCRBLOB
91222 #define sqlite3_bind_zeroblob  0
91223 #define sqlite3_blob_bytes     0
91224 #define sqlite3_blob_close     0
91225 #define sqlite3_blob_open      0
91226 #define sqlite3_blob_read      0
91227 #define sqlite3_blob_write     0
91228 #define sqlite3_blob_reopen    0
91229 #endif
91230
91231 /*
91232 ** The following structure contains pointers to all SQLite API routines.
91233 ** A pointer to this structure is passed into extensions when they are
91234 ** loaded so that the extension can make calls back into the SQLite
91235 ** library.
91236 **
91237 ** When adding new APIs, add them to the bottom of this structure
91238 ** in order to preserve backwards compatibility.
91239 **
91240 ** Extensions that use newer APIs should first call the
91241 ** sqlite3_libversion_number() to make sure that the API they
91242 ** intend to use is supported by the library.  Extensions should
91243 ** also check to make sure that the pointer to the function is
91244 ** not NULL before calling it.
91245 */
91246 static const sqlite3_api_routines sqlite3Apis = {
91247   sqlite3_aggregate_context,
91248 #ifndef SQLITE_OMIT_DEPRECATED
91249   sqlite3_aggregate_count,
91250 #else
91251   0,
91252 #endif
91253   sqlite3_bind_blob,
91254   sqlite3_bind_double,
91255   sqlite3_bind_int,
91256   sqlite3_bind_int64,
91257   sqlite3_bind_null,
91258   sqlite3_bind_parameter_count,
91259   sqlite3_bind_parameter_index,
91260   sqlite3_bind_parameter_name,
91261   sqlite3_bind_text,
91262   sqlite3_bind_text16,
91263   sqlite3_bind_value,
91264   sqlite3_busy_handler,
91265   sqlite3_busy_timeout,
91266   sqlite3_changes,
91267   sqlite3_close,
91268   sqlite3_collation_needed,
91269   sqlite3_collation_needed16,
91270   sqlite3_column_blob,
91271   sqlite3_column_bytes,
91272   sqlite3_column_bytes16,
91273   sqlite3_column_count,
91274   sqlite3_column_database_name,
91275   sqlite3_column_database_name16,
91276   sqlite3_column_decltype,
91277   sqlite3_column_decltype16,
91278   sqlite3_column_double,
91279   sqlite3_column_int,
91280   sqlite3_column_int64,
91281   sqlite3_column_name,
91282   sqlite3_column_name16,
91283   sqlite3_column_origin_name,
91284   sqlite3_column_origin_name16,
91285   sqlite3_column_table_name,
91286   sqlite3_column_table_name16,
91287   sqlite3_column_text,
91288   sqlite3_column_text16,
91289   sqlite3_column_type,
91290   sqlite3_column_value,
91291   sqlite3_commit_hook,
91292   sqlite3_complete,
91293   sqlite3_complete16,
91294   sqlite3_create_collation,
91295   sqlite3_create_collation16,
91296   sqlite3_create_function,
91297   sqlite3_create_function16,
91298   sqlite3_create_module,
91299   sqlite3_data_count,
91300   sqlite3_db_handle,
91301   sqlite3_declare_vtab,
91302   sqlite3_enable_shared_cache,
91303   sqlite3_errcode,
91304   sqlite3_errmsg,
91305   sqlite3_errmsg16,
91306   sqlite3_exec,
91307 #ifndef SQLITE_OMIT_DEPRECATED
91308   sqlite3_expired,
91309 #else
91310   0,
91311 #endif
91312   sqlite3_finalize,
91313   sqlite3_free,
91314   sqlite3_free_table,
91315   sqlite3_get_autocommit,
91316   sqlite3_get_auxdata,
91317   sqlite3_get_table,
91318   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
91319   sqlite3_interrupt,
91320   sqlite3_last_insert_rowid,
91321   sqlite3_libversion,
91322   sqlite3_libversion_number,
91323   sqlite3_malloc,
91324   sqlite3_mprintf,
91325   sqlite3_open,
91326   sqlite3_open16,
91327   sqlite3_prepare,
91328   sqlite3_prepare16,
91329   sqlite3_profile,
91330   sqlite3_progress_handler,
91331   sqlite3_realloc,
91332   sqlite3_reset,
91333   sqlite3_result_blob,
91334   sqlite3_result_double,
91335   sqlite3_result_error,
91336   sqlite3_result_error16,
91337   sqlite3_result_int,
91338   sqlite3_result_int64,
91339   sqlite3_result_null,
91340   sqlite3_result_text,
91341   sqlite3_result_text16,
91342   sqlite3_result_text16be,
91343   sqlite3_result_text16le,
91344   sqlite3_result_value,
91345   sqlite3_rollback_hook,
91346   sqlite3_set_authorizer,
91347   sqlite3_set_auxdata,
91348   sqlite3_snprintf,
91349   sqlite3_step,
91350   sqlite3_table_column_metadata,
91351 #ifndef SQLITE_OMIT_DEPRECATED
91352   sqlite3_thread_cleanup,
91353 #else
91354   0,
91355 #endif
91356   sqlite3_total_changes,
91357   sqlite3_trace,
91358 #ifndef SQLITE_OMIT_DEPRECATED
91359   sqlite3_transfer_bindings,
91360 #else
91361   0,
91362 #endif
91363   sqlite3_update_hook,
91364   sqlite3_user_data,
91365   sqlite3_value_blob,
91366   sqlite3_value_bytes,
91367   sqlite3_value_bytes16,
91368   sqlite3_value_double,
91369   sqlite3_value_int,
91370   sqlite3_value_int64,
91371   sqlite3_value_numeric_type,
91372   sqlite3_value_text,
91373   sqlite3_value_text16,
91374   sqlite3_value_text16be,
91375   sqlite3_value_text16le,
91376   sqlite3_value_type,
91377   sqlite3_vmprintf,
91378   /*
91379   ** The original API set ends here.  All extensions can call any
91380   ** of the APIs above provided that the pointer is not NULL.  But
91381   ** before calling APIs that follow, extension should check the
91382   ** sqlite3_libversion_number() to make sure they are dealing with
91383   ** a library that is new enough to support that API.
91384   *************************************************************************
91385   */
91386   sqlite3_overload_function,
91387
91388   /*
91389   ** Added after 3.3.13
91390   */
91391   sqlite3_prepare_v2,
91392   sqlite3_prepare16_v2,
91393   sqlite3_clear_bindings,
91394
91395   /*
91396   ** Added for 3.4.1
91397   */
91398   sqlite3_create_module_v2,
91399
91400   /*
91401   ** Added for 3.5.0
91402   */
91403   sqlite3_bind_zeroblob,
91404   sqlite3_blob_bytes,
91405   sqlite3_blob_close,
91406   sqlite3_blob_open,
91407   sqlite3_blob_read,
91408   sqlite3_blob_write,
91409   sqlite3_create_collation_v2,
91410   sqlite3_file_control,
91411   sqlite3_memory_highwater,
91412   sqlite3_memory_used,
91413 #ifdef SQLITE_MUTEX_OMIT
91414   0, 
91415   0, 
91416   0,
91417   0,
91418   0,
91419 #else
91420   sqlite3_mutex_alloc,
91421   sqlite3_mutex_enter,
91422   sqlite3_mutex_free,
91423   sqlite3_mutex_leave,
91424   sqlite3_mutex_try,
91425 #endif
91426   sqlite3_open_v2,
91427   sqlite3_release_memory,
91428   sqlite3_result_error_nomem,
91429   sqlite3_result_error_toobig,
91430   sqlite3_sleep,
91431   sqlite3_soft_heap_limit,
91432   sqlite3_vfs_find,
91433   sqlite3_vfs_register,
91434   sqlite3_vfs_unregister,
91435
91436   /*
91437   ** Added for 3.5.8
91438   */
91439   sqlite3_threadsafe,
91440   sqlite3_result_zeroblob,
91441   sqlite3_result_error_code,
91442   sqlite3_test_control,
91443   sqlite3_randomness,
91444   sqlite3_context_db_handle,
91445
91446   /*
91447   ** Added for 3.6.0
91448   */
91449   sqlite3_extended_result_codes,
91450   sqlite3_limit,
91451   sqlite3_next_stmt,
91452   sqlite3_sql,
91453   sqlite3_status,
91454
91455   /*
91456   ** Added for 3.7.4
91457   */
91458   sqlite3_backup_finish,
91459   sqlite3_backup_init,
91460   sqlite3_backup_pagecount,
91461   sqlite3_backup_remaining,
91462   sqlite3_backup_step,
91463 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91464   sqlite3_compileoption_get,
91465   sqlite3_compileoption_used,
91466 #else
91467   0,
91468   0,
91469 #endif
91470   sqlite3_create_function_v2,
91471   sqlite3_db_config,
91472   sqlite3_db_mutex,
91473   sqlite3_db_status,
91474   sqlite3_extended_errcode,
91475   sqlite3_log,
91476   sqlite3_soft_heap_limit64,
91477   sqlite3_sourceid,
91478   sqlite3_stmt_status,
91479   sqlite3_strnicmp,
91480 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
91481   sqlite3_unlock_notify,
91482 #else
91483   0,
91484 #endif
91485 #ifndef SQLITE_OMIT_WAL
91486   sqlite3_wal_autocheckpoint,
91487   sqlite3_wal_checkpoint,
91488   sqlite3_wal_hook,
91489 #else
91490   0,
91491   0,
91492   0,
91493 #endif
91494   sqlite3_blob_reopen,
91495   sqlite3_vtab_config,
91496   sqlite3_vtab_on_conflict,
91497 };
91498
91499 /*
91500 ** Attempt to load an SQLite extension library contained in the file
91501 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91502 ** default entry point name (sqlite3_extension_init) is used.  Use
91503 ** of the default name is recommended.
91504 **
91505 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
91506 **
91507 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
91508 ** error message text.  The calling function should free this memory
91509 ** by calling sqlite3DbFree(db, ).
91510 */
91511 static int sqlite3LoadExtension(
91512   sqlite3 *db,          /* Load the extension into this database connection */
91513   const char *zFile,    /* Name of the shared library containing extension */
91514   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91515   char **pzErrMsg       /* Put error message here if not 0 */
91516 ){
91517   sqlite3_vfs *pVfs = db->pVfs;
91518   void *handle;
91519   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91520   char *zErrmsg = 0;
91521   void **aHandle;
91522   int nMsg = 300 + sqlite3Strlen30(zFile);
91523
91524   if( pzErrMsg ) *pzErrMsg = 0;
91525
91526   /* Ticket #1863.  To avoid a creating security problems for older
91527   ** applications that relink against newer versions of SQLite, the
91528   ** ability to run load_extension is turned off by default.  One
91529   ** must call sqlite3_enable_load_extension() to turn on extension
91530   ** loading.  Otherwise you get the following error.
91531   */
91532   if( (db->flags & SQLITE_LoadExtension)==0 ){
91533     if( pzErrMsg ){
91534       *pzErrMsg = sqlite3_mprintf("not authorized");
91535     }
91536     return SQLITE_ERROR;
91537   }
91538
91539   if( zProc==0 ){
91540     zProc = "sqlite3_extension_init";
91541   }
91542
91543   handle = sqlite3OsDlOpen(pVfs, zFile);
91544   if( handle==0 ){
91545     if( pzErrMsg ){
91546       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91547       if( zErrmsg ){
91548         sqlite3_snprintf(nMsg, zErrmsg, 
91549             "unable to open shared library [%s]", zFile);
91550         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91551       }
91552     }
91553     return SQLITE_ERROR;
91554   }
91555   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91556                    sqlite3OsDlSym(pVfs, handle, zProc);
91557   if( xInit==0 ){
91558     if( pzErrMsg ){
91559       nMsg += sqlite3Strlen30(zProc);
91560       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91561       if( zErrmsg ){
91562         sqlite3_snprintf(nMsg, zErrmsg,
91563             "no entry point [%s] in shared library [%s]", zProc,zFile);
91564         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91565       }
91566       sqlite3OsDlClose(pVfs, handle);
91567     }
91568     return SQLITE_ERROR;
91569   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
91570     if( pzErrMsg ){
91571       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
91572     }
91573     sqlite3_free(zErrmsg);
91574     sqlite3OsDlClose(pVfs, handle);
91575     return SQLITE_ERROR;
91576   }
91577
91578   /* Append the new shared library handle to the db->aExtension array. */
91579   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91580   if( aHandle==0 ){
91581     return SQLITE_NOMEM;
91582   }
91583   if( db->nExtension>0 ){
91584     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91585   }
91586   sqlite3DbFree(db, db->aExtension);
91587   db->aExtension = aHandle;
91588
91589   db->aExtension[db->nExtension++] = handle;
91590   return SQLITE_OK;
91591 }
91592 SQLITE_API int sqlite3_load_extension(
91593   sqlite3 *db,          /* Load the extension into this database connection */
91594   const char *zFile,    /* Name of the shared library containing extension */
91595   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91596   char **pzErrMsg       /* Put error message here if not 0 */
91597 ){
91598   int rc;
91599   sqlite3_mutex_enter(db->mutex);
91600   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
91601   rc = sqlite3ApiExit(db, rc);
91602   sqlite3_mutex_leave(db->mutex);
91603   return rc;
91604 }
91605
91606 /*
91607 ** Call this routine when the database connection is closing in order
91608 ** to clean up loaded extensions
91609 */
91610 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
91611   int i;
91612   assert( sqlite3_mutex_held(db->mutex) );
91613   for(i=0; i<db->nExtension; i++){
91614     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
91615   }
91616   sqlite3DbFree(db, db->aExtension);
91617 }
91618
91619 /*
91620 ** Enable or disable extension loading.  Extension loading is disabled by
91621 ** default so as not to open security holes in older applications.
91622 */
91623 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
91624   sqlite3_mutex_enter(db->mutex);
91625   if( onoff ){
91626     db->flags |= SQLITE_LoadExtension;
91627   }else{
91628     db->flags &= ~SQLITE_LoadExtension;
91629   }
91630   sqlite3_mutex_leave(db->mutex);
91631   return SQLITE_OK;
91632 }
91633
91634 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
91635
91636 /*
91637 ** The auto-extension code added regardless of whether or not extension
91638 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
91639 ** code if regular extension loading is not available.  This is that
91640 ** dummy pointer.
91641 */
91642 #ifdef SQLITE_OMIT_LOAD_EXTENSION
91643 static const sqlite3_api_routines sqlite3Apis = { 0 };
91644 #endif
91645
91646
91647 /*
91648 ** The following object holds the list of automatically loaded
91649 ** extensions.
91650 **
91651 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
91652 ** mutex must be held while accessing this list.
91653 */
91654 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
91655 static SQLITE_WSD struct sqlite3AutoExtList {
91656   int nExt;              /* Number of entries in aExt[] */          
91657   void (**aExt)(void);   /* Pointers to the extension init functions */
91658 } sqlite3Autoext = { 0, 0 };
91659
91660 /* The "wsdAutoext" macro will resolve to the autoextension
91661 ** state vector.  If writable static data is unsupported on the target,
91662 ** we have to locate the state vector at run-time.  In the more common
91663 ** case where writable static data is supported, wsdStat can refer directly
91664 ** to the "sqlite3Autoext" state vector declared above.
91665 */
91666 #ifdef SQLITE_OMIT_WSD
91667 # define wsdAutoextInit \
91668   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
91669 # define wsdAutoext x[0]
91670 #else
91671 # define wsdAutoextInit
91672 # define wsdAutoext sqlite3Autoext
91673 #endif
91674
91675
91676 /*
91677 ** Register a statically linked extension that is automatically
91678 ** loaded by every new database connection.
91679 */
91680 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
91681   int rc = SQLITE_OK;
91682 #ifndef SQLITE_OMIT_AUTOINIT
91683   rc = sqlite3_initialize();
91684   if( rc ){
91685     return rc;
91686   }else
91687 #endif
91688   {
91689     int i;
91690 #if SQLITE_THREADSAFE
91691     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91692 #endif
91693     wsdAutoextInit;
91694     sqlite3_mutex_enter(mutex);
91695     for(i=0; i<wsdAutoext.nExt; i++){
91696       if( wsdAutoext.aExt[i]==xInit ) break;
91697     }
91698     if( i==wsdAutoext.nExt ){
91699       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91700       void (**aNew)(void);
91701       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
91702       if( aNew==0 ){
91703         rc = SQLITE_NOMEM;
91704       }else{
91705         wsdAutoext.aExt = aNew;
91706         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91707         wsdAutoext.nExt++;
91708       }
91709     }
91710     sqlite3_mutex_leave(mutex);
91711     assert( (rc&0xff)==rc );
91712     return rc;
91713   }
91714 }
91715
91716 /*
91717 ** Reset the automatic extension loading mechanism.
91718 */
91719 SQLITE_API void sqlite3_reset_auto_extension(void){
91720 #ifndef SQLITE_OMIT_AUTOINIT
91721   if( sqlite3_initialize()==SQLITE_OK )
91722 #endif
91723   {
91724 #if SQLITE_THREADSAFE
91725     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91726 #endif
91727     wsdAutoextInit;
91728     sqlite3_mutex_enter(mutex);
91729     sqlite3_free(wsdAutoext.aExt);
91730     wsdAutoext.aExt = 0;
91731     wsdAutoext.nExt = 0;
91732     sqlite3_mutex_leave(mutex);
91733   }
91734 }
91735
91736 /*
91737 ** Load all automatic extensions.
91738 **
91739 ** If anything goes wrong, set an error in the database connection.
91740 */
91741 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
91742   int i;
91743   int go = 1;
91744   int rc;
91745   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91746
91747   wsdAutoextInit;
91748   if( wsdAutoext.nExt==0 ){
91749     /* Common case: early out without every having to acquire a mutex */
91750     return;
91751   }
91752   for(i=0; go; i++){
91753     char *zErrmsg;
91754 #if SQLITE_THREADSAFE
91755     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91756 #endif
91757     sqlite3_mutex_enter(mutex);
91758     if( i>=wsdAutoext.nExt ){
91759       xInit = 0;
91760       go = 0;
91761     }else{
91762       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91763               wsdAutoext.aExt[i];
91764     }
91765     sqlite3_mutex_leave(mutex);
91766     zErrmsg = 0;
91767     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
91768       sqlite3Error(db, rc,
91769             "automatic extension loading failed: %s", zErrmsg);
91770       go = 0;
91771     }
91772     sqlite3_free(zErrmsg);
91773   }
91774 }
91775
91776 /************** End of loadext.c *********************************************/
91777 /************** Begin file pragma.c ******************************************/
91778 /*
91779 ** 2003 April 6
91780 **
91781 ** The author disclaims copyright to this source code.  In place of
91782 ** a legal notice, here is a blessing:
91783 **
91784 **    May you do good and not evil.
91785 **    May you find forgiveness for yourself and forgive others.
91786 **    May you share freely, never taking more than you give.
91787 **
91788 *************************************************************************
91789 ** This file contains code used to implement the PRAGMA command.
91790 */
91791
91792 /*
91793 ** Interpret the given string as a safety level.  Return 0 for OFF,
91794 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
91795 ** unrecognized string argument.  The FULL option is disallowed
91796 ** if the omitFull parameter it 1.
91797 **
91798 ** Note that the values returned are one less that the values that
91799 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
91800 ** to support legacy SQL code.  The safety level used to be boolean
91801 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
91802 */
91803 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
91804                              /* 123456789 123456789 */
91805   static const char zText[] = "onoffalseyestruefull";
91806   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
91807   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
91808   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
91809   int i, n;
91810   if( sqlite3Isdigit(*z) ){
91811     return (u8)sqlite3Atoi(z);
91812   }
91813   n = sqlite3Strlen30(z);
91814   for(i=0; i<ArraySize(iLength)-omitFull; i++){
91815     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
91816       return iValue[i];
91817     }
91818   }
91819   return dflt;
91820 }
91821
91822 /*
91823 ** Interpret the given string as a boolean value.
91824 */
91825 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
91826   return getSafetyLevel(z,1,dflt)!=0;
91827 }
91828
91829 /* The sqlite3GetBoolean() function is used by other modules but the
91830 ** remainder of this file is specific to PRAGMA processing.  So omit
91831 ** the rest of the file if PRAGMAs are omitted from the build.
91832 */
91833 #if !defined(SQLITE_OMIT_PRAGMA)
91834
91835 /*
91836 ** Interpret the given string as a locking mode value.
91837 */
91838 static int getLockingMode(const char *z){
91839   if( z ){
91840     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
91841     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
91842   }
91843   return PAGER_LOCKINGMODE_QUERY;
91844 }
91845
91846 #ifndef SQLITE_OMIT_AUTOVACUUM
91847 /*
91848 ** Interpret the given string as an auto-vacuum mode value.
91849 **
91850 ** The following strings, "none", "full" and "incremental" are 
91851 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
91852 */
91853 static int getAutoVacuum(const char *z){
91854   int i;
91855   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
91856   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
91857   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
91858   i = sqlite3Atoi(z);
91859   return (u8)((i>=0&&i<=2)?i:0);
91860 }
91861 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
91862
91863 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91864 /*
91865 ** Interpret the given string as a temp db location. Return 1 for file
91866 ** backed temporary databases, 2 for the Red-Black tree in memory database
91867 ** and 0 to use the compile-time default.
91868 */
91869 static int getTempStore(const char *z){
91870   if( z[0]>='0' && z[0]<='2' ){
91871     return z[0] - '0';
91872   }else if( sqlite3StrICmp(z, "file")==0 ){
91873     return 1;
91874   }else if( sqlite3StrICmp(z, "memory")==0 ){
91875     return 2;
91876   }else{
91877     return 0;
91878   }
91879 }
91880 #endif /* SQLITE_PAGER_PRAGMAS */
91881
91882 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91883 /*
91884 ** Invalidate temp storage, either when the temp storage is changed
91885 ** from default, or when 'file' and the temp_store_directory has changed
91886 */
91887 static int invalidateTempStorage(Parse *pParse){
91888   sqlite3 *db = pParse->db;
91889   if( db->aDb[1].pBt!=0 ){
91890     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
91891       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
91892         "from within a transaction");
91893       return SQLITE_ERROR;
91894     }
91895     sqlite3BtreeClose(db->aDb[1].pBt);
91896     db->aDb[1].pBt = 0;
91897     sqlite3ResetAllSchemasOfConnection(db);
91898   }
91899   return SQLITE_OK;
91900 }
91901 #endif /* SQLITE_PAGER_PRAGMAS */
91902
91903 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91904 /*
91905 ** If the TEMP database is open, close it and mark the database schema
91906 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
91907 ** or DEFAULT_TEMP_STORE pragmas.
91908 */
91909 static int changeTempStorage(Parse *pParse, const char *zStorageType){
91910   int ts = getTempStore(zStorageType);
91911   sqlite3 *db = pParse->db;
91912   if( db->temp_store==ts ) return SQLITE_OK;
91913   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
91914     return SQLITE_ERROR;
91915   }
91916   db->temp_store = (u8)ts;
91917   return SQLITE_OK;
91918 }
91919 #endif /* SQLITE_PAGER_PRAGMAS */
91920
91921 /*
91922 ** Generate code to return a single integer value.
91923 */
91924 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
91925   Vdbe *v = sqlite3GetVdbe(pParse);
91926   int mem = ++pParse->nMem;
91927   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
91928   if( pI64 ){
91929     memcpy(pI64, &value, sizeof(value));
91930   }
91931   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
91932   sqlite3VdbeSetNumCols(v, 1);
91933   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
91934   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
91935 }
91936
91937 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
91938 /*
91939 ** Check to see if zRight and zLeft refer to a pragma that queries
91940 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
91941 ** Also, implement the pragma.
91942 */
91943 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
91944   static const struct sPragmaType {
91945     const char *zName;  /* Name of the pragma */
91946     int mask;           /* Mask for the db->flags value */
91947   } aPragma[] = {
91948     { "full_column_names",        SQLITE_FullColNames  },
91949     { "short_column_names",       SQLITE_ShortColNames },
91950     { "count_changes",            SQLITE_CountRows     },
91951     { "empty_result_callbacks",   SQLITE_NullCallback  },
91952     { "legacy_file_format",       SQLITE_LegacyFileFmt },
91953     { "fullfsync",                SQLITE_FullFSync     },
91954     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
91955     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
91956 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
91957     { "automatic_index",          SQLITE_AutoIndex     },
91958 #endif
91959 #ifdef SQLITE_DEBUG
91960     { "sql_trace",                SQLITE_SqlTrace      },
91961     { "vdbe_listing",             SQLITE_VdbeListing   },
91962     { "vdbe_trace",               SQLITE_VdbeTrace     },
91963 #endif
91964 #ifndef SQLITE_OMIT_CHECK
91965     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
91966 #endif
91967     /* The following is VERY experimental */
91968     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
91969
91970     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
91971     ** flag if there are any active statements. */
91972     { "read_uncommitted",         SQLITE_ReadUncommitted },
91973     { "recursive_triggers",       SQLITE_RecTriggers },
91974
91975     /* This flag may only be set if both foreign-key and trigger support
91976     ** are present in the build.  */
91977 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
91978     { "foreign_keys",             SQLITE_ForeignKeys },
91979 #endif
91980   };
91981   int i;
91982   const struct sPragmaType *p;
91983   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
91984     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
91985       sqlite3 *db = pParse->db;
91986       Vdbe *v;
91987       v = sqlite3GetVdbe(pParse);
91988       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
91989       if( ALWAYS(v) ){
91990         if( zRight==0 ){
91991           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
91992         }else{
91993           int mask = p->mask;          /* Mask of bits to set or clear. */
91994           if( db->autoCommit==0 ){
91995             /* Foreign key support may not be enabled or disabled while not
91996             ** in auto-commit mode.  */
91997             mask &= ~(SQLITE_ForeignKeys);
91998           }
91999
92000           if( sqlite3GetBoolean(zRight, 0) ){
92001             db->flags |= mask;
92002           }else{
92003             db->flags &= ~mask;
92004           }
92005
92006           /* Many of the flag-pragmas modify the code generated by the SQL 
92007           ** compiler (eg. count_changes). So add an opcode to expire all
92008           ** compiled SQL statements after modifying a pragma value.
92009           */
92010           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92011         }
92012       }
92013
92014       return 1;
92015     }
92016   }
92017   return 0;
92018 }
92019 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92020
92021 /*
92022 ** Return a human-readable name for a constraint resolution action.
92023 */
92024 #ifndef SQLITE_OMIT_FOREIGN_KEY
92025 static const char *actionName(u8 action){
92026   const char *zName;
92027   switch( action ){
92028     case OE_SetNull:  zName = "SET NULL";        break;
92029     case OE_SetDflt:  zName = "SET DEFAULT";     break;
92030     case OE_Cascade:  zName = "CASCADE";         break;
92031     case OE_Restrict: zName = "RESTRICT";        break;
92032     default:          zName = "NO ACTION";  
92033                       assert( action==OE_None ); break;
92034   }
92035   return zName;
92036 }
92037 #endif
92038
92039
92040 /*
92041 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92042 ** defined in pager.h. This function returns the associated lowercase
92043 ** journal-mode name.
92044 */
92045 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
92046   static char * const azModeName[] = {
92047     "delete", "persist", "off", "truncate", "memory"
92048 #ifndef SQLITE_OMIT_WAL
92049      , "wal"
92050 #endif
92051   };
92052   assert( PAGER_JOURNALMODE_DELETE==0 );
92053   assert( PAGER_JOURNALMODE_PERSIST==1 );
92054   assert( PAGER_JOURNALMODE_OFF==2 );
92055   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92056   assert( PAGER_JOURNALMODE_MEMORY==4 );
92057   assert( PAGER_JOURNALMODE_WAL==5 );
92058   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92059
92060   if( eMode==ArraySize(azModeName) ) return 0;
92061   return azModeName[eMode];
92062 }
92063
92064 /*
92065 ** Process a pragma statement.  
92066 **
92067 ** Pragmas are of this form:
92068 **
92069 **      PRAGMA [database.]id [= value]
92070 **
92071 ** The identifier might also be a string.  The value is a string, and
92072 ** identifier, or a number.  If minusFlag is true, then the value is
92073 ** a number that was preceded by a minus sign.
92074 **
92075 ** If the left side is "database.id" then pId1 is the database name
92076 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
92077 ** id and pId2 is any empty string.
92078 */
92079 SQLITE_PRIVATE void sqlite3Pragma(
92080   Parse *pParse, 
92081   Token *pId1,        /* First part of [database.]id field */
92082   Token *pId2,        /* Second part of [database.]id field, or NULL */
92083   Token *pValue,      /* Token for <value>, or NULL */
92084   int minusFlag       /* True if a '-' sign preceded <value> */
92085 ){
92086   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92087   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92088   const char *zDb = 0;   /* The database name */
92089   Token *pId;            /* Pointer to <id> token */
92090   int iDb;               /* Database index for <database> */
92091   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
92092   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
92093   sqlite3 *db = pParse->db;    /* The database connection */
92094   Db *pDb;                     /* The specific database being pragmaed */
92095   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
92096
92097   if( v==0 ) return;
92098   sqlite3VdbeRunOnlyOnce(v);
92099   pParse->nMem = 2;
92100
92101   /* Interpret the [database.] part of the pragma statement. iDb is the
92102   ** index of the database this pragma is being applied to in db.aDb[]. */
92103   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
92104   if( iDb<0 ) return;
92105   pDb = &db->aDb[iDb];
92106
92107   /* If the temp database has been explicitly named as part of the 
92108   ** pragma, make sure it is open. 
92109   */
92110   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
92111     return;
92112   }
92113
92114   zLeft = sqlite3NameFromToken(db, pId);
92115   if( !zLeft ) return;
92116   if( minusFlag ){
92117     zRight = sqlite3MPrintf(db, "-%T", pValue);
92118   }else{
92119     zRight = sqlite3NameFromToken(db, pValue);
92120   }
92121
92122   assert( pId2 );
92123   zDb = pId2->n>0 ? pDb->zName : 0;
92124   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
92125     goto pragma_out;
92126   }
92127
92128   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
92129   ** connection.  If it returns SQLITE_OK, then assume that the VFS
92130   ** handled the pragma and generate a no-op prepared statement.
92131   */
92132   aFcntl[0] = 0;
92133   aFcntl[1] = zLeft;
92134   aFcntl[2] = zRight;
92135   aFcntl[3] = 0;
92136   db->busyHandler.nBusy = 0;
92137   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
92138   if( rc==SQLITE_OK ){
92139     if( aFcntl[0] ){
92140       int mem = ++pParse->nMem;
92141       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
92142       sqlite3VdbeSetNumCols(v, 1);
92143       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
92144       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92145       sqlite3_free(aFcntl[0]);
92146     }
92147   }else if( rc!=SQLITE_NOTFOUND ){
92148     if( aFcntl[0] ){
92149       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
92150       sqlite3_free(aFcntl[0]);
92151     }
92152     pParse->nErr++;
92153     pParse->rc = rc;
92154   }else
92155                             
92156  
92157 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
92158   /*
92159   **  PRAGMA [database.]default_cache_size
92160   **  PRAGMA [database.]default_cache_size=N
92161   **
92162   ** The first form reports the current persistent setting for the
92163   ** page cache size.  The value returned is the maximum number of
92164   ** pages in the page cache.  The second form sets both the current
92165   ** page cache size value and the persistent page cache size value
92166   ** stored in the database file.
92167   **
92168   ** Older versions of SQLite would set the default cache size to a
92169   ** negative number to indicate synchronous=OFF.  These days, synchronous
92170   ** is always on by default regardless of the sign of the default cache
92171   ** size.  But continue to take the absolute value of the default cache
92172   ** size of historical compatibility.
92173   */
92174   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
92175     static const VdbeOpList getCacheSize[] = {
92176       { OP_Transaction, 0, 0,        0},                         /* 0 */
92177       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92178       { OP_IfPos,       1, 7,        0},
92179       { OP_Integer,     0, 2,        0},
92180       { OP_Subtract,    1, 2,        1},
92181       { OP_IfPos,       1, 7,        0},
92182       { OP_Integer,     0, 1,        0},                         /* 6 */
92183       { OP_ResultRow,   1, 1,        0},
92184     };
92185     int addr;
92186     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92187     sqlite3VdbeUsesBtree(v, iDb);
92188     if( !zRight ){
92189       sqlite3VdbeSetNumCols(v, 1);
92190       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
92191       pParse->nMem += 2;
92192       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92193       sqlite3VdbeChangeP1(v, addr, iDb);
92194       sqlite3VdbeChangeP1(v, addr+1, iDb);
92195       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
92196     }else{
92197       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
92198       sqlite3BeginWriteOperation(pParse, 0, iDb);
92199       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
92200       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92201       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92202       pDb->pSchema->cache_size = size;
92203       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92204     }
92205   }else
92206 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
92207
92208 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
92209   /*
92210   **  PRAGMA [database.]page_size
92211   **  PRAGMA [database.]page_size=N
92212   **
92213   ** The first form reports the current setting for the
92214   ** database page size in bytes.  The second form sets the
92215   ** database page size value.  The value can only be set if
92216   ** the database has not yet been created.
92217   */
92218   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
92219     Btree *pBt = pDb->pBt;
92220     assert( pBt!=0 );
92221     if( !zRight ){
92222       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
92223       returnSingleInt(pParse, "page_size", size);
92224     }else{
92225       /* Malloc may fail when setting the page-size, as there is an internal
92226       ** buffer that the pager module resizes using sqlite3_realloc().
92227       */
92228       db->nextPagesize = sqlite3Atoi(zRight);
92229       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
92230         db->mallocFailed = 1;
92231       }
92232     }
92233   }else
92234
92235   /*
92236   **  PRAGMA [database.]secure_delete
92237   **  PRAGMA [database.]secure_delete=ON/OFF
92238   **
92239   ** The first form reports the current setting for the
92240   ** secure_delete flag.  The second form changes the secure_delete
92241   ** flag setting and reports thenew value.
92242   */
92243   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
92244     Btree *pBt = pDb->pBt;
92245     int b = -1;
92246     assert( pBt!=0 );
92247     if( zRight ){
92248       b = sqlite3GetBoolean(zRight, 0);
92249     }
92250     if( pId2->n==0 && b>=0 ){
92251       int ii;
92252       for(ii=0; ii<db->nDb; ii++){
92253         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
92254       }
92255     }
92256     b = sqlite3BtreeSecureDelete(pBt, b);
92257     returnSingleInt(pParse, "secure_delete", b);
92258   }else
92259
92260   /*
92261   **  PRAGMA [database.]max_page_count
92262   **  PRAGMA [database.]max_page_count=N
92263   **
92264   ** The first form reports the current setting for the
92265   ** maximum number of pages in the database file.  The 
92266   ** second form attempts to change this setting.  Both
92267   ** forms return the current setting.
92268   **
92269   ** The absolute value of N is used.  This is undocumented and might
92270   ** change.  The only purpose is to provide an easy way to test
92271   ** the sqlite3AbsInt32() function.
92272   **
92273   **  PRAGMA [database.]page_count
92274   **
92275   ** Return the number of pages in the specified database.
92276   */
92277   if( sqlite3StrICmp(zLeft,"page_count")==0
92278    || sqlite3StrICmp(zLeft,"max_page_count")==0
92279   ){
92280     int iReg;
92281     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92282     sqlite3CodeVerifySchema(pParse, iDb);
92283     iReg = ++pParse->nMem;
92284     if( sqlite3Tolower(zLeft[0])=='p' ){
92285       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92286     }else{
92287       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
92288                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
92289     }
92290     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92291     sqlite3VdbeSetNumCols(v, 1);
92292     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92293   }else
92294
92295   /*
92296   **  PRAGMA [database.]locking_mode
92297   **  PRAGMA [database.]locking_mode = (normal|exclusive)
92298   */
92299   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
92300     const char *zRet = "normal";
92301     int eMode = getLockingMode(zRight);
92302
92303     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92304       /* Simple "PRAGMA locking_mode;" statement. This is a query for
92305       ** the current default locking mode (which may be different to
92306       ** the locking-mode of the main database).
92307       */
92308       eMode = db->dfltLockMode;
92309     }else{
92310       Pager *pPager;
92311       if( pId2->n==0 ){
92312         /* This indicates that no database name was specified as part
92313         ** of the PRAGMA command. In this case the locking-mode must be
92314         ** set on all attached databases, as well as the main db file.
92315         **
92316         ** Also, the sqlite3.dfltLockMode variable is set so that
92317         ** any subsequently attached databases also use the specified
92318         ** locking mode.
92319         */
92320         int ii;
92321         assert(pDb==&db->aDb[0]);
92322         for(ii=2; ii<db->nDb; ii++){
92323           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
92324           sqlite3PagerLockingMode(pPager, eMode);
92325         }
92326         db->dfltLockMode = (u8)eMode;
92327       }
92328       pPager = sqlite3BtreePager(pDb->pBt);
92329       eMode = sqlite3PagerLockingMode(pPager, eMode);
92330     }
92331
92332     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92333     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92334       zRet = "exclusive";
92335     }
92336     sqlite3VdbeSetNumCols(v, 1);
92337     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
92338     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92339     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92340   }else
92341
92342   /*
92343   **  PRAGMA [database.]journal_mode
92344   **  PRAGMA [database.]journal_mode =
92345   **                      (delete|persist|off|truncate|memory|wal|off)
92346   */
92347   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
92348     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92349     int ii;           /* Loop counter */
92350
92351     /* Force the schema to be loaded on all databases.  This causes all
92352     ** database files to be opened and the journal_modes set.  This is
92353     ** necessary because subsequent processing must know if the databases
92354     ** are in WAL mode. */
92355     if( sqlite3ReadSchema(pParse) ){
92356       goto pragma_out;
92357     }
92358
92359     sqlite3VdbeSetNumCols(v, 1);
92360     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
92361
92362     if( zRight==0 ){
92363       /* If there is no "=MODE" part of the pragma, do a query for the
92364       ** current mode */
92365       eMode = PAGER_JOURNALMODE_QUERY;
92366     }else{
92367       const char *zMode;
92368       int n = sqlite3Strlen30(zRight);
92369       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
92370         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
92371       }
92372       if( !zMode ){
92373         /* If the "=MODE" part does not match any known journal mode,
92374         ** then do a query */
92375         eMode = PAGER_JOURNALMODE_QUERY;
92376       }
92377     }
92378     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92379       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92380       iDb = 0;
92381       pId2->n = 1;
92382     }
92383     for(ii=db->nDb-1; ii>=0; ii--){
92384       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92385         sqlite3VdbeUsesBtree(v, ii);
92386         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92387       }
92388     }
92389     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92390   }else
92391
92392   /*
92393   **  PRAGMA [database.]journal_size_limit
92394   **  PRAGMA [database.]journal_size_limit=N
92395   **
92396   ** Get or set the size limit on rollback journal files.
92397   */
92398   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
92399     Pager *pPager = sqlite3BtreePager(pDb->pBt);
92400     i64 iLimit = -2;
92401     if( zRight ){
92402       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
92403       if( iLimit<-1 ) iLimit = -1;
92404     }
92405     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
92406     returnSingleInt(pParse, "journal_size_limit", iLimit);
92407   }else
92408
92409 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92410
92411   /*
92412   **  PRAGMA [database.]auto_vacuum
92413   **  PRAGMA [database.]auto_vacuum=N
92414   **
92415   ** Get or set the value of the database 'auto-vacuum' parameter.
92416   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92417   */
92418 #ifndef SQLITE_OMIT_AUTOVACUUM
92419   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
92420     Btree *pBt = pDb->pBt;
92421     assert( pBt!=0 );
92422     if( sqlite3ReadSchema(pParse) ){
92423       goto pragma_out;
92424     }
92425     if( !zRight ){
92426       int auto_vacuum;
92427       if( ALWAYS(pBt) ){
92428          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
92429       }else{
92430          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
92431       }
92432       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92433     }else{
92434       int eAuto = getAutoVacuum(zRight);
92435       assert( eAuto>=0 && eAuto<=2 );
92436       db->nextAutovac = (u8)eAuto;
92437       if( ALWAYS(eAuto>=0) ){
92438         /* Call SetAutoVacuum() to set initialize the internal auto and
92439         ** incr-vacuum flags. This is required in case this connection
92440         ** creates the database file. It is important that it is created
92441         ** as an auto-vacuum capable db.
92442         */
92443         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
92444         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
92445           /* When setting the auto_vacuum mode to either "full" or 
92446           ** "incremental", write the value of meta[6] in the database
92447           ** file. Before writing to meta[6], check that meta[3] indicates
92448           ** that this really is an auto-vacuum capable database.
92449           */
92450           static const VdbeOpList setMeta6[] = {
92451             { OP_Transaction,    0,         1,                 0},    /* 0 */
92452             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92453             { OP_If,             1,         0,                 0},    /* 2 */
92454             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
92455             { OP_Integer,        0,         1,                 0},    /* 4 */
92456             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92457           };
92458           int iAddr;
92459           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92460           sqlite3VdbeChangeP1(v, iAddr, iDb);
92461           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
92462           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
92463           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
92464           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
92465           sqlite3VdbeUsesBtree(v, iDb);
92466         }
92467       }
92468     }
92469   }else
92470 #endif
92471
92472   /*
92473   **  PRAGMA [database.]incremental_vacuum(N)
92474   **
92475   ** Do N steps of incremental vacuuming on a database.
92476   */
92477 #ifndef SQLITE_OMIT_AUTOVACUUM
92478   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
92479     int iLimit, addr;
92480     if( sqlite3ReadSchema(pParse) ){
92481       goto pragma_out;
92482     }
92483     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92484       iLimit = 0x7fffffff;
92485     }
92486     sqlite3BeginWriteOperation(pParse, 0, iDb);
92487     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92488     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92489     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
92490     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
92491     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
92492     sqlite3VdbeJumpHere(v, addr);
92493   }else
92494 #endif
92495
92496 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92497   /*
92498   **  PRAGMA [database.]cache_size
92499   **  PRAGMA [database.]cache_size=N
92500   **
92501   ** The first form reports the current local setting for the
92502   ** page cache size. The second form sets the local
92503   ** page cache size value.  If N is positive then that is the
92504   ** number of pages in the cache.  If N is negative, then the
92505   ** number of pages is adjusted so that the cache uses -N kibibytes
92506   ** of memory.
92507   */
92508   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
92509     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92510     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92511     if( !zRight ){
92512       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92513     }else{
92514       int size = sqlite3Atoi(zRight);
92515       pDb->pSchema->cache_size = size;
92516       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92517     }
92518   }else
92519
92520   /*
92521   **   PRAGMA temp_store
92522   **   PRAGMA temp_store = "default"|"memory"|"file"
92523   **
92524   ** Return or set the local value of the temp_store flag.  Changing
92525   ** the local value does not make changes to the disk file and the default
92526   ** value will be restored the next time the database is opened.
92527   **
92528   ** Note that it is possible for the library compile-time options to
92529   ** override this setting
92530   */
92531   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
92532     if( !zRight ){
92533       returnSingleInt(pParse, "temp_store", db->temp_store);
92534     }else{
92535       changeTempStorage(pParse, zRight);
92536     }
92537   }else
92538
92539   /*
92540   **   PRAGMA temp_store_directory
92541   **   PRAGMA temp_store_directory = ""|"directory_name"
92542   **
92543   ** Return or set the local value of the temp_store_directory flag.  Changing
92544   ** the value sets a specific directory to be used for temporary files.
92545   ** Setting to a null string reverts to the default temporary directory search.
92546   ** If temporary directory is changed, then invalidateTempStorage.
92547   **
92548   */
92549   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
92550     if( !zRight ){
92551       if( sqlite3_temp_directory ){
92552         sqlite3VdbeSetNumCols(v, 1);
92553         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92554             "temp_store_directory", SQLITE_STATIC);
92555         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
92556         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92557       }
92558     }else{
92559 #ifndef SQLITE_OMIT_WSD
92560       if( zRight[0] ){
92561         int res;
92562         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92563         if( rc!=SQLITE_OK || res==0 ){
92564           sqlite3ErrorMsg(pParse, "not a writable directory");
92565           goto pragma_out;
92566         }
92567       }
92568       if( SQLITE_TEMP_STORE==0
92569        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
92570        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
92571       ){
92572         invalidateTempStorage(pParse);
92573       }
92574       sqlite3_free(sqlite3_temp_directory);
92575       if( zRight[0] ){
92576         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
92577       }else{
92578         sqlite3_temp_directory = 0;
92579       }
92580 #endif /* SQLITE_OMIT_WSD */
92581     }
92582   }else
92583
92584 #if SQLITE_OS_WIN
92585   /*
92586   **   PRAGMA data_store_directory
92587   **   PRAGMA data_store_directory = ""|"directory_name"
92588   **
92589   ** Return or set the local value of the data_store_directory flag.  Changing
92590   ** the value sets a specific directory to be used for database files that
92591   ** were specified with a relative pathname.  Setting to a null string reverts
92592   ** to the default database directory, which for database files specified with
92593   ** a relative path will probably be based on the current directory for the
92594   ** process.  Database file specified with an absolute path are not impacted
92595   ** by this setting, regardless of its value.
92596   **
92597   */
92598   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
92599     if( !zRight ){
92600       if( sqlite3_data_directory ){
92601         sqlite3VdbeSetNumCols(v, 1);
92602         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92603             "data_store_directory", SQLITE_STATIC);
92604         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
92605         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92606       }
92607     }else{
92608 #ifndef SQLITE_OMIT_WSD
92609       if( zRight[0] ){
92610         int res;
92611         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92612         if( rc!=SQLITE_OK || res==0 ){
92613           sqlite3ErrorMsg(pParse, "not a writable directory");
92614           goto pragma_out;
92615         }
92616       }
92617       sqlite3_free(sqlite3_data_directory);
92618       if( zRight[0] ){
92619         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
92620       }else{
92621         sqlite3_data_directory = 0;
92622       }
92623 #endif /* SQLITE_OMIT_WSD */
92624     }
92625   }else
92626 #endif
92627
92628 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
92629 #  if defined(__APPLE__)
92630 #    define SQLITE_ENABLE_LOCKING_STYLE 1
92631 #  else
92632 #    define SQLITE_ENABLE_LOCKING_STYLE 0
92633 #  endif
92634 #endif
92635 #if SQLITE_ENABLE_LOCKING_STYLE
92636   /*
92637    **   PRAGMA [database.]lock_proxy_file
92638    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92639    **
92640    ** Return or set the value of the lock_proxy_file flag.  Changing
92641    ** the value sets a specific file to be used for database access locks.
92642    **
92643    */
92644   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
92645     if( !zRight ){
92646       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92647       char *proxy_file_path = NULL;
92648       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92649       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
92650                            &proxy_file_path);
92651       
92652       if( proxy_file_path ){
92653         sqlite3VdbeSetNumCols(v, 1);
92654         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
92655                               "lock_proxy_file", SQLITE_STATIC);
92656         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92657         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92658       }
92659     }else{
92660       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92661       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92662       int res;
92663       if( zRight[0] ){
92664         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
92665                                      zRight);
92666       } else {
92667         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
92668                                      NULL);
92669       }
92670       if( res!=SQLITE_OK ){
92671         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
92672         goto pragma_out;
92673       }
92674     }
92675   }else
92676 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
92677     
92678   /*
92679   **   PRAGMA [database.]synchronous
92680   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92681   **
92682   ** Return or set the local value of the synchronous flag.  Changing
92683   ** the local value does not make changes to the disk file and the
92684   ** default value will be restored the next time the database is
92685   ** opened.
92686   */
92687   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
92688     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92689     if( !zRight ){
92690       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92691     }else{
92692       if( !db->autoCommit ){
92693         sqlite3ErrorMsg(pParse, 
92694             "Safety level may not be changed inside a transaction");
92695       }else{
92696         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
92697       }
92698     }
92699   }else
92700 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92701
92702 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
92703   if( flagPragma(pParse, zLeft, zRight) ){
92704     /* The flagPragma() subroutine also generates any necessary code
92705     ** there is nothing more to do here */
92706   }else
92707 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92708
92709 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
92710   /*
92711   **   PRAGMA table_info(<table>)
92712   **
92713   ** Return a single row for each column of the named table. The columns of
92714   ** the returned data set are:
92715   **
92716   ** cid:        Column id (numbered from left to right, starting at 0)
92717   ** name:       Column name
92718   ** type:       Column declaration type.
92719   ** notnull:    True if 'NOT NULL' is part of column declaration
92720   ** dflt_value: The default value for the column, if any.
92721   */
92722   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
92723     Table *pTab;
92724     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92725     pTab = sqlite3FindTable(db, zRight, zDb);
92726     if( pTab ){
92727       int i;
92728       int nHidden = 0;
92729       Column *pCol;
92730       sqlite3VdbeSetNumCols(v, 6);
92731       pParse->nMem = 6;
92732       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
92733       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92734       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
92735       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
92736       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
92737       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
92738       sqlite3ViewGetColumnNames(pParse, pTab);
92739       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92740         if( IsHiddenColumn(pCol) ){
92741           nHidden++;
92742           continue;
92743         }
92744         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
92745         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
92746         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92747            pCol->zType ? pCol->zType : "", 0);
92748         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
92749         if( pCol->zDflt ){
92750           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
92751         }else{
92752           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
92753         }
92754         sqlite3VdbeAddOp2(v, OP_Integer,
92755                             (pCol->colFlags&COLFLAG_PRIMKEY)!=0, 6);
92756         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
92757       }
92758     }
92759   }else
92760
92761   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
92762     Index *pIdx;
92763     Table *pTab;
92764     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92765     pIdx = sqlite3FindIndex(db, zRight, zDb);
92766     if( pIdx ){
92767       int i;
92768       pTab = pIdx->pTable;
92769       sqlite3VdbeSetNumCols(v, 3);
92770       pParse->nMem = 3;
92771       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
92772       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
92773       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
92774       for(i=0; i<pIdx->nColumn; i++){
92775         int cnum = pIdx->aiColumn[i];
92776         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92777         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
92778         assert( pTab->nCol>cnum );
92779         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
92780         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92781       }
92782     }
92783   }else
92784
92785   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
92786     Index *pIdx;
92787     Table *pTab;
92788     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92789     pTab = sqlite3FindTable(db, zRight, zDb);
92790     if( pTab ){
92791       v = sqlite3GetVdbe(pParse);
92792       pIdx = pTab->pIndex;
92793       if( pIdx ){
92794         int i = 0; 
92795         sqlite3VdbeSetNumCols(v, 3);
92796         pParse->nMem = 3;
92797         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92798         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92799         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
92800         while(pIdx){
92801           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92802           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
92803           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
92804           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92805           ++i;
92806           pIdx = pIdx->pNext;
92807         }
92808       }
92809     }
92810   }else
92811
92812   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
92813     int i;
92814     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92815     sqlite3VdbeSetNumCols(v, 3);
92816     pParse->nMem = 3;
92817     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92818     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92819     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
92820     for(i=0; i<db->nDb; i++){
92821       if( db->aDb[i].pBt==0 ) continue;
92822       assert( db->aDb[i].zName!=0 );
92823       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92824       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
92825       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92826            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
92827       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
92828     }
92829   }else
92830
92831   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
92832     int i = 0;
92833     HashElem *p;
92834     sqlite3VdbeSetNumCols(v, 2);
92835     pParse->nMem = 2;
92836     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
92837     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92838     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
92839       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
92840       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
92841       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
92842       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
92843     }
92844   }else
92845 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
92846
92847 #ifndef SQLITE_OMIT_FOREIGN_KEY
92848   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
92849     FKey *pFK;
92850     Table *pTab;
92851     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92852     pTab = sqlite3FindTable(db, zRight, zDb);
92853     if( pTab ){
92854       v = sqlite3GetVdbe(pParse);
92855       pFK = pTab->pFKey;
92856       if( pFK ){
92857         int i = 0; 
92858         sqlite3VdbeSetNumCols(v, 8);
92859         pParse->nMem = 8;
92860         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
92861         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
92862         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
92863         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
92864         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
92865         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
92866         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
92867         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
92868         while(pFK){
92869           int j;
92870           for(j=0; j<pFK->nCol; j++){
92871             char *zCol = pFK->aCol[j].zCol;
92872             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
92873             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
92874             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
92875             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
92876             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
92877             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
92878                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
92879             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
92880             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
92881             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
92882             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
92883             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
92884           }
92885           ++i;
92886           pFK = pFK->pNextFrom;
92887         }
92888       }
92889     }
92890   }else
92891 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
92892
92893 #ifndef NDEBUG
92894   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
92895     if( zRight ){
92896       if( sqlite3GetBoolean(zRight, 0) ){
92897         sqlite3ParserTrace(stderr, "parser: ");
92898       }else{
92899         sqlite3ParserTrace(0, 0);
92900       }
92901     }
92902   }else
92903 #endif
92904
92905   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
92906   ** used will be case sensitive or not depending on the RHS.
92907   */
92908   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
92909     if( zRight ){
92910       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
92911     }
92912   }else
92913
92914 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
92915 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
92916 #endif
92917
92918 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
92919   /* Pragma "quick_check" is an experimental reduced version of 
92920   ** integrity_check designed to detect most database corruption
92921   ** without most of the overhead of a full integrity-check.
92922   */
92923   if( sqlite3StrICmp(zLeft, "integrity_check")==0
92924    || sqlite3StrICmp(zLeft, "quick_check")==0 
92925   ){
92926     int i, j, addr, mxErr;
92927
92928     /* Code that appears at the end of the integrity check.  If no error
92929     ** messages have been generated, output OK.  Otherwise output the
92930     ** error message
92931     */
92932     static const VdbeOpList endCode[] = {
92933       { OP_AddImm,      1, 0,        0},    /* 0 */
92934       { OP_IfNeg,       1, 0,        0},    /* 1 */
92935       { OP_String8,     0, 3,        0},    /* 2 */
92936       { OP_ResultRow,   3, 1,        0},
92937     };
92938
92939     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
92940
92941     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
92942     ** then iDb is set to the index of the database identified by <db>.
92943     ** In this case, the integrity of database iDb only is verified by
92944     ** the VDBE created below.
92945     **
92946     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
92947     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
92948     ** to -1 here, to indicate that the VDBE should verify the integrity
92949     ** of all attached databases.  */
92950     assert( iDb>=0 );
92951     assert( iDb==0 || pId2->z );
92952     if( pId2->z==0 ) iDb = -1;
92953
92954     /* Initialize the VDBE program */
92955     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92956     pParse->nMem = 6;
92957     sqlite3VdbeSetNumCols(v, 1);
92958     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
92959
92960     /* Set the maximum error count */
92961     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
92962     if( zRight ){
92963       sqlite3GetInt32(zRight, &mxErr);
92964       if( mxErr<=0 ){
92965         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
92966       }
92967     }
92968     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
92969
92970     /* Do an integrity check on each database file */
92971     for(i=0; i<db->nDb; i++){
92972       HashElem *x;
92973       Hash *pTbls;
92974       int cnt = 0;
92975
92976       if( OMIT_TEMPDB && i==1 ) continue;
92977       if( iDb>=0 && i!=iDb ) continue;
92978
92979       sqlite3CodeVerifySchema(pParse, i);
92980       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
92981       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
92982       sqlite3VdbeJumpHere(v, addr);
92983
92984       /* Do an integrity check of the B-Tree
92985       **
92986       ** Begin by filling registers 2, 3, ... with the root pages numbers
92987       ** for all tables and indices in the database.
92988       */
92989       assert( sqlite3SchemaMutexHeld(db, i, 0) );
92990       pTbls = &db->aDb[i].pSchema->tblHash;
92991       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
92992         Table *pTab = sqliteHashData(x);
92993         Index *pIdx;
92994         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
92995         cnt++;
92996         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92997           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
92998           cnt++;
92999         }
93000       }
93001
93002       /* Make sure sufficient number of registers have been allocated */
93003       if( pParse->nMem < cnt+4 ){
93004         pParse->nMem = cnt+4;
93005       }
93006
93007       /* Do the b-tree integrity checks */
93008       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
93009       sqlite3VdbeChangeP5(v, (u8)i);
93010       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
93011       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93012          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
93013          P4_DYNAMIC);
93014       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
93015       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
93016       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
93017       sqlite3VdbeJumpHere(v, addr);
93018
93019       /* Make sure all the indices are constructed correctly.
93020       */
93021       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
93022         Table *pTab = sqliteHashData(x);
93023         Index *pIdx;
93024         int loopTop;
93025
93026         if( pTab->pIndex==0 ) continue;
93027         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
93028         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93029         sqlite3VdbeJumpHere(v, addr);
93030         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
93031         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
93032         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
93033         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
93034         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93035           int jmp2;
93036           int r1;
93037           static const VdbeOpList idxErr[] = {
93038             { OP_AddImm,      1, -1,  0},
93039             { OP_String8,     0,  3,  0},    /* 1 */
93040             { OP_Rowid,       1,  4,  0},
93041             { OP_String8,     0,  5,  0},    /* 3 */
93042             { OP_String8,     0,  6,  0},    /* 4 */
93043             { OP_Concat,      4,  3,  3},
93044             { OP_Concat,      5,  3,  3},
93045             { OP_Concat,      6,  3,  3},
93046             { OP_ResultRow,   3,  1,  0},
93047             { OP_IfPos,       1,  0,  0},    /* 9 */
93048             { OP_Halt,        0,  0,  0},
93049           };
93050           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
93051           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
93052           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
93053           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
93054           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
93055           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
93056           sqlite3VdbeJumpHere(v, addr+9);
93057           sqlite3VdbeJumpHere(v, jmp2);
93058         }
93059         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
93060         sqlite3VdbeJumpHere(v, loopTop);
93061         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93062           static const VdbeOpList cntIdx[] = {
93063              { OP_Integer,      0,  3,  0},
93064              { OP_Rewind,       0,  0,  0},  /* 1 */
93065              { OP_AddImm,       3,  1,  0},
93066              { OP_Next,         0,  0,  0},  /* 3 */
93067              { OP_Eq,           2,  0,  3},  /* 4 */
93068              { OP_AddImm,       1, -1,  0},
93069              { OP_String8,      0,  2,  0},  /* 6 */
93070              { OP_String8,      0,  3,  0},  /* 7 */
93071              { OP_Concat,       3,  2,  2},
93072              { OP_ResultRow,    2,  1,  0},
93073           };
93074           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
93075           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93076           sqlite3VdbeJumpHere(v, addr);
93077           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
93078           sqlite3VdbeChangeP1(v, addr+1, j+2);
93079           sqlite3VdbeChangeP2(v, addr+1, addr+4);
93080           sqlite3VdbeChangeP1(v, addr+3, j+2);
93081           sqlite3VdbeChangeP2(v, addr+3, addr+2);
93082           sqlite3VdbeJumpHere(v, addr+4);
93083           sqlite3VdbeChangeP4(v, addr+6, 
93084                      "wrong # of entries in index ", P4_STATIC);
93085           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
93086         }
93087       } 
93088     }
93089     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
93090     sqlite3VdbeChangeP2(v, addr, -mxErr);
93091     sqlite3VdbeJumpHere(v, addr+1);
93092     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
93093   }else
93094 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
93095
93096 #ifndef SQLITE_OMIT_UTF16
93097   /*
93098   **   PRAGMA encoding
93099   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
93100   **
93101   ** In its first form, this pragma returns the encoding of the main
93102   ** database. If the database is not initialized, it is initialized now.
93103   **
93104   ** The second form of this pragma is a no-op if the main database file
93105   ** has not already been initialized. In this case it sets the default
93106   ** encoding that will be used for the main database file if a new file
93107   ** is created. If an existing main database file is opened, then the
93108   ** default text encoding for the existing database is used.
93109   ** 
93110   ** In all cases new databases created using the ATTACH command are
93111   ** created to use the same default text encoding as the main database. If
93112   ** the main database has not been initialized and/or created when ATTACH
93113   ** is executed, this is done before the ATTACH operation.
93114   **
93115   ** In the second form this pragma sets the text encoding to be used in
93116   ** new database files created using this database handle. It is only
93117   ** useful if invoked immediately after the main database i
93118   */
93119   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
93120     static const struct EncName {
93121       char *zName;
93122       u8 enc;
93123     } encnames[] = {
93124       { "UTF8",     SQLITE_UTF8        },
93125       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
93126       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
93127       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
93128       { "UTF16le",  SQLITE_UTF16LE     },
93129       { "UTF16be",  SQLITE_UTF16BE     },
93130       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
93131       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
93132       { 0, 0 }
93133     };
93134     const struct EncName *pEnc;
93135     if( !zRight ){    /* "PRAGMA encoding" */
93136       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93137       sqlite3VdbeSetNumCols(v, 1);
93138       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
93139       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
93140       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
93141       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
93142       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
93143       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93144       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93145     }else{                        /* "PRAGMA encoding = XXX" */
93146       /* Only change the value of sqlite.enc if the database handle is not
93147       ** initialized. If the main database exists, the new sqlite.enc value
93148       ** will be overwritten when the schema is next loaded. If it does not
93149       ** already exists, it will be created to use the new encoding value.
93150       */
93151       if( 
93152         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
93153         DbHasProperty(db, 0, DB_Empty) 
93154       ){
93155         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93156           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
93157             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
93158             break;
93159           }
93160         }
93161         if( !pEnc->zName ){
93162           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93163         }
93164       }
93165     }
93166   }else
93167 #endif /* SQLITE_OMIT_UTF16 */
93168
93169 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
93170   /*
93171   **   PRAGMA [database.]schema_version
93172   **   PRAGMA [database.]schema_version = <integer>
93173   **
93174   **   PRAGMA [database.]user_version
93175   **   PRAGMA [database.]user_version = <integer>
93176   **
93177   ** The pragma's schema_version and user_version are used to set or get
93178   ** the value of the schema-version and user-version, respectively. Both
93179   ** the schema-version and the user-version are 32-bit signed integers
93180   ** stored in the database header.
93181   **
93182   ** The schema-cookie is usually only manipulated internally by SQLite. It
93183   ** is incremented by SQLite whenever the database schema is modified (by
93184   ** creating or dropping a table or index). The schema version is used by
93185   ** SQLite each time a query is executed to ensure that the internal cache
93186   ** of the schema used when compiling the SQL query matches the schema of
93187   ** the database against which the compiled query is actually executed.
93188   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93189   ** the schema-version is potentially dangerous and may lead to program
93190   ** crashes or database corruption. Use with caution!
93191   **
93192   ** The user-version is not used internally by SQLite. It may be used by
93193   ** applications for any purpose.
93194   */
93195   if( sqlite3StrICmp(zLeft, "schema_version")==0 
93196    || sqlite3StrICmp(zLeft, "user_version")==0 
93197    || sqlite3StrICmp(zLeft, "freelist_count")==0 
93198   ){
93199     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93200     sqlite3VdbeUsesBtree(v, iDb);
93201     switch( zLeft[0] ){
93202       case 'f': case 'F':
93203         iCookie = BTREE_FREE_PAGE_COUNT;
93204         break;
93205       case 's': case 'S':
93206         iCookie = BTREE_SCHEMA_VERSION;
93207         break;
93208       default:
93209         iCookie = BTREE_USER_VERSION;
93210         break;
93211     }
93212
93213     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93214       /* Write the specified cookie value */
93215       static const VdbeOpList setCookie[] = {
93216         { OP_Transaction,    0,  1,  0},    /* 0 */
93217         { OP_Integer,        0,  1,  0},    /* 1 */
93218         { OP_SetCookie,      0,  0,  1},    /* 2 */
93219       };
93220       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93221       sqlite3VdbeChangeP1(v, addr, iDb);
93222       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
93223       sqlite3VdbeChangeP1(v, addr+2, iDb);
93224       sqlite3VdbeChangeP2(v, addr+2, iCookie);
93225     }else{
93226       /* Read the specified cookie value */
93227       static const VdbeOpList readCookie[] = {
93228         { OP_Transaction,     0,  0,  0},    /* 0 */
93229         { OP_ReadCookie,      0,  1,  0},    /* 1 */
93230         { OP_ResultRow,       1,  1,  0}
93231       };
93232       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93233       sqlite3VdbeChangeP1(v, addr, iDb);
93234       sqlite3VdbeChangeP1(v, addr+1, iDb);
93235       sqlite3VdbeChangeP3(v, addr+1, iCookie);
93236       sqlite3VdbeSetNumCols(v, 1);
93237       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93238     }
93239   }else
93240 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
93241
93242 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93243   /*
93244   **   PRAGMA compile_options
93245   **
93246   ** Return the names of all compile-time options used in this build,
93247   ** one option per row.
93248   */
93249   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
93250     int i = 0;
93251     const char *zOpt;
93252     sqlite3VdbeSetNumCols(v, 1);
93253     pParse->nMem = 1;
93254     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
93255     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
93256       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93257       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93258     }
93259   }else
93260 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
93261
93262 #ifndef SQLITE_OMIT_WAL
93263   /*
93264   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93265   **
93266   ** Checkpoint the database.
93267   */
93268   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
93269     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
93270     int eMode = SQLITE_CHECKPOINT_PASSIVE;
93271     if( zRight ){
93272       if( sqlite3StrICmp(zRight, "full")==0 ){
93273         eMode = SQLITE_CHECKPOINT_FULL;
93274       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
93275         eMode = SQLITE_CHECKPOINT_RESTART;
93276       }
93277     }
93278     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93279     sqlite3VdbeSetNumCols(v, 3);
93280     pParse->nMem = 3;
93281     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
93282     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
93283     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
93284
93285     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93286     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93287   }else
93288
93289   /*
93290   **   PRAGMA wal_autocheckpoint
93291   **   PRAGMA wal_autocheckpoint = N
93292   **
93293   ** Configure a database connection to automatically checkpoint a database
93294   ** after accumulating N frames in the log. Or query for the current value
93295   ** of N.
93296   */
93297   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93298     if( zRight ){
93299       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
93300     }
93301     returnSingleInt(pParse, "wal_autocheckpoint", 
93302        db->xWalCallback==sqlite3WalDefaultHook ? 
93303            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
93304   }else
93305 #endif
93306
93307   /*
93308   **  PRAGMA shrink_memory
93309   **
93310   ** This pragma attempts to free as much memory as possible from the
93311   ** current database connection.
93312   */
93313   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
93314     sqlite3_db_release_memory(db);
93315   }else
93316
93317   /*
93318   **   PRAGMA busy_timeout
93319   **   PRAGMA busy_timeout = N
93320   **
93321   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
93322   ** if one is set.  If no busy handler or a different busy handler is set
93323   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
93324   ** disables the timeout.
93325   */
93326   if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
93327     if( zRight ){
93328       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
93329     }
93330     returnSingleInt(pParse, "timeout",  db->busyTimeout);
93331   }else
93332
93333 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
93334   /*
93335   ** Report the current state of file logs for all databases
93336   */
93337   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
93338     static const char *const azLockName[] = {
93339       "unlocked", "shared", "reserved", "pending", "exclusive"
93340     };
93341     int i;
93342     sqlite3VdbeSetNumCols(v, 2);
93343     pParse->nMem = 2;
93344     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
93345     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
93346     for(i=0; i<db->nDb; i++){
93347       Btree *pBt;
93348       const char *zState = "unknown";
93349       int j;
93350       if( db->aDb[i].zName==0 ) continue;
93351       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93352       pBt = db->aDb[i].pBt;
93353       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
93354         zState = "closed";
93355       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
93356                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
93357          zState = azLockName[j];
93358       }
93359       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93360       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93361     }
93362
93363   }else
93364 #endif
93365
93366 #ifdef SQLITE_HAS_CODEC
93367   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
93368     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
93369   }else
93370   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
93371     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
93372   }else
93373   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
93374                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
93375     int i, h1, h2;
93376     char zKey[40];
93377     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93378       h1 += 9*(1&(h1>>6));
93379       h2 += 9*(1&(h2>>6));
93380       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93381     }
93382     if( (zLeft[3] & 0xf)==0xb ){
93383       sqlite3_key(db, zKey, i/2);
93384     }else{
93385       sqlite3_rekey(db, zKey, i/2);
93386     }
93387   }else
93388 #endif
93389 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
93390   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
93391 #ifdef SQLITE_HAS_CODEC
93392     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
93393       sqlite3_activate_see(&zRight[4]);
93394     }
93395 #endif
93396 #ifdef SQLITE_ENABLE_CEROD
93397     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
93398       sqlite3_activate_cerod(&zRight[6]);
93399     }
93400 #endif
93401   }else
93402 #endif
93403
93404  
93405   {/* Empty ELSE clause */}
93406
93407   /*
93408   ** Reset the safety level, in case the fullfsync flag or synchronous
93409   ** setting changed.
93410   */
93411 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93412   if( db->autoCommit ){
93413     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93414                (db->flags&SQLITE_FullFSync)!=0,
93415                (db->flags&SQLITE_CkptFullFSync)!=0);
93416   }
93417 #endif
93418 pragma_out:
93419   sqlite3DbFree(db, zLeft);
93420   sqlite3DbFree(db, zRight);
93421 }
93422
93423 #endif /* SQLITE_OMIT_PRAGMA */
93424
93425 /************** End of pragma.c **********************************************/
93426 /************** Begin file prepare.c *****************************************/
93427 /*
93428 ** 2005 May 25
93429 **
93430 ** The author disclaims copyright to this source code.  In place of
93431 ** a legal notice, here is a blessing:
93432 **
93433 **    May you do good and not evil.
93434 **    May you find forgiveness for yourself and forgive others.
93435 **    May you share freely, never taking more than you give.
93436 **
93437 *************************************************************************
93438 ** This file contains the implementation of the sqlite3_prepare()
93439 ** interface, and routines that contribute to loading the database schema
93440 ** from disk.
93441 */
93442
93443 /*
93444 ** Fill the InitData structure with an error message that indicates
93445 ** that the database is corrupt.
93446 */
93447 static void corruptSchema(
93448   InitData *pData,     /* Initialization context */
93449   const char *zObj,    /* Object being parsed at the point of error */
93450   const char *zExtra   /* Error information */
93451 ){
93452   sqlite3 *db = pData->db;
93453   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
93454     if( zObj==0 ) zObj = "?";
93455     sqlite3SetString(pData->pzErrMsg, db,
93456       "malformed database schema (%s)", zObj);
93457     if( zExtra ){
93458       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
93459                                  "%s - %s", *pData->pzErrMsg, zExtra);
93460     }
93461   }
93462   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
93463 }
93464
93465 /*
93466 ** This is the callback routine for the code that initializes the
93467 ** database.  See sqlite3Init() below for additional information.
93468 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93469 **
93470 ** Each callback contains the following information:
93471 **
93472 **     argv[0] = name of thing being created
93473 **     argv[1] = root page number for table or index. 0 for trigger or view.
93474 **     argv[2] = SQL text for the CREATE statement.
93475 **
93476 */
93477 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93478   InitData *pData = (InitData*)pInit;
93479   sqlite3 *db = pData->db;
93480   int iDb = pData->iDb;
93481
93482   assert( argc==3 );
93483   UNUSED_PARAMETER2(NotUsed, argc);
93484   assert( sqlite3_mutex_held(db->mutex) );
93485   DbClearProperty(db, iDb, DB_Empty);
93486   if( db->mallocFailed ){
93487     corruptSchema(pData, argv[0], 0);
93488     return 1;
93489   }
93490
93491   assert( iDb>=0 && iDb<db->nDb );
93492   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93493   if( argv[1]==0 ){
93494     corruptSchema(pData, argv[0], 0);
93495   }else if( argv[2] && argv[2][0] ){
93496     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93497     ** But because db->init.busy is set to 1, no VDBE code is generated
93498     ** or executed.  All the parser does is build the internal data
93499     ** structures that describe the table, index, or view.
93500     */
93501     int rc;
93502     sqlite3_stmt *pStmt;
93503     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
93504
93505     assert( db->init.busy );
93506     db->init.iDb = iDb;
93507     db->init.newTnum = sqlite3Atoi(argv[1]);
93508     db->init.orphanTrigger = 0;
93509     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
93510     rc = db->errCode;
93511     assert( (rc&0xFF)==(rcp&0xFF) );
93512     db->init.iDb = 0;
93513     if( SQLITE_OK!=rc ){
93514       if( db->init.orphanTrigger ){
93515         assert( iDb==1 );
93516       }else{
93517         pData->rc = rc;
93518         if( rc==SQLITE_NOMEM ){
93519           db->mallocFailed = 1;
93520         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
93521           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
93522         }
93523       }
93524     }
93525     sqlite3_finalize(pStmt);
93526   }else if( argv[0]==0 ){
93527     corruptSchema(pData, 0, 0);
93528   }else{
93529     /* If the SQL column is blank it means this is an index that
93530     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93531     ** constraint for a CREATE TABLE.  The index should have already
93532     ** been created when we processed the CREATE TABLE.  All we have
93533     ** to do here is record the root page number for that index.
93534     */
93535     Index *pIndex;
93536     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
93537     if( pIndex==0 ){
93538       /* This can occur if there exists an index on a TEMP table which
93539       ** has the same name as another index on a permanent index.  Since
93540       ** the permanent table is hidden by the TEMP table, we can also
93541       ** safely ignore the index on the permanent table.
93542       */
93543       /* Do Nothing */;
93544     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
93545       corruptSchema(pData, argv[0], "invalid rootpage");
93546     }
93547   }
93548   return 0;
93549 }
93550
93551 /*
93552 ** Attempt to read the database schema and initialize internal
93553 ** data structures for a single database file.  The index of the
93554 ** database file is given by iDb.  iDb==0 is used for the main
93555 ** database.  iDb==1 should never be used.  iDb>=2 is used for
93556 ** auxiliary databases.  Return one of the SQLITE_ error codes to
93557 ** indicate success or failure.
93558 */
93559 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
93560   int rc;
93561   int i;
93562 #ifndef SQLITE_OMIT_DEPRECATED
93563   int size;
93564 #endif
93565   Table *pTab;
93566   Db *pDb;
93567   char const *azArg[4];
93568   int meta[5];
93569   InitData initData;
93570   char const *zMasterSchema;
93571   char const *zMasterName;
93572   int openedTransaction = 0;
93573
93574   /*
93575   ** The master database table has a structure like this
93576   */
93577   static const char master_schema[] = 
93578      "CREATE TABLE sqlite_master(\n"
93579      "  type text,\n"
93580      "  name text,\n"
93581      "  tbl_name text,\n"
93582      "  rootpage integer,\n"
93583      "  sql text\n"
93584      ")"
93585   ;
93586 #ifndef SQLITE_OMIT_TEMPDB
93587   static const char temp_master_schema[] = 
93588      "CREATE TEMP TABLE sqlite_temp_master(\n"
93589      "  type text,\n"
93590      "  name text,\n"
93591      "  tbl_name text,\n"
93592      "  rootpage integer,\n"
93593      "  sql text\n"
93594      ")"
93595   ;
93596 #else
93597   #define temp_master_schema 0
93598 #endif
93599
93600   assert( iDb>=0 && iDb<db->nDb );
93601   assert( db->aDb[iDb].pSchema );
93602   assert( sqlite3_mutex_held(db->mutex) );
93603   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
93604
93605   /* zMasterSchema and zInitScript are set to point at the master schema
93606   ** and initialisation script appropriate for the database being
93607   ** initialised. zMasterName is the name of the master table.
93608   */
93609   if( !OMIT_TEMPDB && iDb==1 ){
93610     zMasterSchema = temp_master_schema;
93611   }else{
93612     zMasterSchema = master_schema;
93613   }
93614   zMasterName = SCHEMA_TABLE(iDb);
93615
93616   /* Construct the schema tables.  */
93617   azArg[0] = zMasterName;
93618   azArg[1] = "1";
93619   azArg[2] = zMasterSchema;
93620   azArg[3] = 0;
93621   initData.db = db;
93622   initData.iDb = iDb;
93623   initData.rc = SQLITE_OK;
93624   initData.pzErrMsg = pzErrMsg;
93625   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
93626   if( initData.rc ){
93627     rc = initData.rc;
93628     goto error_out;
93629   }
93630   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
93631   if( ALWAYS(pTab) ){
93632     pTab->tabFlags |= TF_Readonly;
93633   }
93634
93635   /* Create a cursor to hold the database open
93636   */
93637   pDb = &db->aDb[iDb];
93638   if( pDb->pBt==0 ){
93639     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
93640       DbSetProperty(db, 1, DB_SchemaLoaded);
93641     }
93642     return SQLITE_OK;
93643   }
93644
93645   /* If there is not already a read-only (or read-write) transaction opened
93646   ** on the b-tree database, open one now. If a transaction is opened, it 
93647   ** will be closed before this function returns.  */
93648   sqlite3BtreeEnter(pDb->pBt);
93649   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
93650     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
93651     if( rc!=SQLITE_OK ){
93652       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
93653       goto initone_error_out;
93654     }
93655     openedTransaction = 1;
93656   }
93657
93658   /* Get the database meta information.
93659   **
93660   ** Meta values are as follows:
93661   **    meta[0]   Schema cookie.  Changes with each schema change.
93662   **    meta[1]   File format of schema layer.
93663   **    meta[2]   Size of the page cache.
93664   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
93665   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
93666   **    meta[5]   User version
93667   **    meta[6]   Incremental vacuum mode
93668   **    meta[7]   unused
93669   **    meta[8]   unused
93670   **    meta[9]   unused
93671   **
93672   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
93673   ** the possible values of meta[4].
93674   */
93675   for(i=0; i<ArraySize(meta); i++){
93676     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
93677   }
93678   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
93679
93680   /* If opening a non-empty database, check the text encoding. For the
93681   ** main database, set sqlite3.enc to the encoding of the main database.
93682   ** For an attached db, it is an error if the encoding is not the same
93683   ** as sqlite3.enc.
93684   */
93685   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
93686     if( iDb==0 ){
93687       u8 encoding;
93688       /* If opening the main database, set ENC(db). */
93689       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
93690       if( encoding==0 ) encoding = SQLITE_UTF8;
93691       ENC(db) = encoding;
93692     }else{
93693       /* If opening an attached database, the encoding much match ENC(db) */
93694       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
93695         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
93696             " text encoding as main database");
93697         rc = SQLITE_ERROR;
93698         goto initone_error_out;
93699       }
93700     }
93701   }else{
93702     DbSetProperty(db, iDb, DB_Empty);
93703   }
93704   pDb->pSchema->enc = ENC(db);
93705
93706   if( pDb->pSchema->cache_size==0 ){
93707 #ifndef SQLITE_OMIT_DEPRECATED
93708     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
93709     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
93710     pDb->pSchema->cache_size = size;
93711 #else
93712     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
93713 #endif
93714     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93715   }
93716
93717   /*
93718   ** file_format==1    Version 3.0.0.
93719   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
93720   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
93721   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
93722   */
93723   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
93724   if( pDb->pSchema->file_format==0 ){
93725     pDb->pSchema->file_format = 1;
93726   }
93727   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
93728     sqlite3SetString(pzErrMsg, db, "unsupported file format");
93729     rc = SQLITE_ERROR;
93730     goto initone_error_out;
93731   }
93732
93733   /* Ticket #2804:  When we open a database in the newer file format,
93734   ** clear the legacy_file_format pragma flag so that a VACUUM will
93735   ** not downgrade the database and thus invalidate any descending
93736   ** indices that the user might have created.
93737   */
93738   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93739     db->flags &= ~SQLITE_LegacyFileFmt;
93740   }
93741
93742   /* Read the schema information out of the schema tables
93743   */
93744   assert( db->init.busy );
93745   {
93746     char *zSql;
93747     zSql = sqlite3MPrintf(db, 
93748         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93749         db->aDb[iDb].zName, zMasterName);
93750 #ifndef SQLITE_OMIT_AUTHORIZATION
93751     {
93752       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93753       xAuth = db->xAuth;
93754       db->xAuth = 0;
93755 #endif
93756       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
93757 #ifndef SQLITE_OMIT_AUTHORIZATION
93758       db->xAuth = xAuth;
93759     }
93760 #endif
93761     if( rc==SQLITE_OK ) rc = initData.rc;
93762     sqlite3DbFree(db, zSql);
93763 #ifndef SQLITE_OMIT_ANALYZE
93764     if( rc==SQLITE_OK ){
93765       sqlite3AnalysisLoad(db, iDb);
93766     }
93767 #endif
93768   }
93769   if( db->mallocFailed ){
93770     rc = SQLITE_NOMEM;
93771     sqlite3ResetAllSchemasOfConnection(db);
93772   }
93773   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
93774     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
93775     ** the schema loaded, even if errors occurred. In this situation the 
93776     ** current sqlite3_prepare() operation will fail, but the following one
93777     ** will attempt to compile the supplied statement against whatever subset
93778     ** of the schema was loaded before the error occurred. The primary
93779     ** purpose of this is to allow access to the sqlite_master table
93780     ** even when its contents have been corrupted.
93781     */
93782     DbSetProperty(db, iDb, DB_SchemaLoaded);
93783     rc = SQLITE_OK;
93784   }
93785
93786   /* Jump here for an error that occurs after successfully allocating
93787   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
93788   ** before that point, jump to error_out.
93789   */
93790 initone_error_out:
93791   if( openedTransaction ){
93792     sqlite3BtreeCommit(pDb->pBt);
93793   }
93794   sqlite3BtreeLeave(pDb->pBt);
93795
93796 error_out:
93797   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
93798     db->mallocFailed = 1;
93799   }
93800   return rc;
93801 }
93802
93803 /*
93804 ** Initialize all database files - the main database file, the file
93805 ** used to store temporary tables, and any additional database files
93806 ** created using ATTACH statements.  Return a success code.  If an
93807 ** error occurs, write an error message into *pzErrMsg.
93808 **
93809 ** After a database is initialized, the DB_SchemaLoaded bit is set
93810 ** bit is set in the flags field of the Db structure. If the database
93811 ** file was of zero-length, then the DB_Empty flag is also set.
93812 */
93813 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
93814   int i, rc;
93815   int commit_internal = !(db->flags&SQLITE_InternChanges);
93816   
93817   assert( sqlite3_mutex_held(db->mutex) );
93818   rc = SQLITE_OK;
93819   db->init.busy = 1;
93820   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
93821     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
93822     rc = sqlite3InitOne(db, i, pzErrMsg);
93823     if( rc ){
93824       sqlite3ResetOneSchema(db, i);
93825     }
93826   }
93827
93828   /* Once all the other databases have been initialised, load the schema
93829   ** for the TEMP database. This is loaded last, as the TEMP database
93830   ** schema may contain references to objects in other databases.
93831   */
93832 #ifndef SQLITE_OMIT_TEMPDB
93833   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
93834                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
93835     rc = sqlite3InitOne(db, 1, pzErrMsg);
93836     if( rc ){
93837       sqlite3ResetOneSchema(db, 1);
93838     }
93839   }
93840 #endif
93841
93842   db->init.busy = 0;
93843   if( rc==SQLITE_OK && commit_internal ){
93844     sqlite3CommitInternalChanges(db);
93845   }
93846
93847   return rc; 
93848 }
93849
93850 /*
93851 ** This routine is a no-op if the database schema is already initialised.
93852 ** Otherwise, the schema is loaded. An error code is returned.
93853 */
93854 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
93855   int rc = SQLITE_OK;
93856   sqlite3 *db = pParse->db;
93857   assert( sqlite3_mutex_held(db->mutex) );
93858   if( !db->init.busy ){
93859     rc = sqlite3Init(db, &pParse->zErrMsg);
93860   }
93861   if( rc!=SQLITE_OK ){
93862     pParse->rc = rc;
93863     pParse->nErr++;
93864   }
93865   return rc;
93866 }
93867
93868
93869 /*
93870 ** Check schema cookies in all databases.  If any cookie is out
93871 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
93872 ** make no changes to pParse->rc.
93873 */
93874 static void schemaIsValid(Parse *pParse){
93875   sqlite3 *db = pParse->db;
93876   int iDb;
93877   int rc;
93878   int cookie;
93879
93880   assert( pParse->checkSchema );
93881   assert( sqlite3_mutex_held(db->mutex) );
93882   for(iDb=0; iDb<db->nDb; iDb++){
93883     int openedTransaction = 0;         /* True if a transaction is opened */
93884     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
93885     if( pBt==0 ) continue;
93886
93887     /* If there is not already a read-only (or read-write) transaction opened
93888     ** on the b-tree database, open one now. If a transaction is opened, it 
93889     ** will be closed immediately after reading the meta-value. */
93890     if( !sqlite3BtreeIsInReadTrans(pBt) ){
93891       rc = sqlite3BtreeBeginTrans(pBt, 0);
93892       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
93893         db->mallocFailed = 1;
93894       }
93895       if( rc!=SQLITE_OK ) return;
93896       openedTransaction = 1;
93897     }
93898
93899     /* Read the schema cookie from the database. If it does not match the 
93900     ** value stored as part of the in-memory schema representation,
93901     ** set Parse.rc to SQLITE_SCHEMA. */
93902     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
93903     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93904     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
93905       sqlite3ResetOneSchema(db, iDb);
93906       pParse->rc = SQLITE_SCHEMA;
93907     }
93908
93909     /* Close the transaction, if one was opened. */
93910     if( openedTransaction ){
93911       sqlite3BtreeCommit(pBt);
93912     }
93913   }
93914 }
93915
93916 /*
93917 ** Convert a schema pointer into the iDb index that indicates
93918 ** which database file in db->aDb[] the schema refers to.
93919 **
93920 ** If the same database is attached more than once, the first
93921 ** attached database is returned.
93922 */
93923 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
93924   int i = -1000000;
93925
93926   /* If pSchema is NULL, then return -1000000. This happens when code in 
93927   ** expr.c is trying to resolve a reference to a transient table (i.e. one
93928   ** created by a sub-select). In this case the return value of this 
93929   ** function should never be used.
93930   **
93931   ** We return -1000000 instead of the more usual -1 simply because using
93932   ** -1000000 as the incorrect index into db->aDb[] is much 
93933   ** more likely to cause a segfault than -1 (of course there are assert()
93934   ** statements too, but it never hurts to play the odds).
93935   */
93936   assert( sqlite3_mutex_held(db->mutex) );
93937   if( pSchema ){
93938     for(i=0; ALWAYS(i<db->nDb); i++){
93939       if( db->aDb[i].pSchema==pSchema ){
93940         break;
93941       }
93942     }
93943     assert( i>=0 && i<db->nDb );
93944   }
93945   return i;
93946 }
93947
93948 /*
93949 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
93950 */
93951 static int sqlite3Prepare(
93952   sqlite3 *db,              /* Database handle. */
93953   const char *zSql,         /* UTF-8 encoded SQL statement. */
93954   int nBytes,               /* Length of zSql in bytes. */
93955   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
93956   Vdbe *pReprepare,         /* VM being reprepared */
93957   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
93958   const char **pzTail       /* OUT: End of parsed string */
93959 ){
93960   Parse *pParse;            /* Parsing context */
93961   char *zErrMsg = 0;        /* Error message */
93962   int rc = SQLITE_OK;       /* Result code */
93963   int i;                    /* Loop counter */
93964
93965   /* Allocate the parsing context */
93966   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
93967   if( pParse==0 ){
93968     rc = SQLITE_NOMEM;
93969     goto end_prepare;
93970   }
93971   pParse->pReprepare = pReprepare;
93972   assert( ppStmt && *ppStmt==0 );
93973   assert( !db->mallocFailed );
93974   assert( sqlite3_mutex_held(db->mutex) );
93975
93976   /* Check to verify that it is possible to get a read lock on all
93977   ** database schemas.  The inability to get a read lock indicates that
93978   ** some other database connection is holding a write-lock, which in
93979   ** turn means that the other connection has made uncommitted changes
93980   ** to the schema.
93981   **
93982   ** Were we to proceed and prepare the statement against the uncommitted
93983   ** schema changes and if those schema changes are subsequently rolled
93984   ** back and different changes are made in their place, then when this
93985   ** prepared statement goes to run the schema cookie would fail to detect
93986   ** the schema change.  Disaster would follow.
93987   **
93988   ** This thread is currently holding mutexes on all Btrees (because
93989   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
93990   ** is not possible for another thread to start a new schema change
93991   ** while this routine is running.  Hence, we do not need to hold 
93992   ** locks on the schema, we just need to make sure nobody else is 
93993   ** holding them.
93994   **
93995   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
93996   ** but it does *not* override schema lock detection, so this all still
93997   ** works even if READ_UNCOMMITTED is set.
93998   */
93999   for(i=0; i<db->nDb; i++) {
94000     Btree *pBt = db->aDb[i].pBt;
94001     if( pBt ){
94002       assert( sqlite3BtreeHoldsMutex(pBt) );
94003       rc = sqlite3BtreeSchemaLocked(pBt);
94004       if( rc ){
94005         const char *zDb = db->aDb[i].zName;
94006         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
94007         testcase( db->flags & SQLITE_ReadUncommitted );
94008         goto end_prepare;
94009       }
94010     }
94011   }
94012
94013   sqlite3VtabUnlockList(db);
94014
94015   pParse->db = db;
94016   pParse->nQueryLoop = (double)1;
94017   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
94018     char *zSqlCopy;
94019     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94020     testcase( nBytes==mxLen );
94021     testcase( nBytes==mxLen+1 );
94022     if( nBytes>mxLen ){
94023       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
94024       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
94025       goto end_prepare;
94026     }
94027     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
94028     if( zSqlCopy ){
94029       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
94030       sqlite3DbFree(db, zSqlCopy);
94031       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
94032     }else{
94033       pParse->zTail = &zSql[nBytes];
94034     }
94035   }else{
94036     sqlite3RunParser(pParse, zSql, &zErrMsg);
94037   }
94038   assert( 1==(int)pParse->nQueryLoop );
94039
94040   if( db->mallocFailed ){
94041     pParse->rc = SQLITE_NOMEM;
94042   }
94043   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
94044   if( pParse->checkSchema ){
94045     schemaIsValid(pParse);
94046   }
94047   if( db->mallocFailed ){
94048     pParse->rc = SQLITE_NOMEM;
94049   }
94050   if( pzTail ){
94051     *pzTail = pParse->zTail;
94052   }
94053   rc = pParse->rc;
94054
94055 #ifndef SQLITE_OMIT_EXPLAIN
94056   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
94057     static const char * const azColName[] = {
94058        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
94059        "selectid", "order", "from", "detail"
94060     };
94061     int iFirst, mx;
94062     if( pParse->explain==2 ){
94063       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
94064       iFirst = 8;
94065       mx = 12;
94066     }else{
94067       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
94068       iFirst = 0;
94069       mx = 8;
94070     }
94071     for(i=iFirst; i<mx; i++){
94072       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
94073                             azColName[i], SQLITE_STATIC);
94074     }
94075   }
94076 #endif
94077
94078   assert( db->init.busy==0 || saveSqlFlag==0 );
94079   if( db->init.busy==0 ){
94080     Vdbe *pVdbe = pParse->pVdbe;
94081     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
94082   }
94083   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
94084     sqlite3VdbeFinalize(pParse->pVdbe);
94085     assert(!(*ppStmt));
94086   }else{
94087     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
94088   }
94089
94090   if( zErrMsg ){
94091     sqlite3Error(db, rc, "%s", zErrMsg);
94092     sqlite3DbFree(db, zErrMsg);
94093   }else{
94094     sqlite3Error(db, rc, 0);
94095   }
94096
94097   /* Delete any TriggerPrg structures allocated while parsing this statement. */
94098   while( pParse->pTriggerPrg ){
94099     TriggerPrg *pT = pParse->pTriggerPrg;
94100     pParse->pTriggerPrg = pT->pNext;
94101     sqlite3DbFree(db, pT);
94102   }
94103
94104 end_prepare:
94105
94106   sqlite3StackFree(db, pParse);
94107   rc = sqlite3ApiExit(db, rc);
94108   assert( (rc&db->errMask)==rc );
94109   return rc;
94110 }
94111 static int sqlite3LockAndPrepare(
94112   sqlite3 *db,              /* Database handle. */
94113   const char *zSql,         /* UTF-8 encoded SQL statement. */
94114   int nBytes,               /* Length of zSql in bytes. */
94115   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94116   Vdbe *pOld,               /* VM being reprepared */
94117   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94118   const char **pzTail       /* OUT: End of parsed string */
94119 ){
94120   int rc;
94121   assert( ppStmt!=0 );
94122   *ppStmt = 0;
94123   if( !sqlite3SafetyCheckOk(db) ){
94124     return SQLITE_MISUSE_BKPT;
94125   }
94126   sqlite3_mutex_enter(db->mutex);
94127   sqlite3BtreeEnterAll(db);
94128   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94129   if( rc==SQLITE_SCHEMA ){
94130     sqlite3_finalize(*ppStmt);
94131     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94132   }
94133   sqlite3BtreeLeaveAll(db);
94134   sqlite3_mutex_leave(db->mutex);
94135   assert( rc==SQLITE_OK || *ppStmt==0 );
94136   return rc;
94137 }
94138
94139 /*
94140 ** Rerun the compilation of a statement after a schema change.
94141 **
94142 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
94143 ** if the statement cannot be recompiled because another connection has
94144 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
94145 ** occurs, return SQLITE_SCHEMA.
94146 */
94147 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
94148   int rc;
94149   sqlite3_stmt *pNew;
94150   const char *zSql;
94151   sqlite3 *db;
94152
94153   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
94154   zSql = sqlite3_sql((sqlite3_stmt *)p);
94155   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94156   db = sqlite3VdbeDb(p);
94157   assert( sqlite3_mutex_held(db->mutex) );
94158   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94159   if( rc ){
94160     if( rc==SQLITE_NOMEM ){
94161       db->mallocFailed = 1;
94162     }
94163     assert( pNew==0 );
94164     return rc;
94165   }else{
94166     assert( pNew!=0 );
94167   }
94168   sqlite3VdbeSwap((Vdbe*)pNew, p);
94169   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
94170   sqlite3VdbeResetStepResult((Vdbe*)pNew);
94171   sqlite3VdbeFinalize((Vdbe*)pNew);
94172   return SQLITE_OK;
94173 }
94174
94175
94176 /*
94177 ** Two versions of the official API.  Legacy and new use.  In the legacy
94178 ** version, the original SQL text is not saved in the prepared statement
94179 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94180 ** sqlite3_step().  In the new version, the original SQL text is retained
94181 ** and the statement is automatically recompiled if an schema change
94182 ** occurs.
94183 */
94184 SQLITE_API int sqlite3_prepare(
94185   sqlite3 *db,              /* Database handle. */
94186   const char *zSql,         /* UTF-8 encoded SQL statement. */
94187   int nBytes,               /* Length of zSql in bytes. */
94188   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94189   const char **pzTail       /* OUT: End of parsed string */
94190 ){
94191   int rc;
94192   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94193   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94194   return rc;
94195 }
94196 SQLITE_API int sqlite3_prepare_v2(
94197   sqlite3 *db,              /* Database handle. */
94198   const char *zSql,         /* UTF-8 encoded SQL statement. */
94199   int nBytes,               /* Length of zSql in bytes. */
94200   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94201   const char **pzTail       /* OUT: End of parsed string */
94202 ){
94203   int rc;
94204   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94205   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94206   return rc;
94207 }
94208
94209
94210 #ifndef SQLITE_OMIT_UTF16
94211 /*
94212 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94213 */
94214 static int sqlite3Prepare16(
94215   sqlite3 *db,              /* Database handle. */ 
94216   const void *zSql,         /* UTF-16 encoded SQL statement. */
94217   int nBytes,               /* Length of zSql in bytes. */
94218   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
94219   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94220   const void **pzTail       /* OUT: End of parsed string */
94221 ){
94222   /* This function currently works by first transforming the UTF-16
94223   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
94224   ** tricky bit is figuring out the pointer to return in *pzTail.
94225   */
94226   char *zSql8;
94227   const char *zTail8 = 0;
94228   int rc = SQLITE_OK;
94229
94230   assert( ppStmt );
94231   *ppStmt = 0;
94232   if( !sqlite3SafetyCheckOk(db) ){
94233     return SQLITE_MISUSE_BKPT;
94234   }
94235   sqlite3_mutex_enter(db->mutex);
94236   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
94237   if( zSql8 ){
94238     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94239   }
94240
94241   if( zTail8 && pzTail ){
94242     /* If sqlite3_prepare returns a tail pointer, we calculate the
94243     ** equivalent pointer into the UTF-16 string by counting the unicode
94244     ** characters between zSql8 and zTail8, and then returning a pointer
94245     ** the same number of characters into the UTF-16 string.
94246     */
94247     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94248     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
94249   }
94250   sqlite3DbFree(db, zSql8); 
94251   rc = sqlite3ApiExit(db, rc);
94252   sqlite3_mutex_leave(db->mutex);
94253   return rc;
94254 }
94255
94256 /*
94257 ** Two versions of the official API.  Legacy and new use.  In the legacy
94258 ** version, the original SQL text is not saved in the prepared statement
94259 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94260 ** sqlite3_step().  In the new version, the original SQL text is retained
94261 ** and the statement is automatically recompiled if an schema change
94262 ** occurs.
94263 */
94264 SQLITE_API int sqlite3_prepare16(
94265   sqlite3 *db,              /* Database handle. */ 
94266   const void *zSql,         /* UTF-16 encoded SQL statement. */
94267   int nBytes,               /* Length of zSql in bytes. */
94268   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94269   const void **pzTail       /* OUT: End of parsed string */
94270 ){
94271   int rc;
94272   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94273   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94274   return rc;
94275 }
94276 SQLITE_API int sqlite3_prepare16_v2(
94277   sqlite3 *db,              /* Database handle. */ 
94278   const void *zSql,         /* UTF-16 encoded SQL statement. */
94279   int nBytes,               /* Length of zSql in bytes. */
94280   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94281   const void **pzTail       /* OUT: End of parsed string */
94282 ){
94283   int rc;
94284   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94285   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94286   return rc;
94287 }
94288
94289 #endif /* SQLITE_OMIT_UTF16 */
94290
94291 /************** End of prepare.c *********************************************/
94292 /************** Begin file select.c ******************************************/
94293 /*
94294 ** 2001 September 15
94295 **
94296 ** The author disclaims copyright to this source code.  In place of
94297 ** a legal notice, here is a blessing:
94298 **
94299 **    May you do good and not evil.
94300 **    May you find forgiveness for yourself and forgive others.
94301 **    May you share freely, never taking more than you give.
94302 **
94303 *************************************************************************
94304 ** This file contains C code routines that are called by the parser
94305 ** to handle SELECT statements in SQLite.
94306 */
94307
94308
94309 /*
94310 ** Delete all the content of a Select structure but do not deallocate
94311 ** the select structure itself.
94312 */
94313 static void clearSelect(sqlite3 *db, Select *p){
94314   sqlite3ExprListDelete(db, p->pEList);
94315   sqlite3SrcListDelete(db, p->pSrc);
94316   sqlite3ExprDelete(db, p->pWhere);
94317   sqlite3ExprListDelete(db, p->pGroupBy);
94318   sqlite3ExprDelete(db, p->pHaving);
94319   sqlite3ExprListDelete(db, p->pOrderBy);
94320   sqlite3SelectDelete(db, p->pPrior);
94321   sqlite3ExprDelete(db, p->pLimit);
94322   sqlite3ExprDelete(db, p->pOffset);
94323 }
94324
94325 /*
94326 ** Initialize a SelectDest structure.
94327 */
94328 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94329   pDest->eDest = (u8)eDest;
94330   pDest->iSDParm = iParm;
94331   pDest->affSdst = 0;
94332   pDest->iSdst = 0;
94333   pDest->nSdst = 0;
94334 }
94335
94336
94337 /*
94338 ** Allocate a new Select structure and return a pointer to that
94339 ** structure.
94340 */
94341 SQLITE_PRIVATE Select *sqlite3SelectNew(
94342   Parse *pParse,        /* Parsing context */
94343   ExprList *pEList,     /* which columns to include in the result */
94344   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94345   Expr *pWhere,         /* the WHERE clause */
94346   ExprList *pGroupBy,   /* the GROUP BY clause */
94347   Expr *pHaving,        /* the HAVING clause */
94348   ExprList *pOrderBy,   /* the ORDER BY clause */
94349   int isDistinct,       /* true if the DISTINCT keyword is present */
94350   Expr *pLimit,         /* LIMIT value.  NULL means not used */
94351   Expr *pOffset         /* OFFSET value.  NULL means no offset */
94352 ){
94353   Select *pNew;
94354   Select standin;
94355   sqlite3 *db = pParse->db;
94356   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
94357   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94358   if( pNew==0 ){
94359     assert( db->mallocFailed );
94360     pNew = &standin;
94361     memset(pNew, 0, sizeof(*pNew));
94362   }
94363   if( pEList==0 ){
94364     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
94365   }
94366   pNew->pEList = pEList;
94367   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
94368   pNew->pSrc = pSrc;
94369   pNew->pWhere = pWhere;
94370   pNew->pGroupBy = pGroupBy;
94371   pNew->pHaving = pHaving;
94372   pNew->pOrderBy = pOrderBy;
94373   pNew->selFlags = isDistinct ? SF_Distinct : 0;
94374   pNew->op = TK_SELECT;
94375   pNew->pLimit = pLimit;
94376   pNew->pOffset = pOffset;
94377   assert( pOffset==0 || pLimit!=0 );
94378   pNew->addrOpenEphm[0] = -1;
94379   pNew->addrOpenEphm[1] = -1;
94380   pNew->addrOpenEphm[2] = -1;
94381   if( db->mallocFailed ) {
94382     clearSelect(db, pNew);
94383     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94384     pNew = 0;
94385   }else{
94386     assert( pNew->pSrc!=0 || pParse->nErr>0 );
94387   }
94388   assert( pNew!=&standin );
94389   return pNew;
94390 }
94391
94392 /*
94393 ** Delete the given Select structure and all of its substructures.
94394 */
94395 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
94396   if( p ){
94397     clearSelect(db, p);
94398     sqlite3DbFree(db, p);
94399   }
94400 }
94401
94402 /*
94403 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94404 ** type of join.  Return an integer constant that expresses that type
94405 ** in terms of the following bit values:
94406 **
94407 **     JT_INNER
94408 **     JT_CROSS
94409 **     JT_OUTER
94410 **     JT_NATURAL
94411 **     JT_LEFT
94412 **     JT_RIGHT
94413 **
94414 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94415 **
94416 ** If an illegal or unsupported join type is seen, then still return
94417 ** a join type, but put an error in the pParse structure.
94418 */
94419 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94420   int jointype = 0;
94421   Token *apAll[3];
94422   Token *p;
94423                              /*   0123456789 123456789 123456789 123 */
94424   static const char zKeyText[] = "naturaleftouterightfullinnercross";
94425   static const struct {
94426     u8 i;        /* Beginning of keyword text in zKeyText[] */
94427     u8 nChar;    /* Length of the keyword in characters */
94428     u8 code;     /* Join type mask */
94429   } aKeyword[] = {
94430     /* natural */ { 0,  7, JT_NATURAL                },
94431     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94432     /* outer   */ { 10, 5, JT_OUTER                  },
94433     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94434     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94435     /* inner   */ { 23, 5, JT_INNER                  },
94436     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94437   };
94438   int i, j;
94439   apAll[0] = pA;
94440   apAll[1] = pB;
94441   apAll[2] = pC;
94442   for(i=0; i<3 && apAll[i]; i++){
94443     p = apAll[i];
94444     for(j=0; j<ArraySize(aKeyword); j++){
94445       if( p->n==aKeyword[j].nChar 
94446           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94447         jointype |= aKeyword[j].code;
94448         break;
94449       }
94450     }
94451     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94452     if( j>=ArraySize(aKeyword) ){
94453       jointype |= JT_ERROR;
94454       break;
94455     }
94456   }
94457   if(
94458      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94459      (jointype & JT_ERROR)!=0
94460   ){
94461     const char *zSp = " ";
94462     assert( pB!=0 );
94463     if( pC==0 ){ zSp++; }
94464     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
94465        "%T %T%s%T", pA, pB, zSp, pC);
94466     jointype = JT_INNER;
94467   }else if( (jointype & JT_OUTER)!=0 
94468          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94469     sqlite3ErrorMsg(pParse, 
94470       "RIGHT and FULL OUTER JOINs are not currently supported");
94471     jointype = JT_INNER;
94472   }
94473   return jointype;
94474 }
94475
94476 /*
94477 ** Return the index of a column in a table.  Return -1 if the column
94478 ** is not contained in the table.
94479 */
94480 static int columnIndex(Table *pTab, const char *zCol){
94481   int i;
94482   for(i=0; i<pTab->nCol; i++){
94483     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94484   }
94485   return -1;
94486 }
94487
94488 /*
94489 ** Search the first N tables in pSrc, from left to right, looking for a
94490 ** table that has a column named zCol.  
94491 **
94492 ** When found, set *piTab and *piCol to the table index and column index
94493 ** of the matching column and return TRUE.
94494 **
94495 ** If not found, return FALSE.
94496 */
94497 static int tableAndColumnIndex(
94498   SrcList *pSrc,       /* Array of tables to search */
94499   int N,               /* Number of tables in pSrc->a[] to search */
94500   const char *zCol,    /* Name of the column we are looking for */
94501   int *piTab,          /* Write index of pSrc->a[] here */
94502   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94503 ){
94504   int i;               /* For looping over tables in pSrc */
94505   int iCol;            /* Index of column matching zCol */
94506
94507   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94508   for(i=0; i<N; i++){
94509     iCol = columnIndex(pSrc->a[i].pTab, zCol);
94510     if( iCol>=0 ){
94511       if( piTab ){
94512         *piTab = i;
94513         *piCol = iCol;
94514       }
94515       return 1;
94516     }
94517   }
94518   return 0;
94519 }
94520
94521 /*
94522 ** This function is used to add terms implied by JOIN syntax to the
94523 ** WHERE clause expression of a SELECT statement. The new term, which
94524 ** is ANDed with the existing WHERE clause, is of the form:
94525 **
94526 **    (tab1.col1 = tab2.col2)
94527 **
94528 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
94529 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94530 ** column iColRight of tab2.
94531 */
94532 static void addWhereTerm(
94533   Parse *pParse,                  /* Parsing context */
94534   SrcList *pSrc,                  /* List of tables in FROM clause */
94535   int iLeft,                      /* Index of first table to join in pSrc */
94536   int iColLeft,                   /* Index of column in first table */
94537   int iRight,                     /* Index of second table in pSrc */
94538   int iColRight,                  /* Index of column in second table */
94539   int isOuterJoin,                /* True if this is an OUTER join */
94540   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94541 ){
94542   sqlite3 *db = pParse->db;
94543   Expr *pE1;
94544   Expr *pE2;
94545   Expr *pEq;
94546
94547   assert( iLeft<iRight );
94548   assert( pSrc->nSrc>iRight );
94549   assert( pSrc->a[iLeft].pTab );
94550   assert( pSrc->a[iRight].pTab );
94551
94552   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94553   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
94554
94555   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94556   if( pEq && isOuterJoin ){
94557     ExprSetProperty(pEq, EP_FromJoin);
94558     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94559     ExprSetIrreducible(pEq);
94560     pEq->iRightJoinTable = (i16)pE2->iTable;
94561   }
94562   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
94563 }
94564
94565 /*
94566 ** Set the EP_FromJoin property on all terms of the given expression.
94567 ** And set the Expr.iRightJoinTable to iTable for every term in the
94568 ** expression.
94569 **
94570 ** The EP_FromJoin property is used on terms of an expression to tell
94571 ** the LEFT OUTER JOIN processing logic that this term is part of the
94572 ** join restriction specified in the ON or USING clause and not a part
94573 ** of the more general WHERE clause.  These terms are moved over to the
94574 ** WHERE clause during join processing but we need to remember that they
94575 ** originated in the ON or USING clause.
94576 **
94577 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
94578 ** expression depends on table iRightJoinTable even if that table is not
94579 ** explicitly mentioned in the expression.  That information is needed
94580 ** for cases like this:
94581 **
94582 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
94583 **
94584 ** The where clause needs to defer the handling of the t1.x=5
94585 ** term until after the t2 loop of the join.  In that way, a
94586 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
94587 ** defer the handling of t1.x=5, it will be processed immediately
94588 ** after the t1 loop and rows with t1.x!=5 will never appear in
94589 ** the output, which is incorrect.
94590 */
94591 static void setJoinExpr(Expr *p, int iTable){
94592   while( p ){
94593     ExprSetProperty(p, EP_FromJoin);
94594     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
94595     ExprSetIrreducible(p);
94596     p->iRightJoinTable = (i16)iTable;
94597     setJoinExpr(p->pLeft, iTable);
94598     p = p->pRight;
94599   } 
94600 }
94601
94602 /*
94603 ** This routine processes the join information for a SELECT statement.
94604 ** ON and USING clauses are converted into extra terms of the WHERE clause.
94605 ** NATURAL joins also create extra WHERE clause terms.
94606 **
94607 ** The terms of a FROM clause are contained in the Select.pSrc structure.
94608 ** The left most table is the first entry in Select.pSrc.  The right-most
94609 ** table is the last entry.  The join operator is held in the entry to
94610 ** the left.  Thus entry 0 contains the join operator for the join between
94611 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
94612 ** also attached to the left entry.
94613 **
94614 ** This routine returns the number of errors encountered.
94615 */
94616 static int sqliteProcessJoin(Parse *pParse, Select *p){
94617   SrcList *pSrc;                  /* All tables in the FROM clause */
94618   int i, j;                       /* Loop counters */
94619   struct SrcList_item *pLeft;     /* Left table being joined */
94620   struct SrcList_item *pRight;    /* Right table being joined */
94621
94622   pSrc = p->pSrc;
94623   pLeft = &pSrc->a[0];
94624   pRight = &pLeft[1];
94625   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
94626     Table *pLeftTab = pLeft->pTab;
94627     Table *pRightTab = pRight->pTab;
94628     int isOuter;
94629
94630     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
94631     isOuter = (pRight->jointype & JT_OUTER)!=0;
94632
94633     /* When the NATURAL keyword is present, add WHERE clause terms for
94634     ** every column that the two tables have in common.
94635     */
94636     if( pRight->jointype & JT_NATURAL ){
94637       if( pRight->pOn || pRight->pUsing ){
94638         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
94639            "an ON or USING clause", 0);
94640         return 1;
94641       }
94642       for(j=0; j<pRightTab->nCol; j++){
94643         char *zName;   /* Name of column in the right table */
94644         int iLeft;     /* Matching left table */
94645         int iLeftCol;  /* Matching column in the left table */
94646
94647         zName = pRightTab->aCol[j].zName;
94648         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
94649           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
94650                        isOuter, &p->pWhere);
94651         }
94652       }
94653     }
94654
94655     /* Disallow both ON and USING clauses in the same join
94656     */
94657     if( pRight->pOn && pRight->pUsing ){
94658       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
94659         "clauses in the same join");
94660       return 1;
94661     }
94662
94663     /* Add the ON clause to the end of the WHERE clause, connected by
94664     ** an AND operator.
94665     */
94666     if( pRight->pOn ){
94667       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
94668       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
94669       pRight->pOn = 0;
94670     }
94671
94672     /* Create extra terms on the WHERE clause for each column named
94673     ** in the USING clause.  Example: If the two tables to be joined are 
94674     ** A and B and the USING clause names X, Y, and Z, then add this
94675     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
94676     ** Report an error if any column mentioned in the USING clause is
94677     ** not contained in both tables to be joined.
94678     */
94679     if( pRight->pUsing ){
94680       IdList *pList = pRight->pUsing;
94681       for(j=0; j<pList->nId; j++){
94682         char *zName;     /* Name of the term in the USING clause */
94683         int iLeft;       /* Table on the left with matching column name */
94684         int iLeftCol;    /* Column number of matching column on the left */
94685         int iRightCol;   /* Column number of matching column on the right */
94686
94687         zName = pList->a[j].zName;
94688         iRightCol = columnIndex(pRightTab, zName);
94689         if( iRightCol<0
94690          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
94691         ){
94692           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
94693             "not present in both tables", zName);
94694           return 1;
94695         }
94696         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
94697                      isOuter, &p->pWhere);
94698       }
94699     }
94700   }
94701   return 0;
94702 }
94703
94704 /*
94705 ** Insert code into "v" that will push the record on the top of the
94706 ** stack into the sorter.
94707 */
94708 static void pushOntoSorter(
94709   Parse *pParse,         /* Parser context */
94710   ExprList *pOrderBy,    /* The ORDER BY clause */
94711   Select *pSelect,       /* The whole SELECT statement */
94712   int regData            /* Register holding data to be sorted */
94713 ){
94714   Vdbe *v = pParse->pVdbe;
94715   int nExpr = pOrderBy->nExpr;
94716   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
94717   int regRecord = sqlite3GetTempReg(pParse);
94718   int op;
94719   sqlite3ExprCacheClear(pParse);
94720   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
94721   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
94722   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
94723   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
94724   if( pSelect->selFlags & SF_UseSorter ){
94725     op = OP_SorterInsert;
94726   }else{
94727     op = OP_IdxInsert;
94728   }
94729   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94730   sqlite3ReleaseTempReg(pParse, regRecord);
94731   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
94732   if( pSelect->iLimit ){
94733     int addr1, addr2;
94734     int iLimit;
94735     if( pSelect->iOffset ){
94736       iLimit = pSelect->iOffset+1;
94737     }else{
94738       iLimit = pSelect->iLimit;
94739     }
94740     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
94741     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94742     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
94743     sqlite3VdbeJumpHere(v, addr1);
94744     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94745     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94746     sqlite3VdbeJumpHere(v, addr2);
94747   }
94748 }
94749
94750 /*
94751 ** Add code to implement the OFFSET
94752 */
94753 static void codeOffset(
94754   Vdbe *v,          /* Generate code into this VM */
94755   Select *p,        /* The SELECT statement being coded */
94756   int iContinue     /* Jump here to skip the current record */
94757 ){
94758   if( p->iOffset && iContinue!=0 ){
94759     int addr;
94760     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94761     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94762     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94763     VdbeComment((v, "skip OFFSET records"));
94764     sqlite3VdbeJumpHere(v, addr);
94765   }
94766 }
94767
94768 /*
94769 ** Add code that will check to make sure the N registers starting at iMem
94770 ** form a distinct entry.  iTab is a sorting index that holds previously
94771 ** seen combinations of the N values.  A new entry is made in iTab
94772 ** if the current N values are new.
94773 **
94774 ** A jump to addrRepeat is made and the N+1 values are popped from the
94775 ** stack if the top N elements are not distinct.
94776 */
94777 static void codeDistinct(
94778   Parse *pParse,     /* Parsing and code generating context */
94779   int iTab,          /* A sorting index used to test for distinctness */
94780   int addrRepeat,    /* Jump to here if not distinct */
94781   int N,             /* Number of elements */
94782   int iMem           /* First element */
94783 ){
94784   Vdbe *v;
94785   int r1;
94786
94787   v = pParse->pVdbe;
94788   r1 = sqlite3GetTempReg(pParse);
94789   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
94790   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
94791   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
94792   sqlite3ReleaseTempReg(pParse, r1);
94793 }
94794
94795 #ifndef SQLITE_OMIT_SUBQUERY
94796 /*
94797 ** Generate an error message when a SELECT is used within a subexpression
94798 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
94799 ** column.  We do this in a subroutine because the error used to occur
94800 ** in multiple places.  (The error only occurs in one place now, but we
94801 ** retain the subroutine to minimize code disruption.)
94802 */
94803 static int checkForMultiColumnSelectError(
94804   Parse *pParse,       /* Parse context. */
94805   SelectDest *pDest,   /* Destination of SELECT results */
94806   int nExpr            /* Number of result columns returned by SELECT */
94807 ){
94808   int eDest = pDest->eDest;
94809   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
94810     sqlite3ErrorMsg(pParse, "only a single result allowed for "
94811        "a SELECT that is part of an expression");
94812     return 1;
94813   }else{
94814     return 0;
94815   }
94816 }
94817 #endif
94818
94819 /*
94820 ** An instance of the following object is used to record information about
94821 ** how to process the DISTINCT keyword, to simplify passing that information
94822 ** into the selectInnerLoop() routine.
94823 */
94824 typedef struct DistinctCtx DistinctCtx;
94825 struct DistinctCtx {
94826   u8 isTnct;      /* True if the DISTINCT keyword is present */
94827   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
94828   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
94829   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
94830 };
94831
94832 /*
94833 ** This routine generates the code for the inside of the inner loop
94834 ** of a SELECT.
94835 **
94836 ** If srcTab and nColumn are both zero, then the pEList expressions
94837 ** are evaluated in order to get the data for this row.  If nColumn>0
94838 ** then data is pulled from srcTab and pEList is used only to get the
94839 ** datatypes for each column.
94840 */
94841 static void selectInnerLoop(
94842   Parse *pParse,          /* The parser context */
94843   Select *p,              /* The complete select statement being coded */
94844   ExprList *pEList,       /* List of values being extracted */
94845   int srcTab,             /* Pull data from this table */
94846   int nColumn,            /* Number of columns in the source table */
94847   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
94848   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
94849   SelectDest *pDest,      /* How to dispose of the results */
94850   int iContinue,          /* Jump here to continue with next row */
94851   int iBreak              /* Jump here to break out of the inner loop */
94852 ){
94853   Vdbe *v = pParse->pVdbe;
94854   int i;
94855   int hasDistinct;        /* True if the DISTINCT keyword is present */
94856   int regResult;              /* Start of memory holding result set */
94857   int eDest = pDest->eDest;   /* How to dispose of results */
94858   int iParm = pDest->iSDParm; /* First argument to disposal method */
94859   int nResultCol;             /* Number of result columns */
94860
94861   assert( v );
94862   if( NEVER(v==0) ) return;
94863   assert( pEList!=0 );
94864   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
94865   if( pOrderBy==0 && !hasDistinct ){
94866     codeOffset(v, p, iContinue);
94867   }
94868
94869   /* Pull the requested columns.
94870   */
94871   if( nColumn>0 ){
94872     nResultCol = nColumn;
94873   }else{
94874     nResultCol = pEList->nExpr;
94875   }
94876   if( pDest->iSdst==0 ){
94877     pDest->iSdst = pParse->nMem+1;
94878     pDest->nSdst = nResultCol;
94879     pParse->nMem += nResultCol;
94880   }else{ 
94881     assert( pDest->nSdst==nResultCol );
94882   }
94883   regResult = pDest->iSdst;
94884   if( nColumn>0 ){
94885     for(i=0; i<nColumn; i++){
94886       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
94887     }
94888   }else if( eDest!=SRT_Exists ){
94889     /* If the destination is an EXISTS(...) expression, the actual
94890     ** values returned by the SELECT are not required.
94891     */
94892     sqlite3ExprCacheClear(pParse);
94893     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
94894   }
94895   nColumn = nResultCol;
94896
94897   /* If the DISTINCT keyword was present on the SELECT statement
94898   ** and this row has been seen before, then do not make this row
94899   ** part of the result.
94900   */
94901   if( hasDistinct ){
94902     assert( pEList!=0 );
94903     assert( pEList->nExpr==nColumn );
94904     switch( pDistinct->eTnctType ){
94905       case WHERE_DISTINCT_ORDERED: {
94906         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
94907         int iJump;              /* Jump destination */
94908         int regPrev;            /* Previous row content */
94909
94910         /* Allocate space for the previous row */
94911         regPrev = pParse->nMem+1;
94912         pParse->nMem += nColumn;
94913
94914         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
94915         ** sets the MEM_Cleared bit on the first register of the
94916         ** previous value.  This will cause the OP_Ne below to always
94917         ** fail on the first iteration of the loop even if the first
94918         ** row is all NULLs.
94919         */
94920         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
94921         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
94922         pOp->opcode = OP_Null;
94923         pOp->p1 = 1;
94924         pOp->p2 = regPrev;
94925
94926         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
94927         for(i=0; i<nColumn; i++){
94928           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
94929           if( i<nColumn-1 ){
94930             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
94931           }else{
94932             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
94933           }
94934           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
94935           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
94936         }
94937         assert( sqlite3VdbeCurrentAddr(v)==iJump );
94938         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
94939         break;
94940       }
94941
94942       case WHERE_DISTINCT_UNIQUE: {
94943         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
94944         break;
94945       }
94946
94947       default: {
94948         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
94949         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
94950         break;
94951       }
94952     }
94953     if( pOrderBy==0 ){
94954       codeOffset(v, p, iContinue);
94955     }
94956   }
94957
94958   switch( eDest ){
94959     /* In this mode, write each query result to the key of the temporary
94960     ** table iParm.
94961     */
94962 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94963     case SRT_Union: {
94964       int r1;
94965       r1 = sqlite3GetTempReg(pParse);
94966       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94967       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
94968       sqlite3ReleaseTempReg(pParse, r1);
94969       break;
94970     }
94971
94972     /* Construct a record from the query result, but instead of
94973     ** saving that record, use it as a key to delete elements from
94974     ** the temporary table iParm.
94975     */
94976     case SRT_Except: {
94977       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
94978       break;
94979     }
94980 #endif
94981
94982     /* Store the result as data using a unique key.
94983     */
94984     case SRT_Table:
94985     case SRT_EphemTab: {
94986       int r1 = sqlite3GetTempReg(pParse);
94987       testcase( eDest==SRT_Table );
94988       testcase( eDest==SRT_EphemTab );
94989       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
94990       if( pOrderBy ){
94991         pushOntoSorter(pParse, pOrderBy, p, r1);
94992       }else{
94993         int r2 = sqlite3GetTempReg(pParse);
94994         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
94995         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
94996         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94997         sqlite3ReleaseTempReg(pParse, r2);
94998       }
94999       sqlite3ReleaseTempReg(pParse, r1);
95000       break;
95001     }
95002
95003 #ifndef SQLITE_OMIT_SUBQUERY
95004     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95005     ** then there should be a single item on the stack.  Write this
95006     ** item into the set table with bogus data.
95007     */
95008     case SRT_Set: {
95009       assert( nColumn==1 );
95010       pDest->affSdst =
95011                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
95012       if( pOrderBy ){
95013         /* At first glance you would think we could optimize out the
95014         ** ORDER BY in this case since the order of entries in the set
95015         ** does not matter.  But there might be a LIMIT clause, in which
95016         ** case the order does matter */
95017         pushOntoSorter(pParse, pOrderBy, p, regResult);
95018       }else{
95019         int r1 = sqlite3GetTempReg(pParse);
95020         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
95021         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
95022         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95023         sqlite3ReleaseTempReg(pParse, r1);
95024       }
95025       break;
95026     }
95027
95028     /* If any row exist in the result set, record that fact and abort.
95029     */
95030     case SRT_Exists: {
95031       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
95032       /* The LIMIT clause will terminate the loop for us */
95033       break;
95034     }
95035
95036     /* If this is a scalar select that is part of an expression, then
95037     ** store the results in the appropriate memory cell and break out
95038     ** of the scan loop.
95039     */
95040     case SRT_Mem: {
95041       assert( nColumn==1 );
95042       if( pOrderBy ){
95043         pushOntoSorter(pParse, pOrderBy, p, regResult);
95044       }else{
95045         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
95046         /* The LIMIT clause will jump out of the loop for us */
95047       }
95048       break;
95049     }
95050 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95051
95052     /* Send the data to the callback function or to a subroutine.  In the
95053     ** case of a subroutine, the subroutine itself is responsible for
95054     ** popping the data from the stack.
95055     */
95056     case SRT_Coroutine:
95057     case SRT_Output: {
95058       testcase( eDest==SRT_Coroutine );
95059       testcase( eDest==SRT_Output );
95060       if( pOrderBy ){
95061         int r1 = sqlite3GetTempReg(pParse);
95062         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95063         pushOntoSorter(pParse, pOrderBy, p, r1);
95064         sqlite3ReleaseTempReg(pParse, r1);
95065       }else if( eDest==SRT_Coroutine ){
95066         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95067       }else{
95068         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
95069         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
95070       }
95071       break;
95072     }
95073
95074 #if !defined(SQLITE_OMIT_TRIGGER)
95075     /* Discard the results.  This is used for SELECT statements inside
95076     ** the body of a TRIGGER.  The purpose of such selects is to call
95077     ** user-defined functions that have side effects.  We do not care
95078     ** about the actual results of the select.
95079     */
95080     default: {
95081       assert( eDest==SRT_Discard );
95082       break;
95083     }
95084 #endif
95085   }
95086
95087   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
95088   ** there is a sorter, in which case the sorter has already limited
95089   ** the output for us.
95090   */
95091   if( pOrderBy==0 && p->iLimit ){
95092     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95093   }
95094 }
95095
95096 /*
95097 ** Given an expression list, generate a KeyInfo structure that records
95098 ** the collating sequence for each expression in that expression list.
95099 **
95100 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
95101 ** KeyInfo structure is appropriate for initializing a virtual index to
95102 ** implement that clause.  If the ExprList is the result set of a SELECT
95103 ** then the KeyInfo structure is appropriate for initializing a virtual
95104 ** index to implement a DISTINCT test.
95105 **
95106 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
95107 ** function is responsible for seeing that this structure is eventually
95108 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
95109 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
95110 */
95111 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
95112   sqlite3 *db = pParse->db;
95113   int nExpr;
95114   KeyInfo *pInfo;
95115   struct ExprList_item *pItem;
95116   int i;
95117
95118   nExpr = pList->nExpr;
95119   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
95120   if( pInfo ){
95121     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
95122     pInfo->nField = (u16)nExpr;
95123     pInfo->enc = ENC(db);
95124     pInfo->db = db;
95125     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
95126       CollSeq *pColl;
95127       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95128       if( !pColl ){
95129         pColl = db->pDfltColl;
95130       }
95131       pInfo->aColl[i] = pColl;
95132       pInfo->aSortOrder[i] = pItem->sortOrder;
95133     }
95134   }
95135   return pInfo;
95136 }
95137
95138 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95139 /*
95140 ** Name of the connection operator, used for error messages.
95141 */
95142 static const char *selectOpName(int id){
95143   char *z;
95144   switch( id ){
95145     case TK_ALL:       z = "UNION ALL";   break;
95146     case TK_INTERSECT: z = "INTERSECT";   break;
95147     case TK_EXCEPT:    z = "EXCEPT";      break;
95148     default:           z = "UNION";       break;
95149   }
95150   return z;
95151 }
95152 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95153
95154 #ifndef SQLITE_OMIT_EXPLAIN
95155 /*
95156 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95157 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95158 ** where the caption is of the form:
95159 **
95160 **   "USE TEMP B-TREE FOR xxx"
95161 **
95162 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
95163 ** is determined by the zUsage argument.
95164 */
95165 static void explainTempTable(Parse *pParse, const char *zUsage){
95166   if( pParse->explain==2 ){
95167     Vdbe *v = pParse->pVdbe;
95168     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
95169     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95170   }
95171 }
95172
95173 /*
95174 ** Assign expression b to lvalue a. A second, no-op, version of this macro
95175 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
95176 ** in sqlite3Select() to assign values to structure member variables that
95177 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
95178 ** code with #ifndef directives.
95179 */
95180 # define explainSetInteger(a, b) a = b
95181
95182 #else
95183 /* No-op versions of the explainXXX() functions and macros. */
95184 # define explainTempTable(y,z)
95185 # define explainSetInteger(y,z)
95186 #endif
95187
95188 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
95189 /*
95190 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95191 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95192 ** where the caption is of one of the two forms:
95193 **
95194 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95195 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95196 **
95197 ** where iSub1 and iSub2 are the integers passed as the corresponding
95198 ** function parameters, and op is the text representation of the parameter
95199 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95200 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
95201 ** false, or the second form if it is true.
95202 */
95203 static void explainComposite(
95204   Parse *pParse,                  /* Parse context */
95205   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95206   int iSub1,                      /* Subquery id 1 */
95207   int iSub2,                      /* Subquery id 2 */
95208   int bUseTmp                     /* True if a temp table was used */
95209 ){
95210   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95211   if( pParse->explain==2 ){
95212     Vdbe *v = pParse->pVdbe;
95213     char *zMsg = sqlite3MPrintf(
95214         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95215         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95216     );
95217     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95218   }
95219 }
95220 #else
95221 /* No-op versions of the explainXXX() functions and macros. */
95222 # define explainComposite(v,w,x,y,z)
95223 #endif
95224
95225 /*
95226 ** If the inner loop was generated using a non-null pOrderBy argument,
95227 ** then the results were placed in a sorter.  After the loop is terminated
95228 ** we need to run the sorter and output the results.  The following
95229 ** routine generates the code needed to do that.
95230 */
95231 static void generateSortTail(
95232   Parse *pParse,    /* Parsing context */
95233   Select *p,        /* The SELECT statement */
95234   Vdbe *v,          /* Generate code into this VDBE */
95235   int nColumn,      /* Number of columns of data */
95236   SelectDest *pDest /* Write the sorted results here */
95237 ){
95238   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
95239   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
95240   int addr;
95241   int iTab;
95242   int pseudoTab = 0;
95243   ExprList *pOrderBy = p->pOrderBy;
95244
95245   int eDest = pDest->eDest;
95246   int iParm = pDest->iSDParm;
95247
95248   int regRow;
95249   int regRowid;
95250
95251   iTab = pOrderBy->iECursor;
95252   regRow = sqlite3GetTempReg(pParse);
95253   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95254     pseudoTab = pParse->nTab++;
95255     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95256     regRowid = 0;
95257   }else{
95258     regRowid = sqlite3GetTempReg(pParse);
95259   }
95260   if( p->selFlags & SF_UseSorter ){
95261     int regSortOut = ++pParse->nMem;
95262     int ptab2 = pParse->nTab++;
95263     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95264     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95265     codeOffset(v, p, addrContinue);
95266     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95267     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95268     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95269   }else{
95270     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95271     codeOffset(v, p, addrContinue);
95272     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95273   }
95274   switch( eDest ){
95275     case SRT_Table:
95276     case SRT_EphemTab: {
95277       testcase( eDest==SRT_Table );
95278       testcase( eDest==SRT_EphemTab );
95279       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95280       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95281       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95282       break;
95283     }
95284 #ifndef SQLITE_OMIT_SUBQUERY
95285     case SRT_Set: {
95286       assert( nColumn==1 );
95287       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
95288                         &pDest->affSdst, 1);
95289       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
95290       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95291       break;
95292     }
95293     case SRT_Mem: {
95294       assert( nColumn==1 );
95295       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
95296       /* The LIMIT clause will terminate the loop for us */
95297       break;
95298     }
95299 #endif
95300     default: {
95301       int i;
95302       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
95303       testcase( eDest==SRT_Output );
95304       testcase( eDest==SRT_Coroutine );
95305       for(i=0; i<nColumn; i++){
95306         assert( regRow!=pDest->iSdst+i );
95307         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
95308         if( i==0 ){
95309           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95310         }
95311       }
95312       if( eDest==SRT_Output ){
95313         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
95314         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
95315       }else{
95316         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95317       }
95318       break;
95319     }
95320   }
95321   sqlite3ReleaseTempReg(pParse, regRow);
95322   sqlite3ReleaseTempReg(pParse, regRowid);
95323
95324   /* The bottom of the loop
95325   */
95326   sqlite3VdbeResolveLabel(v, addrContinue);
95327   if( p->selFlags & SF_UseSorter ){
95328     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95329   }else{
95330     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
95331   }
95332   sqlite3VdbeResolveLabel(v, addrBreak);
95333   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95334     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95335   }
95336 }
95337
95338 /*
95339 ** Return a pointer to a string containing the 'declaration type' of the
95340 ** expression pExpr. The string may be treated as static by the caller.
95341 **
95342 ** The declaration type is the exact datatype definition extracted from the
95343 ** original CREATE TABLE statement if the expression is a column. The
95344 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
95345 ** is considered a column can be complex in the presence of subqueries. The
95346 ** result-set expression in all of the following SELECT statements is 
95347 ** considered a column by this function.
95348 **
95349 **   SELECT col FROM tbl;
95350 **   SELECT (SELECT col FROM tbl;
95351 **   SELECT (SELECT col FROM tbl);
95352 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
95353 ** 
95354 ** The declaration type for any expression other than a column is NULL.
95355 */
95356 static const char *columnType(
95357   NameContext *pNC, 
95358   Expr *pExpr,
95359   const char **pzOriginDb,
95360   const char **pzOriginTab,
95361   const char **pzOriginCol
95362 ){
95363   char const *zType = 0;
95364   char const *zOriginDb = 0;
95365   char const *zOriginTab = 0;
95366   char const *zOriginCol = 0;
95367   int j;
95368   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95369
95370   switch( pExpr->op ){
95371     case TK_AGG_COLUMN:
95372     case TK_COLUMN: {
95373       /* The expression is a column. Locate the table the column is being
95374       ** extracted from in NameContext.pSrcList. This table may be real
95375       ** database table or a subquery.
95376       */
95377       Table *pTab = 0;            /* Table structure column is extracted from */
95378       Select *pS = 0;             /* Select the column is extracted from */
95379       int iCol = pExpr->iColumn;  /* Index of column in pTab */
95380       testcase( pExpr->op==TK_AGG_COLUMN );
95381       testcase( pExpr->op==TK_COLUMN );
95382       while( pNC && !pTab ){
95383         SrcList *pTabList = pNC->pSrcList;
95384         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95385         if( j<pTabList->nSrc ){
95386           pTab = pTabList->a[j].pTab;
95387           pS = pTabList->a[j].pSelect;
95388         }else{
95389           pNC = pNC->pNext;
95390         }
95391       }
95392
95393       if( pTab==0 ){
95394         /* At one time, code such as "SELECT new.x" within a trigger would
95395         ** cause this condition to run.  Since then, we have restructured how
95396         ** trigger code is generated and so this condition is no longer 
95397         ** possible. However, it can still be true for statements like
95398         ** the following:
95399         **
95400         **   CREATE TABLE t1(col INTEGER);
95401         **   SELECT (SELECT t1.col) FROM FROM t1;
95402         **
95403         ** when columnType() is called on the expression "t1.col" in the 
95404         ** sub-select. In this case, set the column type to NULL, even
95405         ** though it should really be "INTEGER".
95406         **
95407         ** This is not a problem, as the column type of "t1.col" is never
95408         ** used. When columnType() is called on the expression 
95409         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95410         ** branch below.  */
95411         break;
95412       }
95413
95414       assert( pTab && pExpr->pTab==pTab );
95415       if( pS ){
95416         /* The "table" is actually a sub-select or a view in the FROM clause
95417         ** of the SELECT statement. Return the declaration type and origin
95418         ** data for the result-set column of the sub-select.
95419         */
95420         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95421           /* If iCol is less than zero, then the expression requests the
95422           ** rowid of the sub-select or view. This expression is legal (see 
95423           ** test case misc2.2.2) - it always evaluates to NULL.
95424           */
95425           NameContext sNC;
95426           Expr *p = pS->pEList->a[iCol].pExpr;
95427           sNC.pSrcList = pS->pSrc;
95428           sNC.pNext = pNC;
95429           sNC.pParse = pNC->pParse;
95430           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95431         }
95432       }else if( ALWAYS(pTab->pSchema) ){
95433         /* A real table */
95434         assert( !pS );
95435         if( iCol<0 ) iCol = pTab->iPKey;
95436         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95437         if( iCol<0 ){
95438           zType = "INTEGER";
95439           zOriginCol = "rowid";
95440         }else{
95441           zType = pTab->aCol[iCol].zType;
95442           zOriginCol = pTab->aCol[iCol].zName;
95443         }
95444         zOriginTab = pTab->zName;
95445         if( pNC->pParse ){
95446           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95447           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95448         }
95449       }
95450       break;
95451     }
95452 #ifndef SQLITE_OMIT_SUBQUERY
95453     case TK_SELECT: {
95454       /* The expression is a sub-select. Return the declaration type and
95455       ** origin info for the single column in the result set of the SELECT
95456       ** statement.
95457       */
95458       NameContext sNC;
95459       Select *pS = pExpr->x.pSelect;
95460       Expr *p = pS->pEList->a[0].pExpr;
95461       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95462       sNC.pSrcList = pS->pSrc;
95463       sNC.pNext = pNC;
95464       sNC.pParse = pNC->pParse;
95465       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
95466       break;
95467     }
95468 #endif
95469   }
95470   
95471   if( pzOriginDb ){
95472     assert( pzOriginTab && pzOriginCol );
95473     *pzOriginDb = zOriginDb;
95474     *pzOriginTab = zOriginTab;
95475     *pzOriginCol = zOriginCol;
95476   }
95477   return zType;
95478 }
95479
95480 /*
95481 ** Generate code that will tell the VDBE the declaration types of columns
95482 ** in the result set.
95483 */
95484 static void generateColumnTypes(
95485   Parse *pParse,      /* Parser context */
95486   SrcList *pTabList,  /* List of tables */
95487   ExprList *pEList    /* Expressions defining the result set */
95488 ){
95489 #ifndef SQLITE_OMIT_DECLTYPE
95490   Vdbe *v = pParse->pVdbe;
95491   int i;
95492   NameContext sNC;
95493   sNC.pSrcList = pTabList;
95494   sNC.pParse = pParse;
95495   for(i=0; i<pEList->nExpr; i++){
95496     Expr *p = pEList->a[i].pExpr;
95497     const char *zType;
95498 #ifdef SQLITE_ENABLE_COLUMN_METADATA
95499     const char *zOrigDb = 0;
95500     const char *zOrigTab = 0;
95501     const char *zOrigCol = 0;
95502     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95503
95504     /* The vdbe must make its own copy of the column-type and other 
95505     ** column specific strings, in case the schema is reset before this
95506     ** virtual machine is deleted.
95507     */
95508     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
95509     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
95510     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
95511 #else
95512     zType = columnType(&sNC, p, 0, 0, 0);
95513 #endif
95514     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
95515   }
95516 #endif /* SQLITE_OMIT_DECLTYPE */
95517 }
95518
95519 /*
95520 ** Generate code that will tell the VDBE the names of columns
95521 ** in the result set.  This information is used to provide the
95522 ** azCol[] values in the callback.
95523 */
95524 static void generateColumnNames(
95525   Parse *pParse,      /* Parser context */
95526   SrcList *pTabList,  /* List of tables */
95527   ExprList *pEList    /* Expressions defining the result set */
95528 ){
95529   Vdbe *v = pParse->pVdbe;
95530   int i, j;
95531   sqlite3 *db = pParse->db;
95532   int fullNames, shortNames;
95533
95534 #ifndef SQLITE_OMIT_EXPLAIN
95535   /* If this is an EXPLAIN, skip this step */
95536   if( pParse->explain ){
95537     return;
95538   }
95539 #endif
95540
95541   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95542   pParse->colNamesSet = 1;
95543   fullNames = (db->flags & SQLITE_FullColNames)!=0;
95544   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
95545   sqlite3VdbeSetNumCols(v, pEList->nExpr);
95546   for(i=0; i<pEList->nExpr; i++){
95547     Expr *p;
95548     p = pEList->a[i].pExpr;
95549     if( NEVER(p==0) ) continue;
95550     if( pEList->a[i].zName ){
95551       char *zName = pEList->a[i].zName;
95552       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
95553     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95554       Table *pTab;
95555       char *zCol;
95556       int iCol = p->iColumn;
95557       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95558         if( pTabList->a[j].iCursor==p->iTable ) break;
95559       }
95560       assert( j<pTabList->nSrc );
95561       pTab = pTabList->a[j].pTab;
95562       if( iCol<0 ) iCol = pTab->iPKey;
95563       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95564       if( iCol<0 ){
95565         zCol = "rowid";
95566       }else{
95567         zCol = pTab->aCol[iCol].zName;
95568       }
95569       if( !shortNames && !fullNames ){
95570         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
95571             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95572       }else if( fullNames ){
95573         char *zName = 0;
95574         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
95575         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
95576       }else{
95577         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
95578       }
95579     }else{
95580       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
95581           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95582     }
95583   }
95584   generateColumnTypes(pParse, pTabList, pEList);
95585 }
95586
95587 /*
95588 ** Given a an expression list (which is really the list of expressions
95589 ** that form the result set of a SELECT statement) compute appropriate
95590 ** column names for a table that would hold the expression list.
95591 **
95592 ** All column names will be unique.
95593 **
95594 ** Only the column names are computed.  Column.zType, Column.zColl,
95595 ** and other fields of Column are zeroed.
95596 **
95597 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
95598 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
95599 */
95600 static int selectColumnsFromExprList(
95601   Parse *pParse,          /* Parsing context */
95602   ExprList *pEList,       /* Expr list from which to derive column names */
95603   i16 *pnCol,             /* Write the number of columns here */
95604   Column **paCol          /* Write the new column list here */
95605 ){
95606   sqlite3 *db = pParse->db;   /* Database connection */
95607   int i, j;                   /* Loop counters */
95608   int cnt;                    /* Index added to make the name unique */
95609   Column *aCol, *pCol;        /* For looping over result columns */
95610   int nCol;                   /* Number of columns in the result set */
95611   Expr *p;                    /* Expression for a single result column */
95612   char *zName;                /* Column name */
95613   int nName;                  /* Size of name in zName[] */
95614
95615   if( pEList ){
95616     nCol = pEList->nExpr;
95617     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
95618     testcase( aCol==0 );
95619   }else{
95620     nCol = 0;
95621     aCol = 0;
95622   }
95623   *pnCol = nCol;
95624   *paCol = aCol;
95625
95626   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95627     /* Get an appropriate name for the column
95628     */
95629     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
95630     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
95631                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
95632     if( (zName = pEList->a[i].zName)!=0 ){
95633       /* If the column contains an "AS <name>" phrase, use <name> as the name */
95634       zName = sqlite3DbStrDup(db, zName);
95635     }else{
95636       Expr *pColExpr = p;  /* The expression that is the result column name */
95637       Table *pTab;         /* Table associated with this expression */
95638       while( pColExpr->op==TK_DOT ){
95639         pColExpr = pColExpr->pRight;
95640         assert( pColExpr!=0 );
95641       }
95642       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
95643         /* For columns use the column name name */
95644         int iCol = pColExpr->iColumn;
95645         pTab = pColExpr->pTab;
95646         if( iCol<0 ) iCol = pTab->iPKey;
95647         zName = sqlite3MPrintf(db, "%s",
95648                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
95649       }else if( pColExpr->op==TK_ID ){
95650         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
95651         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
95652       }else{
95653         /* Use the original text of the column expression as its name */
95654         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
95655       }
95656     }
95657     if( db->mallocFailed ){
95658       sqlite3DbFree(db, zName);
95659       break;
95660     }
95661
95662     /* Make sure the column name is unique.  If the name is not unique,
95663     ** append a integer to the name so that it becomes unique.
95664     */
95665     nName = sqlite3Strlen30(zName);
95666     for(j=cnt=0; j<i; j++){
95667       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
95668         char *zNewName;
95669         zName[nName] = 0;
95670         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
95671         sqlite3DbFree(db, zName);
95672         zName = zNewName;
95673         j = -1;
95674         if( zName==0 ) break;
95675       }
95676     }
95677     pCol->zName = zName;
95678   }
95679   if( db->mallocFailed ){
95680     for(j=0; j<i; j++){
95681       sqlite3DbFree(db, aCol[j].zName);
95682     }
95683     sqlite3DbFree(db, aCol);
95684     *paCol = 0;
95685     *pnCol = 0;
95686     return SQLITE_NOMEM;
95687   }
95688   return SQLITE_OK;
95689 }
95690
95691 /*
95692 ** Add type and collation information to a column list based on
95693 ** a SELECT statement.
95694 ** 
95695 ** The column list presumably came from selectColumnNamesFromExprList().
95696 ** The column list has only names, not types or collations.  This
95697 ** routine goes through and adds the types and collations.
95698 **
95699 ** This routine requires that all identifiers in the SELECT
95700 ** statement be resolved.
95701 */
95702 static void selectAddColumnTypeAndCollation(
95703   Parse *pParse,        /* Parsing contexts */
95704   int nCol,             /* Number of columns */
95705   Column *aCol,         /* List of columns */
95706   Select *pSelect       /* SELECT used to determine types and collations */
95707 ){
95708   sqlite3 *db = pParse->db;
95709   NameContext sNC;
95710   Column *pCol;
95711   CollSeq *pColl;
95712   int i;
95713   Expr *p;
95714   struct ExprList_item *a;
95715
95716   assert( pSelect!=0 );
95717   assert( (pSelect->selFlags & SF_Resolved)!=0 );
95718   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
95719   if( db->mallocFailed ) return;
95720   memset(&sNC, 0, sizeof(sNC));
95721   sNC.pSrcList = pSelect->pSrc;
95722   a = pSelect->pEList->a;
95723   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95724     p = a[i].pExpr;
95725     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
95726     pCol->affinity = sqlite3ExprAffinity(p);
95727     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
95728     pColl = sqlite3ExprCollSeq(pParse, p);
95729     if( pColl ){
95730       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
95731     }
95732   }
95733 }
95734
95735 /*
95736 ** Given a SELECT statement, generate a Table structure that describes
95737 ** the result set of that SELECT.
95738 */
95739 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
95740   Table *pTab;
95741   sqlite3 *db = pParse->db;
95742   int savedFlags;
95743
95744   savedFlags = db->flags;
95745   db->flags &= ~SQLITE_FullColNames;
95746   db->flags |= SQLITE_ShortColNames;
95747   sqlite3SelectPrep(pParse, pSelect, 0);
95748   if( pParse->nErr ) return 0;
95749   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
95750   db->flags = savedFlags;
95751   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
95752   if( pTab==0 ){
95753     return 0;
95754   }
95755   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
95756   ** is disabled */
95757   assert( db->lookaside.bEnabled==0 );
95758   pTab->nRef = 1;
95759   pTab->zName = 0;
95760   pTab->nRowEst = 1000000;
95761   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
95762   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
95763   pTab->iPKey = -1;
95764   if( db->mallocFailed ){
95765     sqlite3DeleteTable(db, pTab);
95766     return 0;
95767   }
95768   return pTab;
95769 }
95770
95771 /*
95772 ** Get a VDBE for the given parser context.  Create a new one if necessary.
95773 ** If an error occurs, return NULL and leave a message in pParse.
95774 */
95775 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
95776   Vdbe *v = pParse->pVdbe;
95777   if( v==0 ){
95778     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
95779 #ifndef SQLITE_OMIT_TRACE
95780     if( v ){
95781       sqlite3VdbeAddOp0(v, OP_Trace);
95782     }
95783 #endif
95784   }
95785   return v;
95786 }
95787
95788
95789 /*
95790 ** Compute the iLimit and iOffset fields of the SELECT based on the
95791 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95792 ** that appear in the original SQL statement after the LIMIT and OFFSET
95793 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
95794 ** are the integer memory register numbers for counters used to compute 
95795 ** the limit and offset.  If there is no limit and/or offset, then 
95796 ** iLimit and iOffset are negative.
95797 **
95798 ** This routine changes the values of iLimit and iOffset only if
95799 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
95800 ** iOffset should have been preset to appropriate default values
95801 ** (usually but not always -1) prior to calling this routine.
95802 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95803 ** redefined.  The UNION ALL operator uses this property to force
95804 ** the reuse of the same limit and offset registers across multiple
95805 ** SELECT statements.
95806 */
95807 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95808   Vdbe *v = 0;
95809   int iLimit = 0;
95810   int iOffset;
95811   int addr1, n;
95812   if( p->iLimit ) return;
95813
95814   /* 
95815   ** "LIMIT -1" always shows all rows.  There is some
95816   ** contraversy about what the correct behavior should be.
95817   ** The current implementation interprets "LIMIT 0" to mean
95818   ** no rows.
95819   */
95820   sqlite3ExprCacheClear(pParse);
95821   assert( p->pOffset==0 || p->pLimit!=0 );
95822   if( p->pLimit ){
95823     p->iLimit = iLimit = ++pParse->nMem;
95824     v = sqlite3GetVdbe(pParse);
95825     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95826     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
95827       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
95828       VdbeComment((v, "LIMIT counter"));
95829       if( n==0 ){
95830         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95831       }else{
95832         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95833       }
95834     }else{
95835       sqlite3ExprCode(pParse, p->pLimit, iLimit);
95836       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95837       VdbeComment((v, "LIMIT counter"));
95838       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95839     }
95840     if( p->pOffset ){
95841       p->iOffset = iOffset = ++pParse->nMem;
95842       pParse->nMem++;   /* Allocate an extra register for limit+offset */
95843       sqlite3ExprCode(pParse, p->pOffset, iOffset);
95844       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95845       VdbeComment((v, "OFFSET counter"));
95846       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
95847       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
95848       sqlite3VdbeJumpHere(v, addr1);
95849       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
95850       VdbeComment((v, "LIMIT+OFFSET"));
95851       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
95852       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
95853       sqlite3VdbeJumpHere(v, addr1);
95854     }
95855   }
95856 }
95857
95858 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95859 /*
95860 ** Return the appropriate collating sequence for the iCol-th column of
95861 ** the result set for the compound-select statement "p".  Return NULL if
95862 ** the column has no default collating sequence.
95863 **
95864 ** The collating sequence for the compound select is taken from the
95865 ** left-most term of the select that has a collating sequence.
95866 */
95867 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
95868   CollSeq *pRet;
95869   if( p->pPrior ){
95870     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
95871   }else{
95872     pRet = 0;
95873   }
95874   assert( iCol>=0 );
95875   if( pRet==0 && iCol<p->pEList->nExpr ){
95876     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
95877   }
95878   return pRet;
95879 }
95880 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95881
95882 /* Forward reference */
95883 static int multiSelectOrderBy(
95884   Parse *pParse,        /* Parsing context */
95885   Select *p,            /* The right-most of SELECTs to be coded */
95886   SelectDest *pDest     /* What to do with query results */
95887 );
95888
95889
95890 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95891 /*
95892 ** This routine is called to process a compound query form from
95893 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
95894 ** INTERSECT
95895 **
95896 ** "p" points to the right-most of the two queries.  the query on the
95897 ** left is p->pPrior.  The left query could also be a compound query
95898 ** in which case this routine will be called recursively. 
95899 **
95900 ** The results of the total query are to be written into a destination
95901 ** of type eDest with parameter iParm.
95902 **
95903 ** Example 1:  Consider a three-way compound SQL statement.
95904 **
95905 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
95906 **
95907 ** This statement is parsed up as follows:
95908 **
95909 **     SELECT c FROM t3
95910 **      |
95911 **      `----->  SELECT b FROM t2
95912 **                |
95913 **                `------>  SELECT a FROM t1
95914 **
95915 ** The arrows in the diagram above represent the Select.pPrior pointer.
95916 ** So if this routine is called with p equal to the t3 query, then
95917 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
95918 **
95919 ** Notice that because of the way SQLite parses compound SELECTs, the
95920 ** individual selects always group from left to right.
95921 */
95922 static int multiSelect(
95923   Parse *pParse,        /* Parsing context */
95924   Select *p,            /* The right-most of SELECTs to be coded */
95925   SelectDest *pDest     /* What to do with query results */
95926 ){
95927   int rc = SQLITE_OK;   /* Success code from a subroutine */
95928   Select *pPrior;       /* Another SELECT immediately to our left */
95929   Vdbe *v;              /* Generate code to this VDBE */
95930   SelectDest dest;      /* Alternative data destination */
95931   Select *pDelete = 0;  /* Chain of simple selects to delete */
95932   sqlite3 *db;          /* Database connection */
95933 #ifndef SQLITE_OMIT_EXPLAIN
95934   int iSub1;            /* EQP id of left-hand query */
95935   int iSub2;            /* EQP id of right-hand query */
95936 #endif
95937
95938   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
95939   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
95940   */
95941   assert( p && p->pPrior );  /* Calling function guarantees this much */
95942   db = pParse->db;
95943   pPrior = p->pPrior;
95944   assert( pPrior->pRightmost!=pPrior );
95945   assert( pPrior->pRightmost==p->pRightmost );
95946   dest = *pDest;
95947   if( pPrior->pOrderBy ){
95948     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
95949       selectOpName(p->op));
95950     rc = 1;
95951     goto multi_select_end;
95952   }
95953   if( pPrior->pLimit ){
95954     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
95955       selectOpName(p->op));
95956     rc = 1;
95957     goto multi_select_end;
95958   }
95959
95960   v = sqlite3GetVdbe(pParse);
95961   assert( v!=0 );  /* The VDBE already created by calling function */
95962
95963   /* Create the destination temporary table if necessary
95964   */
95965   if( dest.eDest==SRT_EphemTab ){
95966     assert( p->pEList );
95967     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
95968     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
95969     dest.eDest = SRT_Table;
95970   }
95971
95972   /* Make sure all SELECTs in the statement have the same number of elements
95973   ** in their result sets.
95974   */
95975   assert( p->pEList && pPrior->pEList );
95976   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
95977     if( p->selFlags & SF_Values ){
95978       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
95979     }else{
95980       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
95981         " do not have the same number of result columns", selectOpName(p->op));
95982     }
95983     rc = 1;
95984     goto multi_select_end;
95985   }
95986
95987   /* Compound SELECTs that have an ORDER BY clause are handled separately.
95988   */
95989   if( p->pOrderBy ){
95990     return multiSelectOrderBy(pParse, p, pDest);
95991   }
95992
95993   /* Generate code for the left and right SELECT statements.
95994   */
95995   switch( p->op ){
95996     case TK_ALL: {
95997       int addr = 0;
95998       int nLimit;
95999       assert( !pPrior->pLimit );
96000       pPrior->pLimit = p->pLimit;
96001       pPrior->pOffset = p->pOffset;
96002       explainSetInteger(iSub1, pParse->iNextSelectId);
96003       rc = sqlite3Select(pParse, pPrior, &dest);
96004       p->pLimit = 0;
96005       p->pOffset = 0;
96006       if( rc ){
96007         goto multi_select_end;
96008       }
96009       p->pPrior = 0;
96010       p->iLimit = pPrior->iLimit;
96011       p->iOffset = pPrior->iOffset;
96012       if( p->iLimit ){
96013         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
96014         VdbeComment((v, "Jump ahead if LIMIT reached"));
96015       }
96016       explainSetInteger(iSub2, pParse->iNextSelectId);
96017       rc = sqlite3Select(pParse, p, &dest);
96018       testcase( rc!=SQLITE_OK );
96019       pDelete = p->pPrior;
96020       p->pPrior = pPrior;
96021       p->nSelectRow += pPrior->nSelectRow;
96022       if( pPrior->pLimit
96023        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
96024        && p->nSelectRow > (double)nLimit 
96025       ){
96026         p->nSelectRow = (double)nLimit;
96027       }
96028       if( addr ){
96029         sqlite3VdbeJumpHere(v, addr);
96030       }
96031       break;
96032     }
96033     case TK_EXCEPT:
96034     case TK_UNION: {
96035       int unionTab;    /* Cursor number of the temporary table holding result */
96036       u8 op = 0;       /* One of the SRT_ operations to apply to self */
96037       int priorOp;     /* The SRT_ operation to apply to prior selects */
96038       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
96039       int addr;
96040       SelectDest uniondest;
96041
96042       testcase( p->op==TK_EXCEPT );
96043       testcase( p->op==TK_UNION );
96044       priorOp = SRT_Union;
96045       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
96046         /* We can reuse a temporary table generated by a SELECT to our
96047         ** right.
96048         */
96049         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
96050                                      ** of a 3-way or more compound */
96051         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
96052         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
96053         unionTab = dest.iSDParm;
96054       }else{
96055         /* We will need to create our own temporary table to hold the
96056         ** intermediate results.
96057         */
96058         unionTab = pParse->nTab++;
96059         assert( p->pOrderBy==0 );
96060         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
96061         assert( p->addrOpenEphm[0] == -1 );
96062         p->addrOpenEphm[0] = addr;
96063         p->pRightmost->selFlags |= SF_UsesEphemeral;
96064         assert( p->pEList );
96065       }
96066
96067       /* Code the SELECT statements to our left
96068       */
96069       assert( !pPrior->pOrderBy );
96070       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
96071       explainSetInteger(iSub1, pParse->iNextSelectId);
96072       rc = sqlite3Select(pParse, pPrior, &uniondest);
96073       if( rc ){
96074         goto multi_select_end;
96075       }
96076
96077       /* Code the current SELECT statement
96078       */
96079       if( p->op==TK_EXCEPT ){
96080         op = SRT_Except;
96081       }else{
96082         assert( p->op==TK_UNION );
96083         op = SRT_Union;
96084       }
96085       p->pPrior = 0;
96086       pLimit = p->pLimit;
96087       p->pLimit = 0;
96088       pOffset = p->pOffset;
96089       p->pOffset = 0;
96090       uniondest.eDest = op;
96091       explainSetInteger(iSub2, pParse->iNextSelectId);
96092       rc = sqlite3Select(pParse, p, &uniondest);
96093       testcase( rc!=SQLITE_OK );
96094       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
96095       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
96096       sqlite3ExprListDelete(db, p->pOrderBy);
96097       pDelete = p->pPrior;
96098       p->pPrior = pPrior;
96099       p->pOrderBy = 0;
96100       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
96101       sqlite3ExprDelete(db, p->pLimit);
96102       p->pLimit = pLimit;
96103       p->pOffset = pOffset;
96104       p->iLimit = 0;
96105       p->iOffset = 0;
96106
96107       /* Convert the data in the temporary table into whatever form
96108       ** it is that we currently need.
96109       */
96110       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
96111       if( dest.eDest!=priorOp ){
96112         int iCont, iBreak, iStart;
96113         assert( p->pEList );
96114         if( dest.eDest==SRT_Output ){
96115           Select *pFirst = p;
96116           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96117           generateColumnNames(pParse, 0, pFirst->pEList);
96118         }
96119         iBreak = sqlite3VdbeMakeLabel(v);
96120         iCont = sqlite3VdbeMakeLabel(v);
96121         computeLimitRegisters(pParse, p, iBreak);
96122         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
96123         iStart = sqlite3VdbeCurrentAddr(v);
96124         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
96125                         0, 0, &dest, iCont, iBreak);
96126         sqlite3VdbeResolveLabel(v, iCont);
96127         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
96128         sqlite3VdbeResolveLabel(v, iBreak);
96129         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
96130       }
96131       break;
96132     }
96133     default: assert( p->op==TK_INTERSECT ); {
96134       int tab1, tab2;
96135       int iCont, iBreak, iStart;
96136       Expr *pLimit, *pOffset;
96137       int addr;
96138       SelectDest intersectdest;
96139       int r1;
96140
96141       /* INTERSECT is different from the others since it requires
96142       ** two temporary tables.  Hence it has its own case.  Begin
96143       ** by allocating the tables we will need.
96144       */
96145       tab1 = pParse->nTab++;
96146       tab2 = pParse->nTab++;
96147       assert( p->pOrderBy==0 );
96148
96149       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
96150       assert( p->addrOpenEphm[0] == -1 );
96151       p->addrOpenEphm[0] = addr;
96152       p->pRightmost->selFlags |= SF_UsesEphemeral;
96153       assert( p->pEList );
96154
96155       /* Code the SELECTs to our left into temporary table "tab1".
96156       */
96157       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
96158       explainSetInteger(iSub1, pParse->iNextSelectId);
96159       rc = sqlite3Select(pParse, pPrior, &intersectdest);
96160       if( rc ){
96161         goto multi_select_end;
96162       }
96163
96164       /* Code the current SELECT into temporary table "tab2"
96165       */
96166       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
96167       assert( p->addrOpenEphm[1] == -1 );
96168       p->addrOpenEphm[1] = addr;
96169       p->pPrior = 0;
96170       pLimit = p->pLimit;
96171       p->pLimit = 0;
96172       pOffset = p->pOffset;
96173       p->pOffset = 0;
96174       intersectdest.iSDParm = tab2;
96175       explainSetInteger(iSub2, pParse->iNextSelectId);
96176       rc = sqlite3Select(pParse, p, &intersectdest);
96177       testcase( rc!=SQLITE_OK );
96178       pDelete = p->pPrior;
96179       p->pPrior = pPrior;
96180       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96181       sqlite3ExprDelete(db, p->pLimit);
96182       p->pLimit = pLimit;
96183       p->pOffset = pOffset;
96184
96185       /* Generate code to take the intersection of the two temporary
96186       ** tables.
96187       */
96188       assert( p->pEList );
96189       if( dest.eDest==SRT_Output ){
96190         Select *pFirst = p;
96191         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96192         generateColumnNames(pParse, 0, pFirst->pEList);
96193       }
96194       iBreak = sqlite3VdbeMakeLabel(v);
96195       iCont = sqlite3VdbeMakeLabel(v);
96196       computeLimitRegisters(pParse, p, iBreak);
96197       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96198       r1 = sqlite3GetTempReg(pParse);
96199       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96200       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96201       sqlite3ReleaseTempReg(pParse, r1);
96202       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96203                       0, 0, &dest, iCont, iBreak);
96204       sqlite3VdbeResolveLabel(v, iCont);
96205       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
96206       sqlite3VdbeResolveLabel(v, iBreak);
96207       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
96208       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
96209       break;
96210     }
96211   }
96212
96213   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96214
96215   /* Compute collating sequences used by 
96216   ** temporary tables needed to implement the compound select.
96217   ** Attach the KeyInfo structure to all temporary tables.
96218   **
96219   ** This section is run by the right-most SELECT statement only.
96220   ** SELECT statements to the left always skip this part.  The right-most
96221   ** SELECT might also skip this part if it has no ORDER BY clause and
96222   ** no temp tables are required.
96223   */
96224   if( p->selFlags & SF_UsesEphemeral ){
96225     int i;                        /* Loop counter */
96226     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96227     Select *pLoop;                /* For looping through SELECT statements */
96228     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96229     int nCol;                     /* Number of columns in result set */
96230
96231     assert( p->pRightmost==p );
96232     nCol = p->pEList->nExpr;
96233     pKeyInfo = sqlite3DbMallocZero(db,
96234                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96235     if( !pKeyInfo ){
96236       rc = SQLITE_NOMEM;
96237       goto multi_select_end;
96238     }
96239
96240     pKeyInfo->enc = ENC(db);
96241     pKeyInfo->nField = (u16)nCol;
96242
96243     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96244       *apColl = multiSelectCollSeq(pParse, p, i);
96245       if( 0==*apColl ){
96246         *apColl = db->pDfltColl;
96247       }
96248     }
96249     pKeyInfo->aSortOrder = (u8*)apColl;
96250
96251     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96252       for(i=0; i<2; i++){
96253         int addr = pLoop->addrOpenEphm[i];
96254         if( addr<0 ){
96255           /* If [0] is unused then [1] is also unused.  So we can
96256           ** always safely abort as soon as the first unused slot is found */
96257           assert( pLoop->addrOpenEphm[1]<0 );
96258           break;
96259         }
96260         sqlite3VdbeChangeP2(v, addr, nCol);
96261         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96262         pLoop->addrOpenEphm[i] = -1;
96263       }
96264     }
96265     sqlite3DbFree(db, pKeyInfo);
96266   }
96267
96268 multi_select_end:
96269   pDest->iSdst = dest.iSdst;
96270   pDest->nSdst = dest.nSdst;
96271   sqlite3SelectDelete(db, pDelete);
96272   return rc;
96273 }
96274 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96275
96276 /*
96277 ** Code an output subroutine for a coroutine implementation of a
96278 ** SELECT statment.
96279 **
96280 ** The data to be output is contained in pIn->iSdst.  There are
96281 ** pIn->nSdst columns to be output.  pDest is where the output should
96282 ** be sent.
96283 **
96284 ** regReturn is the number of the register holding the subroutine
96285 ** return address.
96286 **
96287 ** If regPrev>0 then it is the first register in a vector that
96288 ** records the previous output.  mem[regPrev] is a flag that is false
96289 ** if there has been no previous output.  If regPrev>0 then code is
96290 ** generated to suppress duplicates.  pKeyInfo is used for comparing
96291 ** keys.
96292 **
96293 ** If the LIMIT found in p->iLimit is reached, jump immediately to
96294 ** iBreak.
96295 */
96296 static int generateOutputSubroutine(
96297   Parse *pParse,          /* Parsing context */
96298   Select *p,              /* The SELECT statement */
96299   SelectDest *pIn,        /* Coroutine supplying data */
96300   SelectDest *pDest,      /* Where to send the data */
96301   int regReturn,          /* The return address register */
96302   int regPrev,            /* Previous result register.  No uniqueness if 0 */
96303   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96304   int p4type,             /* The p4 type for pKeyInfo */
96305   int iBreak              /* Jump here if we hit the LIMIT */
96306 ){
96307   Vdbe *v = pParse->pVdbe;
96308   int iContinue;
96309   int addr;
96310
96311   addr = sqlite3VdbeCurrentAddr(v);
96312   iContinue = sqlite3VdbeMakeLabel(v);
96313
96314   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
96315   */
96316   if( regPrev ){
96317     int j1, j2;
96318     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
96319     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
96320                               (char*)pKeyInfo, p4type);
96321     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96322     sqlite3VdbeJumpHere(v, j1);
96323     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
96324     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96325   }
96326   if( pParse->db->mallocFailed ) return 0;
96327
96328   /* Suppress the first OFFSET entries if there is an OFFSET clause
96329   */
96330   codeOffset(v, p, iContinue);
96331
96332   switch( pDest->eDest ){
96333     /* Store the result as data using a unique key.
96334     */
96335     case SRT_Table:
96336     case SRT_EphemTab: {
96337       int r1 = sqlite3GetTempReg(pParse);
96338       int r2 = sqlite3GetTempReg(pParse);
96339       testcase( pDest->eDest==SRT_Table );
96340       testcase( pDest->eDest==SRT_EphemTab );
96341       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
96342       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
96343       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
96344       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96345       sqlite3ReleaseTempReg(pParse, r2);
96346       sqlite3ReleaseTempReg(pParse, r1);
96347       break;
96348     }
96349
96350 #ifndef SQLITE_OMIT_SUBQUERY
96351     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96352     ** then there should be a single item on the stack.  Write this
96353     ** item into the set table with bogus data.
96354     */
96355     case SRT_Set: {
96356       int r1;
96357       assert( pIn->nSdst==1 );
96358       pDest->affSdst = 
96359          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
96360       r1 = sqlite3GetTempReg(pParse);
96361       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
96362       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
96363       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
96364       sqlite3ReleaseTempReg(pParse, r1);
96365       break;
96366     }
96367
96368 #if 0  /* Never occurs on an ORDER BY query */
96369     /* If any row exist in the result set, record that fact and abort.
96370     */
96371     case SRT_Exists: {
96372       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
96373       /* The LIMIT clause will terminate the loop for us */
96374       break;
96375     }
96376 #endif
96377
96378     /* If this is a scalar select that is part of an expression, then
96379     ** store the results in the appropriate memory cell and break out
96380     ** of the scan loop.
96381     */
96382     case SRT_Mem: {
96383       assert( pIn->nSdst==1 );
96384       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
96385       /* The LIMIT clause will jump out of the loop for us */
96386       break;
96387     }
96388 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96389
96390     /* The results are stored in a sequence of registers
96391     ** starting at pDest->iSdst.  Then the co-routine yields.
96392     */
96393     case SRT_Coroutine: {
96394       if( pDest->iSdst==0 ){
96395         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
96396         pDest->nSdst = pIn->nSdst;
96397       }
96398       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
96399       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96400       break;
96401     }
96402
96403     /* If none of the above, then the result destination must be
96404     ** SRT_Output.  This routine is never called with any other
96405     ** destination other than the ones handled above or SRT_Output.
96406     **
96407     ** For SRT_Output, results are stored in a sequence of registers.  
96408     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
96409     ** return the next row of result.
96410     */
96411     default: {
96412       assert( pDest->eDest==SRT_Output );
96413       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
96414       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
96415       break;
96416     }
96417   }
96418
96419   /* Jump to the end of the loop if the LIMIT is reached.
96420   */
96421   if( p->iLimit ){
96422     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96423   }
96424
96425   /* Generate the subroutine return
96426   */
96427   sqlite3VdbeResolveLabel(v, iContinue);
96428   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
96429
96430   return addr;
96431 }
96432
96433 /*
96434 ** Alternative compound select code generator for cases when there
96435 ** is an ORDER BY clause.
96436 **
96437 ** We assume a query of the following form:
96438 **
96439 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96440 **
96441 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96442 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
96443 ** co-routines.  Then run the co-routines in parallel and merge the results
96444 ** into the output.  In addition to the two coroutines (called selectA and
96445 ** selectB) there are 7 subroutines:
96446 **
96447 **    outA:    Move the output of the selectA coroutine into the output
96448 **             of the compound query.
96449 **
96450 **    outB:    Move the output of the selectB coroutine into the output
96451 **             of the compound query.  (Only generated for UNION and
96452 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96453 **             appears only in B.)
96454 **
96455 **    AltB:    Called when there is data from both coroutines and A<B.
96456 **
96457 **    AeqB:    Called when there is data from both coroutines and A==B.
96458 **
96459 **    AgtB:    Called when there is data from both coroutines and A>B.
96460 **
96461 **    EofA:    Called when data is exhausted from selectA.
96462 **
96463 **    EofB:    Called when data is exhausted from selectB.
96464 **
96465 ** The implementation of the latter five subroutines depend on which 
96466 ** <operator> is used:
96467 **
96468 **
96469 **             UNION ALL         UNION            EXCEPT          INTERSECT
96470 **          -------------  -----------------  --------------  -----------------
96471 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96472 **
96473 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96474 **
96475 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96476 **
96477 **   EofA:   outB, nextB      outB, nextB          halt             halt
96478 **
96479 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96480 **
96481 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96482 ** causes an immediate jump to EofA and an EOF on B following nextB causes
96483 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96484 ** following nextX causes a jump to the end of the select processing.
96485 **
96486 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96487 ** within the output subroutine.  The regPrev register set holds the previously
96488 ** output value.  A comparison is made against this value and the output
96489 ** is skipped if the next results would be the same as the previous.
96490 **
96491 ** The implementation plan is to implement the two coroutines and seven
96492 ** subroutines first, then put the control logic at the bottom.  Like this:
96493 **
96494 **          goto Init
96495 **     coA: coroutine for left query (A)
96496 **     coB: coroutine for right query (B)
96497 **    outA: output one row of A
96498 **    outB: output one row of B (UNION and UNION ALL only)
96499 **    EofA: ...
96500 **    EofB: ...
96501 **    AltB: ...
96502 **    AeqB: ...
96503 **    AgtB: ...
96504 **    Init: initialize coroutine registers
96505 **          yield coA
96506 **          if eof(A) goto EofA
96507 **          yield coB
96508 **          if eof(B) goto EofB
96509 **    Cmpr: Compare A, B
96510 **          Jump AltB, AeqB, AgtB
96511 **     End: ...
96512 **
96513 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96514 ** actually called using Gosub and they do not Return.  EofA and EofB loop
96515 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96516 ** and AgtB jump to either L2 or to one of EofA or EofB.
96517 */
96518 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96519 static int multiSelectOrderBy(
96520   Parse *pParse,        /* Parsing context */
96521   Select *p,            /* The right-most of SELECTs to be coded */
96522   SelectDest *pDest     /* What to do with query results */
96523 ){
96524   int i, j;             /* Loop counters */
96525   Select *pPrior;       /* Another SELECT immediately to our left */
96526   Vdbe *v;              /* Generate code to this VDBE */
96527   SelectDest destA;     /* Destination for coroutine A */
96528   SelectDest destB;     /* Destination for coroutine B */
96529   int regAddrA;         /* Address register for select-A coroutine */
96530   int regEofA;          /* Flag to indicate when select-A is complete */
96531   int regAddrB;         /* Address register for select-B coroutine */
96532   int regEofB;          /* Flag to indicate when select-B is complete */
96533   int addrSelectA;      /* Address of the select-A coroutine */
96534   int addrSelectB;      /* Address of the select-B coroutine */
96535   int regOutA;          /* Address register for the output-A subroutine */
96536   int regOutB;          /* Address register for the output-B subroutine */
96537   int addrOutA;         /* Address of the output-A subroutine */
96538   int addrOutB = 0;     /* Address of the output-B subroutine */
96539   int addrEofA;         /* Address of the select-A-exhausted subroutine */
96540   int addrEofB;         /* Address of the select-B-exhausted subroutine */
96541   int addrAltB;         /* Address of the A<B subroutine */
96542   int addrAeqB;         /* Address of the A==B subroutine */
96543   int addrAgtB;         /* Address of the A>B subroutine */
96544   int regLimitA;        /* Limit register for select-A */
96545   int regLimitB;        /* Limit register for select-A */
96546   int regPrev;          /* A range of registers to hold previous output */
96547   int savedLimit;       /* Saved value of p->iLimit */
96548   int savedOffset;      /* Saved value of p->iOffset */
96549   int labelCmpr;        /* Label for the start of the merge algorithm */
96550   int labelEnd;         /* Label for the end of the overall SELECT stmt */
96551   int j1;               /* Jump instructions that get retargetted */
96552   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96553   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96554   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96555   sqlite3 *db;          /* Database connection */
96556   ExprList *pOrderBy;   /* The ORDER BY clause */
96557   int nOrderBy;         /* Number of terms in the ORDER BY clause */
96558   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96559 #ifndef SQLITE_OMIT_EXPLAIN
96560   int iSub1;            /* EQP id of left-hand query */
96561   int iSub2;            /* EQP id of right-hand query */
96562 #endif
96563
96564   assert( p->pOrderBy!=0 );
96565   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96566   db = pParse->db;
96567   v = pParse->pVdbe;
96568   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96569   labelEnd = sqlite3VdbeMakeLabel(v);
96570   labelCmpr = sqlite3VdbeMakeLabel(v);
96571
96572
96573   /* Patch up the ORDER BY clause
96574   */
96575   op = p->op;  
96576   pPrior = p->pPrior;
96577   assert( pPrior->pOrderBy==0 );
96578   pOrderBy = p->pOrderBy;
96579   assert( pOrderBy );
96580   nOrderBy = pOrderBy->nExpr;
96581
96582   /* For operators other than UNION ALL we have to make sure that
96583   ** the ORDER BY clause covers every term of the result set.  Add
96584   ** terms to the ORDER BY clause as necessary.
96585   */
96586   if( op!=TK_ALL ){
96587     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
96588       struct ExprList_item *pItem;
96589       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
96590         assert( pItem->iOrderByCol>0 );
96591         if( pItem->iOrderByCol==i ) break;
96592       }
96593       if( j==nOrderBy ){
96594         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
96595         if( pNew==0 ) return SQLITE_NOMEM;
96596         pNew->flags |= EP_IntValue;
96597         pNew->u.iValue = i;
96598         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
96599         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
96600       }
96601     }
96602   }
96603
96604   /* Compute the comparison permutation and keyinfo that is used with
96605   ** the permutation used to determine if the next
96606   ** row of results comes from selectA or selectB.  Also add explicit
96607   ** collations to the ORDER BY clause terms so that when the subqueries
96608   ** to the right and the left are evaluated, they use the correct
96609   ** collation.
96610   */
96611   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
96612   if( aPermute ){
96613     struct ExprList_item *pItem;
96614     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
96615       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
96616       aPermute[i] = pItem->iOrderByCol - 1;
96617     }
96618     pKeyMerge =
96619       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
96620     if( pKeyMerge ){
96621       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
96622       pKeyMerge->nField = (u16)nOrderBy;
96623       pKeyMerge->enc = ENC(db);
96624       for(i=0; i<nOrderBy; i++){
96625         CollSeq *pColl;
96626         Expr *pTerm = pOrderBy->a[i].pExpr;
96627         if( pTerm->flags & EP_Collate ){
96628           pColl = sqlite3ExprCollSeq(pParse, pTerm);
96629         }else{
96630           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
96631           if( pColl==0 ) pColl = db->pDfltColl;
96632           pOrderBy->a[i].pExpr =
96633              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
96634         }
96635         pKeyMerge->aColl[i] = pColl;
96636         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
96637       }
96638     }
96639   }else{
96640     pKeyMerge = 0;
96641   }
96642
96643   /* Reattach the ORDER BY clause to the query.
96644   */
96645   p->pOrderBy = pOrderBy;
96646   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
96647
96648   /* Allocate a range of temporary registers and the KeyInfo needed
96649   ** for the logic that removes duplicate result rows when the
96650   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
96651   */
96652   if( op==TK_ALL ){
96653     regPrev = 0;
96654   }else{
96655     int nExpr = p->pEList->nExpr;
96656     assert( nOrderBy>=nExpr || db->mallocFailed );
96657     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
96658     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
96659     pKeyDup = sqlite3DbMallocZero(db,
96660                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
96661     if( pKeyDup ){
96662       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
96663       pKeyDup->nField = (u16)nExpr;
96664       pKeyDup->enc = ENC(db);
96665       for(i=0; i<nExpr; i++){
96666         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
96667         pKeyDup->aSortOrder[i] = 0;
96668       }
96669     }
96670   }
96671  
96672   /* Separate the left and the right query from one another
96673   */
96674   p->pPrior = 0;
96675   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
96676   if( pPrior->pPrior==0 ){
96677     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
96678   }
96679
96680   /* Compute the limit registers */
96681   computeLimitRegisters(pParse, p, labelEnd);
96682   if( p->iLimit && op==TK_ALL ){
96683     regLimitA = ++pParse->nMem;
96684     regLimitB = ++pParse->nMem;
96685     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
96686                                   regLimitA);
96687     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
96688   }else{
96689     regLimitA = regLimitB = 0;
96690   }
96691   sqlite3ExprDelete(db, p->pLimit);
96692   p->pLimit = 0;
96693   sqlite3ExprDelete(db, p->pOffset);
96694   p->pOffset = 0;
96695
96696   regAddrA = ++pParse->nMem;
96697   regEofA = ++pParse->nMem;
96698   regAddrB = ++pParse->nMem;
96699   regEofB = ++pParse->nMem;
96700   regOutA = ++pParse->nMem;
96701   regOutB = ++pParse->nMem;
96702   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
96703   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
96704
96705   /* Jump past the various subroutines and coroutines to the main
96706   ** merge loop
96707   */
96708   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
96709   addrSelectA = sqlite3VdbeCurrentAddr(v);
96710
96711
96712   /* Generate a coroutine to evaluate the SELECT statement to the
96713   ** left of the compound operator - the "A" select.
96714   */
96715   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
96716   pPrior->iLimit = regLimitA;
96717   explainSetInteger(iSub1, pParse->iNextSelectId);
96718   sqlite3Select(pParse, pPrior, &destA);
96719   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
96720   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96721   VdbeNoopComment((v, "End coroutine for left SELECT"));
96722
96723   /* Generate a coroutine to evaluate the SELECT statement on 
96724   ** the right - the "B" select
96725   */
96726   addrSelectB = sqlite3VdbeCurrentAddr(v);
96727   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
96728   savedLimit = p->iLimit;
96729   savedOffset = p->iOffset;
96730   p->iLimit = regLimitB;
96731   p->iOffset = 0;  
96732   explainSetInteger(iSub2, pParse->iNextSelectId);
96733   sqlite3Select(pParse, p, &destB);
96734   p->iLimit = savedLimit;
96735   p->iOffset = savedOffset;
96736   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
96737   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96738   VdbeNoopComment((v, "End coroutine for right SELECT"));
96739
96740   /* Generate a subroutine that outputs the current row of the A
96741   ** select as the next output row of the compound select.
96742   */
96743   VdbeNoopComment((v, "Output routine for A"));
96744   addrOutA = generateOutputSubroutine(pParse,
96745                  p, &destA, pDest, regOutA,
96746                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
96747   
96748   /* Generate a subroutine that outputs the current row of the B
96749   ** select as the next output row of the compound select.
96750   */
96751   if( op==TK_ALL || op==TK_UNION ){
96752     VdbeNoopComment((v, "Output routine for B"));
96753     addrOutB = generateOutputSubroutine(pParse,
96754                  p, &destB, pDest, regOutB,
96755                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
96756   }
96757
96758   /* Generate a subroutine to run when the results from select A
96759   ** are exhausted and only data in select B remains.
96760   */
96761   VdbeNoopComment((v, "eof-A subroutine"));
96762   if( op==TK_EXCEPT || op==TK_INTERSECT ){
96763     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
96764   }else{  
96765     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
96766     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96767     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96768     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
96769     p->nSelectRow += pPrior->nSelectRow;
96770   }
96771
96772   /* Generate a subroutine to run when the results from select B
96773   ** are exhausted and only data in select A remains.
96774   */
96775   if( op==TK_INTERSECT ){
96776     addrEofB = addrEofA;
96777     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96778   }else{  
96779     VdbeNoopComment((v, "eof-B subroutine"));
96780     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
96781     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96782     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96783     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
96784   }
96785
96786   /* Generate code to handle the case of A<B
96787   */
96788   VdbeNoopComment((v, "A-lt-B subroutine"));
96789   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96790   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96791   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96792   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96793
96794   /* Generate code to handle the case of A==B
96795   */
96796   if( op==TK_ALL ){
96797     addrAeqB = addrAltB;
96798   }else if( op==TK_INTERSECT ){
96799     addrAeqB = addrAltB;
96800     addrAltB++;
96801   }else{
96802     VdbeNoopComment((v, "A-eq-B subroutine"));
96803     addrAeqB =
96804     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96805     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96806     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96807   }
96808
96809   /* Generate code to handle the case of A>B
96810   */
96811   VdbeNoopComment((v, "A-gt-B subroutine"));
96812   addrAgtB = sqlite3VdbeCurrentAddr(v);
96813   if( op==TK_ALL || op==TK_UNION ){
96814     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96815   }
96816   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96817   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96818   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96819
96820   /* This code runs once to initialize everything.
96821   */
96822   sqlite3VdbeJumpHere(v, j1);
96823   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96824   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96825   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96826   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96827   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96828   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96829
96830   /* Implement the main merge loop
96831   */
96832   sqlite3VdbeResolveLabel(v, labelCmpr);
96833   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96834   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
96835                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96836   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
96837   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96838
96839   /* Release temporary registers
96840   */
96841   if( regPrev ){
96842     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96843   }
96844
96845   /* Jump to the this point in order to terminate the query.
96846   */
96847   sqlite3VdbeResolveLabel(v, labelEnd);
96848
96849   /* Set the number of output columns
96850   */
96851   if( pDest->eDest==SRT_Output ){
96852     Select *pFirst = pPrior;
96853     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96854     generateColumnNames(pParse, 0, pFirst->pEList);
96855   }
96856
96857   /* Reassembly the compound query so that it will be freed correctly
96858   ** by the calling function */
96859   if( p->pPrior ){
96860     sqlite3SelectDelete(db, p->pPrior);
96861   }
96862   p->pPrior = pPrior;
96863
96864   /*** TBD:  Insert subroutine calls to close cursors on incomplete
96865   **** subqueries ****/
96866   explainComposite(pParse, p->op, iSub1, iSub2, 0);
96867   return SQLITE_OK;
96868 }
96869 #endif
96870
96871 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96872 /* Forward Declarations */
96873 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
96874 static void substSelect(sqlite3*, Select *, int, ExprList *);
96875
96876 /*
96877 ** Scan through the expression pExpr.  Replace every reference to
96878 ** a column in table number iTable with a copy of the iColumn-th
96879 ** entry in pEList.  (But leave references to the ROWID column 
96880 ** unchanged.)
96881 **
96882 ** This routine is part of the flattening procedure.  A subquery
96883 ** whose result set is defined by pEList appears as entry in the
96884 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
96885 ** FORM clause entry is iTable.  This routine make the necessary 
96886 ** changes to pExpr so that it refers directly to the source table
96887 ** of the subquery rather the result set of the subquery.
96888 */
96889 static Expr *substExpr(
96890   sqlite3 *db,        /* Report malloc errors to this connection */
96891   Expr *pExpr,        /* Expr in which substitution occurs */
96892   int iTable,         /* Table to be substituted */
96893   ExprList *pEList    /* Substitute expressions */
96894 ){
96895   if( pExpr==0 ) return 0;
96896   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
96897     if( pExpr->iColumn<0 ){
96898       pExpr->op = TK_NULL;
96899     }else{
96900       Expr *pNew;
96901       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
96902       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
96903       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
96904       sqlite3ExprDelete(db, pExpr);
96905       pExpr = pNew;
96906     }
96907   }else{
96908     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
96909     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
96910     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96911       substSelect(db, pExpr->x.pSelect, iTable, pEList);
96912     }else{
96913       substExprList(db, pExpr->x.pList, iTable, pEList);
96914     }
96915   }
96916   return pExpr;
96917 }
96918 static void substExprList(
96919   sqlite3 *db,         /* Report malloc errors here */
96920   ExprList *pList,     /* List to scan and in which to make substitutes */
96921   int iTable,          /* Table to be substituted */
96922   ExprList *pEList     /* Substitute values */
96923 ){
96924   int i;
96925   if( pList==0 ) return;
96926   for(i=0; i<pList->nExpr; i++){
96927     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
96928   }
96929 }
96930 static void substSelect(
96931   sqlite3 *db,         /* Report malloc errors here */
96932   Select *p,           /* SELECT statement in which to make substitutions */
96933   int iTable,          /* Table to be replaced */
96934   ExprList *pEList     /* Substitute values */
96935 ){
96936   SrcList *pSrc;
96937   struct SrcList_item *pItem;
96938   int i;
96939   if( !p ) return;
96940   substExprList(db, p->pEList, iTable, pEList);
96941   substExprList(db, p->pGroupBy, iTable, pEList);
96942   substExprList(db, p->pOrderBy, iTable, pEList);
96943   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
96944   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
96945   substSelect(db, p->pPrior, iTable, pEList);
96946   pSrc = p->pSrc;
96947   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
96948   if( ALWAYS(pSrc) ){
96949     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
96950       substSelect(db, pItem->pSelect, iTable, pEList);
96951     }
96952   }
96953 }
96954 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
96955
96956 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96957 /*
96958 ** This routine attempts to flatten subqueries as a performance optimization.
96959 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
96960 **
96961 ** To understand the concept of flattening, consider the following
96962 ** query:
96963 **
96964 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
96965 **
96966 ** The default way of implementing this query is to execute the
96967 ** subquery first and store the results in a temporary table, then
96968 ** run the outer query on that temporary table.  This requires two
96969 ** passes over the data.  Furthermore, because the temporary table
96970 ** has no indices, the WHERE clause on the outer query cannot be
96971 ** optimized.
96972 **
96973 ** This routine attempts to rewrite queries such as the above into
96974 ** a single flat select, like this:
96975 **
96976 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
96977 **
96978 ** The code generated for this simpification gives the same result
96979 ** but only has to scan the data once.  And because indices might 
96980 ** exist on the table t1, a complete scan of the data might be
96981 ** avoided.
96982 **
96983 ** Flattening is only attempted if all of the following are true:
96984 **
96985 **   (1)  The subquery and the outer query do not both use aggregates.
96986 **
96987 **   (2)  The subquery is not an aggregate or the outer query is not a join.
96988 **
96989 **   (3)  The subquery is not the right operand of a left outer join
96990 **        (Originally ticket #306.  Strengthened by ticket #3300)
96991 **
96992 **   (4)  The subquery is not DISTINCT.
96993 **
96994 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
96995 **        sub-queries that were excluded from this optimization. Restriction 
96996 **        (4) has since been expanded to exclude all DISTINCT subqueries.
96997 **
96998 **   (6)  The subquery does not use aggregates or the outer query is not
96999 **        DISTINCT.
97000 **
97001 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
97002 **        A FROM clause, consider adding a FROM close with the special
97003 **        table sqlite_once that consists of a single row containing a
97004 **        single NULL.
97005 **
97006 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
97007 **
97008 **   (9)  The subquery does not use LIMIT or the outer query does not use
97009 **        aggregates.
97010 **
97011 **  (10)  The subquery does not use aggregates or the outer query does not
97012 **        use LIMIT.
97013 **
97014 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
97015 **
97016 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
97017 **        a separate restriction deriving from ticket #350.
97018 **
97019 **  (13)  The subquery and outer query do not both use LIMIT.
97020 **
97021 **  (14)  The subquery does not use OFFSET.
97022 **
97023 **  (15)  The outer query is not part of a compound select or the
97024 **        subquery does not have a LIMIT clause.
97025 **        (See ticket #2339 and ticket [02a8e81d44]).
97026 **
97027 **  (16)  The outer query is not an aggregate or the subquery does
97028 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
97029 **        until we introduced the group_concat() function.  
97030 **
97031 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
97032 **        compound clause made up entirely of non-aggregate queries, and 
97033 **        the parent query:
97034 **
97035 **          * is not itself part of a compound select,
97036 **          * is not an aggregate or DISTINCT query, and
97037 **          * is not a join
97038 **
97039 **        The parent and sub-query may contain WHERE clauses. Subject to
97040 **        rules (11), (13) and (14), they may also contain ORDER BY,
97041 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
97042 **        operator other than UNION ALL because all the other compound
97043 **        operators have an implied DISTINCT which is disallowed by
97044 **        restriction (4).
97045 **
97046 **        Also, each component of the sub-query must return the same number
97047 **        of result columns. This is actually a requirement for any compound
97048 **        SELECT statement, but all the code here does is make sure that no
97049 **        such (illegal) sub-query is flattened. The caller will detect the
97050 **        syntax error and return a detailed message.
97051 **
97052 **  (18)  If the sub-query is a compound select, then all terms of the
97053 **        ORDER by clause of the parent must be simple references to 
97054 **        columns of the sub-query.
97055 **
97056 **  (19)  The subquery does not use LIMIT or the outer query does not
97057 **        have a WHERE clause.
97058 **
97059 **  (20)  If the sub-query is a compound select, then it must not use
97060 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
97061 **        somewhat by saying that the terms of the ORDER BY clause must
97062 **        appear as unmodified result columns in the outer query.  But we
97063 **        have other optimizations in mind to deal with that case.
97064 **
97065 **  (21)  The subquery does not use LIMIT or the outer query is not
97066 **        DISTINCT.  (See ticket [752e1646fc]).
97067 **
97068 ** In this routine, the "p" parameter is a pointer to the outer query.
97069 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
97070 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
97071 **
97072 ** If flattening is not attempted, this routine is a no-op and returns 0.
97073 ** If flattening is attempted this routine returns 1.
97074 **
97075 ** All of the expression analysis must occur on both the outer query and
97076 ** the subquery before this routine runs.
97077 */
97078 static int flattenSubquery(
97079   Parse *pParse,       /* Parsing context */
97080   Select *p,           /* The parent or outer SELECT statement */
97081   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
97082   int isAgg,           /* True if outer SELECT uses aggregate functions */
97083   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
97084 ){
97085   const char *zSavedAuthContext = pParse->zAuthContext;
97086   Select *pParent;
97087   Select *pSub;       /* The inner query or "subquery" */
97088   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
97089   SrcList *pSrc;      /* The FROM clause of the outer query */
97090   SrcList *pSubSrc;   /* The FROM clause of the subquery */
97091   ExprList *pList;    /* The result set of the outer query */
97092   int iParent;        /* VDBE cursor number of the pSub result set temp table */
97093   int i;              /* Loop counter */
97094   Expr *pWhere;                    /* The WHERE clause */
97095   struct SrcList_item *pSubitem;   /* The subquery */
97096   sqlite3 *db = pParse->db;
97097
97098   /* Check to see if flattening is permitted.  Return 0 if not.
97099   */
97100   assert( p!=0 );
97101   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
97102   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
97103   pSrc = p->pSrc;
97104   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
97105   pSubitem = &pSrc->a[iFrom];
97106   iParent = pSubitem->iCursor;
97107   pSub = pSubitem->pSelect;
97108   assert( pSub!=0 );
97109   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
97110   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
97111   pSubSrc = pSub->pSrc;
97112   assert( pSubSrc );
97113   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
97114   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
97115   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
97116   ** became arbitrary expressions, we were forced to add restrictions (13)
97117   ** and (14). */
97118   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
97119   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
97120   if( p->pRightmost && pSub->pLimit ){
97121     return 0;                                            /* Restriction (15) */
97122   }
97123   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
97124   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
97125   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
97126      return 0;         /* Restrictions (8)(9) */
97127   }
97128   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
97129      return 0;         /* Restriction (6)  */
97130   }
97131   if( p->pOrderBy && pSub->pOrderBy ){
97132      return 0;                                           /* Restriction (11) */
97133   }
97134   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
97135   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
97136   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
97137      return 0;         /* Restriction (21) */
97138   }
97139
97140   /* OBSOLETE COMMENT 1:
97141   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
97142   ** not used as the right operand of an outer join.  Examples of why this
97143   ** is not allowed:
97144   **
97145   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
97146   **
97147   ** If we flatten the above, we would get
97148   **
97149   **         (t1 LEFT OUTER JOIN t2) JOIN t3
97150   **
97151   ** which is not at all the same thing.
97152   **
97153   ** OBSOLETE COMMENT 2:
97154   ** Restriction 12:  If the subquery is the right operand of a left outer
97155   ** join, make sure the subquery has no WHERE clause.
97156   ** An examples of why this is not allowed:
97157   **
97158   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
97159   **
97160   ** If we flatten the above, we would get
97161   **
97162   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
97163   **
97164   ** But the t2.x>0 test will always fail on a NULL row of t2, which
97165   ** effectively converts the OUTER JOIN into an INNER JOIN.
97166   **
97167   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
97168   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
97169   ** is fraught with danger.  Best to avoid the whole thing.  If the
97170   ** subquery is the right term of a LEFT JOIN, then do not flatten.
97171   */
97172   if( (pSubitem->jointype & JT_OUTER)!=0 ){
97173     return 0;
97174   }
97175
97176   /* Restriction 17: If the sub-query is a compound SELECT, then it must
97177   ** use only the UNION ALL operator. And none of the simple select queries
97178   ** that make up the compound SELECT are allowed to be aggregate or distinct
97179   ** queries.
97180   */
97181   if( pSub->pPrior ){
97182     if( pSub->pOrderBy ){
97183       return 0;  /* Restriction 20 */
97184     }
97185     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
97186       return 0;
97187     }
97188     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
97189       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
97190       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
97191       assert( pSub->pSrc!=0 );
97192       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
97193        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
97194        || pSub1->pSrc->nSrc<1
97195        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
97196       ){
97197         return 0;
97198       }
97199       testcase( pSub1->pSrc->nSrc>1 );
97200     }
97201
97202     /* Restriction 18. */
97203     if( p->pOrderBy ){
97204       int ii;
97205       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
97206         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
97207       }
97208     }
97209   }
97210
97211   /***** If we reach this point, flattening is permitted. *****/
97212
97213   /* Authorize the subquery */
97214   pParse->zAuthContext = pSubitem->zName;
97215   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
97216   testcase( i==SQLITE_DENY );
97217   pParse->zAuthContext = zSavedAuthContext;
97218
97219   /* If the sub-query is a compound SELECT statement, then (by restrictions
97220   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
97221   ** be of the form:
97222   **
97223   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
97224   **
97225   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97226   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
97227   ** OFFSET clauses and joins them to the left-hand-side of the original
97228   ** using UNION ALL operators. In this case N is the number of simple
97229   ** select statements in the compound sub-query.
97230   **
97231   ** Example:
97232   **
97233   **     SELECT a+1 FROM (
97234   **        SELECT x FROM tab
97235   **        UNION ALL
97236   **        SELECT y FROM tab
97237   **        UNION ALL
97238   **        SELECT abs(z*2) FROM tab2
97239   **     ) WHERE a!=5 ORDER BY 1
97240   **
97241   ** Transformed into:
97242   **
97243   **     SELECT x+1 FROM tab WHERE x+1!=5
97244   **     UNION ALL
97245   **     SELECT y+1 FROM tab WHERE y+1!=5
97246   **     UNION ALL
97247   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97248   **     ORDER BY 1
97249   **
97250   ** We call this the "compound-subquery flattening".
97251   */
97252   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97253     Select *pNew;
97254     ExprList *pOrderBy = p->pOrderBy;
97255     Expr *pLimit = p->pLimit;
97256     Select *pPrior = p->pPrior;
97257     p->pOrderBy = 0;
97258     p->pSrc = 0;
97259     p->pPrior = 0;
97260     p->pLimit = 0;
97261     pNew = sqlite3SelectDup(db, p, 0);
97262     p->pLimit = pLimit;
97263     p->pOrderBy = pOrderBy;
97264     p->pSrc = pSrc;
97265     p->op = TK_ALL;
97266     p->pRightmost = 0;
97267     if( pNew==0 ){
97268       pNew = pPrior;
97269     }else{
97270       pNew->pPrior = pPrior;
97271       pNew->pRightmost = 0;
97272     }
97273     p->pPrior = pNew;
97274     if( db->mallocFailed ) return 1;
97275   }
97276
97277   /* Begin flattening the iFrom-th entry of the FROM clause 
97278   ** in the outer query.
97279   */
97280   pSub = pSub1 = pSubitem->pSelect;
97281
97282   /* Delete the transient table structure associated with the
97283   ** subquery
97284   */
97285   sqlite3DbFree(db, pSubitem->zDatabase);
97286   sqlite3DbFree(db, pSubitem->zName);
97287   sqlite3DbFree(db, pSubitem->zAlias);
97288   pSubitem->zDatabase = 0;
97289   pSubitem->zName = 0;
97290   pSubitem->zAlias = 0;
97291   pSubitem->pSelect = 0;
97292
97293   /* Defer deleting the Table object associated with the
97294   ** subquery until code generation is
97295   ** complete, since there may still exist Expr.pTab entries that
97296   ** refer to the subquery even after flattening.  Ticket #3346.
97297   **
97298   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97299   */
97300   if( ALWAYS(pSubitem->pTab!=0) ){
97301     Table *pTabToDel = pSubitem->pTab;
97302     if( pTabToDel->nRef==1 ){
97303       Parse *pToplevel = sqlite3ParseToplevel(pParse);
97304       pTabToDel->pNextZombie = pToplevel->pZombieTab;
97305       pToplevel->pZombieTab = pTabToDel;
97306     }else{
97307       pTabToDel->nRef--;
97308     }
97309     pSubitem->pTab = 0;
97310   }
97311
97312   /* The following loop runs once for each term in a compound-subquery
97313   ** flattening (as described above).  If we are doing a different kind
97314   ** of flattening - a flattening other than a compound-subquery flattening -
97315   ** then this loop only runs once.
97316   **
97317   ** This loop moves all of the FROM elements of the subquery into the
97318   ** the FROM clause of the outer query.  Before doing this, remember
97319   ** the cursor number for the original outer query FROM element in
97320   ** iParent.  The iParent cursor will never be used.  Subsequent code
97321   ** will scan expressions looking for iParent references and replace
97322   ** those references with expressions that resolve to the subquery FROM
97323   ** elements we are now copying in.
97324   */
97325   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97326     int nSubSrc;
97327     u8 jointype = 0;
97328     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97329     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97330     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97331
97332     if( pSrc ){
97333       assert( pParent==p );  /* First time through the loop */
97334       jointype = pSubitem->jointype;
97335     }else{
97336       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97337       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97338       if( pSrc==0 ){
97339         assert( db->mallocFailed );
97340         break;
97341       }
97342     }
97343
97344     /* The subquery uses a single slot of the FROM clause of the outer
97345     ** query.  If the subquery has more than one element in its FROM clause,
97346     ** then expand the outer query to make space for it to hold all elements
97347     ** of the subquery.
97348     **
97349     ** Example:
97350     **
97351     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97352     **
97353     ** The outer query has 3 slots in its FROM clause.  One slot of the
97354     ** outer query (the middle slot) is used by the subquery.  The next
97355     ** block of code will expand the out query to 4 slots.  The middle
97356     ** slot is expanded to two slots in order to make space for the
97357     ** two elements in the FROM clause of the subquery.
97358     */
97359     if( nSubSrc>1 ){
97360       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97361       if( db->mallocFailed ){
97362         break;
97363       }
97364     }
97365
97366     /* Transfer the FROM clause terms from the subquery into the
97367     ** outer query.
97368     */
97369     for(i=0; i<nSubSrc; i++){
97370       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97371       pSrc->a[i+iFrom] = pSubSrc->a[i];
97372       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97373     }
97374     pSrc->a[iFrom].jointype = jointype;
97375   
97376     /* Now begin substituting subquery result set expressions for 
97377     ** references to the iParent in the outer query.
97378     ** 
97379     ** Example:
97380     **
97381     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97382     **   \                     \_____________ subquery __________/          /
97383     **    \_____________________ outer query ______________________________/
97384     **
97385     ** We look at every expression in the outer query and every place we see
97386     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97387     */
97388     pList = pParent->pEList;
97389     for(i=0; i<pList->nExpr; i++){
97390       if( pList->a[i].zName==0 ){
97391         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
97392         sqlite3Dequote(zName);
97393         pList->a[i].zName = zName;
97394       }
97395     }
97396     substExprList(db, pParent->pEList, iParent, pSub->pEList);
97397     if( isAgg ){
97398       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97399       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97400     }
97401     if( pSub->pOrderBy ){
97402       assert( pParent->pOrderBy==0 );
97403       pParent->pOrderBy = pSub->pOrderBy;
97404       pSub->pOrderBy = 0;
97405     }else if( pParent->pOrderBy ){
97406       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97407     }
97408     if( pSub->pWhere ){
97409       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
97410     }else{
97411       pWhere = 0;
97412     }
97413     if( subqueryIsAgg ){
97414       assert( pParent->pHaving==0 );
97415       pParent->pHaving = pParent->pWhere;
97416       pParent->pWhere = pWhere;
97417       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97418       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
97419                                   sqlite3ExprDup(db, pSub->pHaving, 0));
97420       assert( pParent->pGroupBy==0 );
97421       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
97422     }else{
97423       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97424       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
97425     }
97426   
97427     /* The flattened query is distinct if either the inner or the
97428     ** outer query is distinct. 
97429     */
97430     pParent->selFlags |= pSub->selFlags & SF_Distinct;
97431   
97432     /*
97433     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97434     **
97435     ** One is tempted to try to add a and b to combine the limits.  But this
97436     ** does not work if either limit is negative.
97437     */
97438     if( pSub->pLimit ){
97439       pParent->pLimit = pSub->pLimit;
97440       pSub->pLimit = 0;
97441     }
97442   }
97443
97444   /* Finially, delete what is left of the subquery and return
97445   ** success.
97446   */
97447   sqlite3SelectDelete(db, pSub1);
97448
97449   return 1;
97450 }
97451 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97452
97453 /*
97454 ** Analyze the SELECT statement passed as an argument to see if it
97455 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
97456 ** it is, or 0 otherwise. At present, a query is considered to be
97457 ** a min()/max() query if:
97458 **
97459 **   1. There is a single object in the FROM clause.
97460 **
97461 **   2. There is a single expression in the result set, and it is
97462 **      either min(x) or max(x), where x is a column reference.
97463 */
97464 static u8 minMaxQuery(Select *p){
97465   Expr *pExpr;
97466   ExprList *pEList = p->pEList;
97467
97468   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
97469   pExpr = pEList->a[0].pExpr;
97470   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97471   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
97472   pEList = pExpr->x.pList;
97473   if( pEList==0 || pEList->nExpr!=1 ) return 0;
97474   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
97475   assert( !ExprHasProperty(pExpr, EP_IntValue) );
97476   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
97477     return WHERE_ORDERBY_MIN;
97478   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
97479     return WHERE_ORDERBY_MAX;
97480   }
97481   return WHERE_ORDERBY_NORMAL;
97482 }
97483
97484 /*
97485 ** The select statement passed as the first argument is an aggregate query.
97486 ** The second argment is the associated aggregate-info object. This 
97487 ** function tests if the SELECT is of the form:
97488 **
97489 **   SELECT count(*) FROM <tbl>
97490 **
97491 ** where table is a database table, not a sub-select or view. If the query
97492 ** does match this pattern, then a pointer to the Table object representing
97493 ** <tbl> is returned. Otherwise, 0 is returned.
97494 */
97495 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97496   Table *pTab;
97497   Expr *pExpr;
97498
97499   assert( !p->pGroupBy );
97500
97501   if( p->pWhere || p->pEList->nExpr!=1 
97502    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97503   ){
97504     return 0;
97505   }
97506   pTab = p->pSrc->a[0].pTab;
97507   pExpr = p->pEList->a[0].pExpr;
97508   assert( pTab && !pTab->pSelect && pExpr );
97509
97510   if( IsVirtual(pTab) ) return 0;
97511   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97512   if( NEVER(pAggInfo->nFunc==0) ) return 0;
97513   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
97514   if( pExpr->flags&EP_Distinct ) return 0;
97515
97516   return pTab;
97517 }
97518
97519 /*
97520 ** If the source-list item passed as an argument was augmented with an
97521 ** INDEXED BY clause, then try to locate the specified index. If there
97522 ** was such a clause and the named index cannot be found, return 
97523 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
97524 ** pFrom->pIndex and return SQLITE_OK.
97525 */
97526 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97527   if( pFrom->pTab && pFrom->zIndex ){
97528     Table *pTab = pFrom->pTab;
97529     char *zIndex = pFrom->zIndex;
97530     Index *pIdx;
97531     for(pIdx=pTab->pIndex; 
97532         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
97533         pIdx=pIdx->pNext
97534     );
97535     if( !pIdx ){
97536       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97537       pParse->checkSchema = 1;
97538       return SQLITE_ERROR;
97539     }
97540     pFrom->pIndex = pIdx;
97541   }
97542   return SQLITE_OK;
97543 }
97544
97545 /*
97546 ** This routine is a Walker callback for "expanding" a SELECT statement.
97547 ** "Expanding" means to do the following:
97548 **
97549 **    (1)  Make sure VDBE cursor numbers have been assigned to every
97550 **         element of the FROM clause.
97551 **
97552 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
97553 **         defines FROM clause.  When views appear in the FROM clause,
97554 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
97555 **         that implements the view.  A copy is made of the view's SELECT
97556 **         statement so that we can freely modify or delete that statement
97557 **         without worrying about messing up the presistent representation
97558 **         of the view.
97559 **
97560 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97561 **         on joins and the ON and USING clause of joins.
97562 **
97563 **    (4)  Scan the list of columns in the result set (pEList) looking
97564 **         for instances of the "*" operator or the TABLE.* operator.
97565 **         If found, expand each "*" to be every column in every table
97566 **         and TABLE.* to be every column in TABLE.
97567 **
97568 */
97569 static int selectExpander(Walker *pWalker, Select *p){
97570   Parse *pParse = pWalker->pParse;
97571   int i, j, k;
97572   SrcList *pTabList;
97573   ExprList *pEList;
97574   struct SrcList_item *pFrom;
97575   sqlite3 *db = pParse->db;
97576
97577   if( db->mallocFailed  ){
97578     return WRC_Abort;
97579   }
97580   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
97581     return WRC_Prune;
97582   }
97583   p->selFlags |= SF_Expanded;
97584   pTabList = p->pSrc;
97585   pEList = p->pEList;
97586
97587   /* Make sure cursor numbers have been assigned to all entries in
97588   ** the FROM clause of the SELECT statement.
97589   */
97590   sqlite3SrcListAssignCursors(pParse, pTabList);
97591
97592   /* Look up every table named in the FROM clause of the select.  If
97593   ** an entry of the FROM clause is a subquery instead of a table or view,
97594   ** then create a transient table structure to describe the subquery.
97595   */
97596   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97597     Table *pTab;
97598     if( pFrom->pTab!=0 ){
97599       /* This statement has already been prepared.  There is no need
97600       ** to go further. */
97601       assert( i==0 );
97602       return WRC_Prune;
97603     }
97604     if( pFrom->zName==0 ){
97605 #ifndef SQLITE_OMIT_SUBQUERY
97606       Select *pSel = pFrom->pSelect;
97607       /* A sub-query in the FROM clause of a SELECT */
97608       assert( pSel!=0 );
97609       assert( pFrom->pTab==0 );
97610       sqlite3WalkSelect(pWalker, pSel);
97611       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
97612       if( pTab==0 ) return WRC_Abort;
97613       pTab->nRef = 1;
97614       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
97615       while( pSel->pPrior ){ pSel = pSel->pPrior; }
97616       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
97617       pTab->iPKey = -1;
97618       pTab->nRowEst = 1000000;
97619       pTab->tabFlags |= TF_Ephemeral;
97620 #endif
97621     }else{
97622       /* An ordinary table or view name in the FROM clause */
97623       assert( pFrom->pTab==0 );
97624       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
97625       if( pTab==0 ) return WRC_Abort;
97626       pTab->nRef++;
97627 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
97628       if( pTab->pSelect || IsVirtual(pTab) ){
97629         /* We reach here if the named table is a really a view */
97630         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
97631         assert( pFrom->pSelect==0 );
97632         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
97633         sqlite3WalkSelect(pWalker, pFrom->pSelect);
97634       }
97635 #endif
97636     }
97637
97638     /* Locate the index named by the INDEXED BY clause, if any. */
97639     if( sqlite3IndexedByLookup(pParse, pFrom) ){
97640       return WRC_Abort;
97641     }
97642   }
97643
97644   /* Process NATURAL keywords, and ON and USING clauses of joins.
97645   */
97646   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
97647     return WRC_Abort;
97648   }
97649
97650   /* For every "*" that occurs in the column list, insert the names of
97651   ** all columns in all tables.  And for every TABLE.* insert the names
97652   ** of all columns in TABLE.  The parser inserted a special expression
97653   ** with the TK_ALL operator for each "*" that it found in the column list.
97654   ** The following code just has to locate the TK_ALL expressions and expand
97655   ** each one to the list of all columns in all tables.
97656   **
97657   ** The first loop just checks to see if there are any "*" operators
97658   ** that need expanding.
97659   */
97660   for(k=0; k<pEList->nExpr; k++){
97661     Expr *pE = pEList->a[k].pExpr;
97662     if( pE->op==TK_ALL ) break;
97663     assert( pE->op!=TK_DOT || pE->pRight!=0 );
97664     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
97665     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
97666   }
97667   if( k<pEList->nExpr ){
97668     /*
97669     ** If we get here it means the result set contains one or more "*"
97670     ** operators that need to be expanded.  Loop through each expression
97671     ** in the result set and expand them one by one.
97672     */
97673     struct ExprList_item *a = pEList->a;
97674     ExprList *pNew = 0;
97675     int flags = pParse->db->flags;
97676     int longNames = (flags & SQLITE_FullColNames)!=0
97677                       && (flags & SQLITE_ShortColNames)==0;
97678
97679     for(k=0; k<pEList->nExpr; k++){
97680       Expr *pE = a[k].pExpr;
97681       assert( pE->op!=TK_DOT || pE->pRight!=0 );
97682       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
97683         /* This particular expression does not need to be expanded.
97684         */
97685         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
97686         if( pNew ){
97687           pNew->a[pNew->nExpr-1].zName = a[k].zName;
97688           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
97689           a[k].zName = 0;
97690           a[k].zSpan = 0;
97691         }
97692         a[k].pExpr = 0;
97693       }else{
97694         /* This expression is a "*" or a "TABLE.*" and needs to be
97695         ** expanded. */
97696         int tableSeen = 0;      /* Set to 1 when TABLE matches */
97697         char *zTName;            /* text of name of TABLE */
97698         if( pE->op==TK_DOT ){
97699           assert( pE->pLeft!=0 );
97700           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
97701           zTName = pE->pLeft->u.zToken;
97702         }else{
97703           zTName = 0;
97704         }
97705         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97706           Table *pTab = pFrom->pTab;
97707           char *zTabName = pFrom->zAlias;
97708           if( zTabName==0 ){
97709             zTabName = pTab->zName;
97710           }
97711           if( db->mallocFailed ) break;
97712           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
97713             continue;
97714           }
97715           tableSeen = 1;
97716           for(j=0; j<pTab->nCol; j++){
97717             Expr *pExpr, *pRight;
97718             char *zName = pTab->aCol[j].zName;
97719             char *zColname;  /* The computed column name */
97720             char *zToFree;   /* Malloced string that needs to be freed */
97721             Token sColname;  /* Computed column name as a token */
97722
97723             /* If a column is marked as 'hidden' (currently only possible
97724             ** for virtual tables), do not include it in the expanded
97725             ** result-set list.
97726             */
97727             if( IsHiddenColumn(&pTab->aCol[j]) ){
97728               assert(IsVirtual(pTab));
97729               continue;
97730             }
97731
97732             if( i>0 && zTName==0 ){
97733               if( (pFrom->jointype & JT_NATURAL)!=0
97734                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
97735               ){
97736                 /* In a NATURAL join, omit the join columns from the 
97737                 ** table to the right of the join */
97738                 continue;
97739               }
97740               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
97741                 /* In a join with a USING clause, omit columns in the
97742                 ** using clause from the table on the right. */
97743                 continue;
97744               }
97745             }
97746             pRight = sqlite3Expr(db, TK_ID, zName);
97747             zColname = zName;
97748             zToFree = 0;
97749             if( longNames || pTabList->nSrc>1 ){
97750               Expr *pLeft;
97751               pLeft = sqlite3Expr(db, TK_ID, zTabName);
97752               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
97753               if( longNames ){
97754                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
97755                 zToFree = zColname;
97756               }
97757             }else{
97758               pExpr = pRight;
97759             }
97760             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
97761             sColname.z = zColname;
97762             sColname.n = sqlite3Strlen30(zColname);
97763             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
97764             sqlite3DbFree(db, zToFree);
97765           }
97766         }
97767         if( !tableSeen ){
97768           if( zTName ){
97769             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
97770           }else{
97771             sqlite3ErrorMsg(pParse, "no tables specified");
97772           }
97773         }
97774       }
97775     }
97776     sqlite3ExprListDelete(db, pEList);
97777     p->pEList = pNew;
97778   }
97779 #if SQLITE_MAX_COLUMN
97780   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
97781     sqlite3ErrorMsg(pParse, "too many columns in result set");
97782   }
97783 #endif
97784   return WRC_Continue;
97785 }
97786
97787 /*
97788 ** No-op routine for the parse-tree walker.
97789 **
97790 ** When this routine is the Walker.xExprCallback then expression trees
97791 ** are walked without any actions being taken at each node.  Presumably,
97792 ** when this routine is used for Walker.xExprCallback then 
97793 ** Walker.xSelectCallback is set to do something useful for every 
97794 ** subquery in the parser tree.
97795 */
97796 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97797   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97798   return WRC_Continue;
97799 }
97800
97801 /*
97802 ** This routine "expands" a SELECT statement and all of its subqueries.
97803 ** For additional information on what it means to "expand" a SELECT
97804 ** statement, see the comment on the selectExpand worker callback above.
97805 **
97806 ** Expanding a SELECT statement is the first step in processing a
97807 ** SELECT statement.  The SELECT statement must be expanded before
97808 ** name resolution is performed.
97809 **
97810 ** If anything goes wrong, an error message is written into pParse.
97811 ** The calling function can detect the problem by looking at pParse->nErr
97812 ** and/or pParse->db->mallocFailed.
97813 */
97814 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
97815   Walker w;
97816   w.xSelectCallback = selectExpander;
97817   w.xExprCallback = exprWalkNoop;
97818   w.pParse = pParse;
97819   sqlite3WalkSelect(&w, pSelect);
97820 }
97821
97822
97823 #ifndef SQLITE_OMIT_SUBQUERY
97824 /*
97825 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
97826 ** interface.
97827 **
97828 ** For each FROM-clause subquery, add Column.zType and Column.zColl
97829 ** information to the Table structure that represents the result set
97830 ** of that subquery.
97831 **
97832 ** The Table structure that represents the result set was constructed
97833 ** by selectExpander() but the type and collation information was omitted
97834 ** at that point because identifiers had not yet been resolved.  This
97835 ** routine is called after identifier resolution.
97836 */
97837 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97838   Parse *pParse;
97839   int i;
97840   SrcList *pTabList;
97841   struct SrcList_item *pFrom;
97842
97843   assert( p->selFlags & SF_Resolved );
97844   if( (p->selFlags & SF_HasTypeInfo)==0 ){
97845     p->selFlags |= SF_HasTypeInfo;
97846     pParse = pWalker->pParse;
97847     pTabList = p->pSrc;
97848     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97849       Table *pTab = pFrom->pTab;
97850       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97851         /* A sub-query in the FROM clause of a SELECT */
97852         Select *pSel = pFrom->pSelect;
97853         assert( pSel );
97854         while( pSel->pPrior ) pSel = pSel->pPrior;
97855         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
97856       }
97857     }
97858   }
97859   return WRC_Continue;
97860 }
97861 #endif
97862
97863
97864 /*
97865 ** This routine adds datatype and collating sequence information to
97866 ** the Table structures of all FROM-clause subqueries in a
97867 ** SELECT statement.
97868 **
97869 ** Use this routine after name resolution.
97870 */
97871 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
97872 #ifndef SQLITE_OMIT_SUBQUERY
97873   Walker w;
97874   w.xSelectCallback = selectAddSubqueryTypeInfo;
97875   w.xExprCallback = exprWalkNoop;
97876   w.pParse = pParse;
97877   sqlite3WalkSelect(&w, pSelect);
97878 #endif
97879 }
97880
97881
97882 /*
97883 ** This routine sets up a SELECT statement for processing.  The
97884 ** following is accomplished:
97885 **
97886 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
97887 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
97888 **     *  ON and USING clauses are shifted into WHERE statements
97889 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
97890 **     *  Identifiers in expression are matched to tables.
97891 **
97892 ** This routine acts recursively on all subqueries within the SELECT.
97893 */
97894 SQLITE_PRIVATE void sqlite3SelectPrep(
97895   Parse *pParse,         /* The parser context */
97896   Select *p,             /* The SELECT statement being coded. */
97897   NameContext *pOuterNC  /* Name context for container */
97898 ){
97899   sqlite3 *db;
97900   if( NEVER(p==0) ) return;
97901   db = pParse->db;
97902   if( p->selFlags & SF_HasTypeInfo ) return;
97903   sqlite3SelectExpand(pParse, p);
97904   if( pParse->nErr || db->mallocFailed ) return;
97905   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
97906   if( pParse->nErr || db->mallocFailed ) return;
97907   sqlite3SelectAddTypeInfo(pParse, p);
97908 }
97909
97910 /*
97911 ** Reset the aggregate accumulator.
97912 **
97913 ** The aggregate accumulator is a set of memory cells that hold
97914 ** intermediate results while calculating an aggregate.  This
97915 ** routine generates code that stores NULLs in all of those memory
97916 ** cells.
97917 */
97918 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
97919   Vdbe *v = pParse->pVdbe;
97920   int i;
97921   struct AggInfo_func *pFunc;
97922   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
97923     return;
97924   }
97925   for(i=0; i<pAggInfo->nColumn; i++){
97926     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
97927   }
97928   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
97929     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
97930     if( pFunc->iDistinct>=0 ){
97931       Expr *pE = pFunc->pExpr;
97932       assert( !ExprHasProperty(pE, EP_xIsSelect) );
97933       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
97934         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
97935            "argument");
97936         pFunc->iDistinct = -1;
97937       }else{
97938         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
97939         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
97940                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
97941       }
97942     }
97943   }
97944 }
97945
97946 /*
97947 ** Invoke the OP_AggFinalize opcode for every aggregate function
97948 ** in the AggInfo structure.
97949 */
97950 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
97951   Vdbe *v = pParse->pVdbe;
97952   int i;
97953   struct AggInfo_func *pF;
97954   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97955     ExprList *pList = pF->pExpr->x.pList;
97956     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97957     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
97958                       (void*)pF->pFunc, P4_FUNCDEF);
97959   }
97960 }
97961
97962 /*
97963 ** Update the accumulator memory cells for an aggregate based on
97964 ** the current cursor position.
97965 */
97966 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
97967   Vdbe *v = pParse->pVdbe;
97968   int i;
97969   int regHit = 0;
97970   int addrHitTest = 0;
97971   struct AggInfo_func *pF;
97972   struct AggInfo_col *pC;
97973
97974   pAggInfo->directMode = 1;
97975   sqlite3ExprCacheClear(pParse);
97976   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
97977     int nArg;
97978     int addrNext = 0;
97979     int regAgg;
97980     ExprList *pList = pF->pExpr->x.pList;
97981     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
97982     if( pList ){
97983       nArg = pList->nExpr;
97984       regAgg = sqlite3GetTempRange(pParse, nArg);
97985       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
97986     }else{
97987       nArg = 0;
97988       regAgg = 0;
97989     }
97990     if( pF->iDistinct>=0 ){
97991       addrNext = sqlite3VdbeMakeLabel(v);
97992       assert( nArg==1 );
97993       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
97994     }
97995     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
97996       CollSeq *pColl = 0;
97997       struct ExprList_item *pItem;
97998       int j;
97999       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
98000       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
98001         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
98002       }
98003       if( !pColl ){
98004         pColl = pParse->db->pDfltColl;
98005       }
98006       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
98007       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
98008     }
98009     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
98010                       (void*)pF->pFunc, P4_FUNCDEF);
98011     sqlite3VdbeChangeP5(v, (u8)nArg);
98012     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
98013     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
98014     if( addrNext ){
98015       sqlite3VdbeResolveLabel(v, addrNext);
98016       sqlite3ExprCacheClear(pParse);
98017     }
98018   }
98019
98020   /* Before populating the accumulator registers, clear the column cache.
98021   ** Otherwise, if any of the required column values are already present 
98022   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
98023   ** to pC->iMem. But by the time the value is used, the original register
98024   ** may have been used, invalidating the underlying buffer holding the
98025   ** text or blob value. See ticket [883034dcb5].
98026   **
98027   ** Another solution would be to change the OP_SCopy used to copy cached
98028   ** values to an OP_Copy.
98029   */
98030   if( regHit ){
98031     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
98032   }
98033   sqlite3ExprCacheClear(pParse);
98034   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
98035     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
98036   }
98037   pAggInfo->directMode = 0;
98038   sqlite3ExprCacheClear(pParse);
98039   if( addrHitTest ){
98040     sqlite3VdbeJumpHere(v, addrHitTest);
98041   }
98042 }
98043
98044 /*
98045 ** Add a single OP_Explain instruction to the VDBE to explain a simple
98046 ** count(*) query ("SELECT count(*) FROM pTab").
98047 */
98048 #ifndef SQLITE_OMIT_EXPLAIN
98049 static void explainSimpleCount(
98050   Parse *pParse,                  /* Parse context */
98051   Table *pTab,                    /* Table being queried */
98052   Index *pIdx                     /* Index used to optimize scan, or NULL */
98053 ){
98054   if( pParse->explain==2 ){
98055     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
98056         pTab->zName, 
98057         pIdx ? "USING COVERING INDEX " : "",
98058         pIdx ? pIdx->zName : "",
98059         pTab->nRowEst
98060     );
98061     sqlite3VdbeAddOp4(
98062         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
98063     );
98064   }
98065 }
98066 #else
98067 # define explainSimpleCount(a,b,c)
98068 #endif
98069
98070 /*
98071 ** Generate code for the SELECT statement given in the p argument.  
98072 **
98073 ** The results are distributed in various ways depending on the
98074 ** contents of the SelectDest structure pointed to by argument pDest
98075 ** as follows:
98076 **
98077 **     pDest->eDest    Result
98078 **     ------------    -------------------------------------------
98079 **     SRT_Output      Generate a row of output (using the OP_ResultRow
98080 **                     opcode) for each row in the result set.
98081 **
98082 **     SRT_Mem         Only valid if the result is a single column.
98083 **                     Store the first column of the first result row
98084 **                     in register pDest->iSDParm then abandon the rest
98085 **                     of the query.  This destination implies "LIMIT 1".
98086 **
98087 **     SRT_Set         The result must be a single column.  Store each
98088 **                     row of result as the key in table pDest->iSDParm. 
98089 **                     Apply the affinity pDest->affSdst before storing
98090 **                     results.  Used to implement "IN (SELECT ...)".
98091 **
98092 **     SRT_Union       Store results as a key in a temporary table 
98093 **                     identified by pDest->iSDParm.
98094 **
98095 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
98096 **
98097 **     SRT_Table       Store results in temporary table pDest->iSDParm.
98098 **                     This is like SRT_EphemTab except that the table
98099 **                     is assumed to already be open.
98100 **
98101 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
98102 **                     the result there. The cursor is left open after
98103 **                     returning.  This is like SRT_Table except that
98104 **                     this destination uses OP_OpenEphemeral to create
98105 **                     the table first.
98106 **
98107 **     SRT_Coroutine   Generate a co-routine that returns a new row of
98108 **                     results each time it is invoked.  The entry point
98109 **                     of the co-routine is stored in register pDest->iSDParm.
98110 **
98111 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
98112 **                     set is not empty.
98113 **
98114 **     SRT_Discard     Throw the results away.  This is used by SELECT
98115 **                     statements within triggers whose only purpose is
98116 **                     the side-effects of functions.
98117 **
98118 ** This routine returns the number of errors.  If any errors are
98119 ** encountered, then an appropriate error message is left in
98120 ** pParse->zErrMsg.
98121 **
98122 ** This routine does NOT free the Select structure passed in.  The
98123 ** calling function needs to do that.
98124 */
98125 SQLITE_PRIVATE int sqlite3Select(
98126   Parse *pParse,         /* The parser context */
98127   Select *p,             /* The SELECT statement being coded. */
98128   SelectDest *pDest      /* What to do with the query results */
98129 ){
98130   int i, j;              /* Loop counters */
98131   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
98132   Vdbe *v;               /* The virtual machine under construction */
98133   int isAgg;             /* True for select lists like "count(*)" */
98134   ExprList *pEList;      /* List of columns to extract. */
98135   SrcList *pTabList;     /* List of tables to select from */
98136   Expr *pWhere;          /* The WHERE clause.  May be NULL */
98137   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
98138   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
98139   Expr *pHaving;         /* The HAVING clause.  May be NULL */
98140   int rc = 1;            /* Value to return from this function */
98141   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
98142   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
98143   AggInfo sAggInfo;      /* Information used by aggregate queries */
98144   int iEnd;              /* Address of the end of the query */
98145   sqlite3 *db;           /* The database connection */
98146
98147 #ifndef SQLITE_OMIT_EXPLAIN
98148   int iRestoreSelectId = pParse->iSelectId;
98149   pParse->iSelectId = pParse->iNextSelectId++;
98150 #endif
98151
98152   db = pParse->db;
98153   if( p==0 || db->mallocFailed || pParse->nErr ){
98154     return 1;
98155   }
98156   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
98157   memset(&sAggInfo, 0, sizeof(sAggInfo));
98158
98159   if( IgnorableOrderby(pDest) ){
98160     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
98161            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
98162     /* If ORDER BY makes no difference in the output then neither does
98163     ** DISTINCT so it can be removed too. */
98164     sqlite3ExprListDelete(db, p->pOrderBy);
98165     p->pOrderBy = 0;
98166     p->selFlags &= ~SF_Distinct;
98167   }
98168   sqlite3SelectPrep(pParse, p, 0);
98169   pOrderBy = p->pOrderBy;
98170   pTabList = p->pSrc;
98171   pEList = p->pEList;
98172   if( pParse->nErr || db->mallocFailed ){
98173     goto select_end;
98174   }
98175   isAgg = (p->selFlags & SF_Aggregate)!=0;
98176   assert( pEList!=0 );
98177
98178   /* Begin generating code.
98179   */
98180   v = sqlite3GetVdbe(pParse);
98181   if( v==0 ) goto select_end;
98182
98183   /* If writing to memory or generating a set
98184   ** only a single column may be output.
98185   */
98186 #ifndef SQLITE_OMIT_SUBQUERY
98187   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
98188     goto select_end;
98189   }
98190 #endif
98191
98192   /* Generate code for all sub-queries in the FROM clause
98193   */
98194 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98195   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
98196     struct SrcList_item *pItem = &pTabList->a[i];
98197     SelectDest dest;
98198     Select *pSub = pItem->pSelect;
98199     int isAggSub;
98200
98201     if( pSub==0 ) continue;
98202
98203     /* Sometimes the code for a subquery will be generated more than
98204     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
98205     ** for example.  In that case, do not regenerate the code to manifest
98206     ** a view or the co-routine to implement a view.  The first instance
98207     ** is sufficient, though the subroutine to manifest the view does need
98208     ** to be invoked again. */
98209     if( pItem->addrFillSub ){
98210       if( pItem->viaCoroutine==0 ){
98211         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
98212       }
98213       continue;
98214     }
98215
98216     /* Increment Parse.nHeight by the height of the largest expression
98217     ** tree refered to by this, the parent select. The child select
98218     ** may contain expression trees of at most
98219     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
98220     ** more conservative than necessary, but much easier than enforcing
98221     ** an exact limit.
98222     */
98223     pParse->nHeight += sqlite3SelectExprHeight(p);
98224
98225     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
98226     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
98227       /* This subquery can be absorbed into its parent. */
98228       if( isAggSub ){
98229         isAgg = 1;
98230         p->selFlags |= SF_Aggregate;
98231       }
98232       i = -1;
98233     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
98234       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
98235     ){
98236       /* Implement a co-routine that will return a single row of the result
98237       ** set on each invocation.
98238       */
98239       int addrTop;
98240       int addrEof;
98241       pItem->regReturn = ++pParse->nMem;
98242       addrEof = ++pParse->nMem;
98243       /* Before coding the OP_Goto to jump to the start of the main routine,
98244       ** ensure that the jump to the verify-schema routine has already
98245       ** been coded. Otherwise, the verify-schema would likely be coded as 
98246       ** part of the co-routine. If the main routine then accessed the 
98247       ** database before invoking the co-routine for the first time (for 
98248       ** example to initialize a LIMIT register from a sub-select), it would 
98249       ** be doing so without having verified the schema version and obtained 
98250       ** the required db locks. See ticket d6b36be38.  */
98251       sqlite3CodeVerifySchema(pParse, -1);
98252       sqlite3VdbeAddOp0(v, OP_Goto);
98253       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
98254       sqlite3VdbeChangeP5(v, 1);
98255       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
98256       pItem->addrFillSub = addrTop;
98257       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
98258       sqlite3VdbeChangeP5(v, 1);
98259       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
98260       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98261       sqlite3Select(pParse, pSub, &dest);
98262       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98263       pItem->viaCoroutine = 1;
98264       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
98265       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
98266       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
98267       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
98268       VdbeComment((v, "end %s", pItem->pTab->zName));
98269       sqlite3VdbeJumpHere(v, addrTop-1);
98270       sqlite3ClearTempRegCache(pParse);
98271     }else{
98272       /* Generate a subroutine that will fill an ephemeral table with
98273       ** the content of this subquery.  pItem->addrFillSub will point
98274       ** to the address of the generated subroutine.  pItem->regReturn
98275       ** is a register allocated to hold the subroutine return address
98276       */
98277       int topAddr;
98278       int onceAddr = 0;
98279       int retAddr;
98280       assert( pItem->addrFillSub==0 );
98281       pItem->regReturn = ++pParse->nMem;
98282       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98283       pItem->addrFillSub = topAddr+1;
98284       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98285       if( pItem->isCorrelated==0 ){
98286         /* If the subquery is no correlated and if we are not inside of
98287         ** a trigger, then we only need to compute the value of the subquery
98288         ** once. */
98289         onceAddr = sqlite3CodeOnce(pParse);
98290       }
98291       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98292       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98293       sqlite3Select(pParse, pSub, &dest);
98294       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98295       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
98296       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98297       VdbeComment((v, "end %s", pItem->pTab->zName));
98298       sqlite3VdbeChangeP1(v, topAddr, retAddr);
98299       sqlite3ClearTempRegCache(pParse);
98300     }
98301     if( /*pParse->nErr ||*/ db->mallocFailed ){
98302       goto select_end;
98303     }
98304     pParse->nHeight -= sqlite3SelectExprHeight(p);
98305     pTabList = p->pSrc;
98306     if( !IgnorableOrderby(pDest) ){
98307       pOrderBy = p->pOrderBy;
98308     }
98309   }
98310   pEList = p->pEList;
98311 #endif
98312   pWhere = p->pWhere;
98313   pGroupBy = p->pGroupBy;
98314   pHaving = p->pHaving;
98315   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
98316
98317 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98318   /* If there is are a sequence of queries, do the earlier ones first.
98319   */
98320   if( p->pPrior ){
98321     if( p->pRightmost==0 ){
98322       Select *pLoop, *pRight = 0;
98323       int cnt = 0;
98324       int mxSelect;
98325       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98326         pLoop->pRightmost = p;
98327         pLoop->pNext = pRight;
98328         pRight = pLoop;
98329       }
98330       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
98331       if( mxSelect && cnt>mxSelect ){
98332         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
98333         goto select_end;
98334       }
98335     }
98336     rc = multiSelect(pParse, p, pDest);
98337     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98338     return rc;
98339   }
98340 #endif
98341
98342   /* If there is both a GROUP BY and an ORDER BY clause and they are
98343   ** identical, then disable the ORDER BY clause since the GROUP BY
98344   ** will cause elements to come out in the correct order.  This is
98345   ** an optimization - the correct answer should result regardless.
98346   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
98347   ** to disable this optimization for testing purposes.
98348   */
98349   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
98350          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
98351     pOrderBy = 0;
98352   }
98353
98354   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
98355   ** if the select-list is the same as the ORDER BY list, then this query
98356   ** can be rewritten as a GROUP BY. In other words, this:
98357   **
98358   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98359   **
98360   ** is transformed to:
98361   **
98362   **     SELECT xyz FROM ... GROUP BY xyz
98363   **
98364   ** The second form is preferred as a single index (or temp-table) may be 
98365   ** used for both the ORDER BY and DISTINCT processing. As originally 
98366   ** written the query must use a temp-table for at least one of the ORDER 
98367   ** BY and DISTINCT, and an index or separate temp-table for the other.
98368   */
98369   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
98370    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
98371   ){
98372     p->selFlags &= ~SF_Distinct;
98373     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
98374     pGroupBy = p->pGroupBy;
98375     pOrderBy = 0;
98376     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
98377     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
98378     ** original setting of the SF_Distinct flag, not the current setting */
98379     assert( sDistinct.isTnct );
98380   }
98381
98382   /* If there is an ORDER BY clause, then this sorting
98383   ** index might end up being unused if the data can be 
98384   ** extracted in pre-sorted order.  If that is the case, then the
98385   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98386   ** we figure out that the sorting index is not needed.  The addrSortIndex
98387   ** variable is used to facilitate that change.
98388   */
98389   if( pOrderBy ){
98390     KeyInfo *pKeyInfo;
98391     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98392     pOrderBy->iECursor = pParse->nTab++;
98393     p->addrOpenEphm[2] = addrSortIndex =
98394       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98395                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98396                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98397   }else{
98398     addrSortIndex = -1;
98399   }
98400
98401   /* If the output is destined for a temporary table, open that table.
98402   */
98403   if( pDest->eDest==SRT_EphemTab ){
98404     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
98405   }
98406
98407   /* Set the limiter.
98408   */
98409   iEnd = sqlite3VdbeMakeLabel(v);
98410   p->nSelectRow = (double)LARGEST_INT64;
98411   computeLimitRegisters(pParse, p, iEnd);
98412   if( p->iLimit==0 && addrSortIndex>=0 ){
98413     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98414     p->selFlags |= SF_UseSorter;
98415   }
98416
98417   /* Open a virtual index to use for the distinct set.
98418   */
98419   if( p->selFlags & SF_Distinct ){
98420     sDistinct.tabTnct = pParse->nTab++;
98421     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98422                                 sDistinct.tabTnct, 0, 0,
98423                                 (char*)keyInfoFromExprList(pParse, p->pEList),
98424                                 P4_KEYINFO_HANDOFF);
98425     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98426     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
98427   }else{
98428     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
98429   }
98430
98431   if( !isAgg && pGroupBy==0 ){
98432     /* No aggregate functions and no GROUP BY clause */
98433     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
98434
98435     /* Begin the database scan. */
98436     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
98437     if( pWInfo==0 ) goto select_end;
98438     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98439     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
98440     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
98441
98442     /* If sorting index that was created by a prior OP_OpenEphemeral 
98443     ** instruction ended up not being needed, then change the OP_OpenEphemeral
98444     ** into an OP_Noop.
98445     */
98446     if( addrSortIndex>=0 && pOrderBy==0 ){
98447       sqlite3VdbeChangeToNoop(v, addrSortIndex);
98448       p->addrOpenEphm[2] = -1;
98449     }
98450
98451     /* Use the standard inner loop. */
98452     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
98453                     pWInfo->iContinue, pWInfo->iBreak);
98454
98455     /* End the database scan loop.
98456     */
98457     sqlite3WhereEnd(pWInfo);
98458   }else{
98459     /* This case when there exist aggregate functions or a GROUP BY clause
98460     ** or both */
98461     NameContext sNC;    /* Name context for processing aggregate information */
98462     int iAMem;          /* First Mem address for storing current GROUP BY */
98463     int iBMem;          /* First Mem address for previous GROUP BY */
98464     int iUseFlag;       /* Mem address holding flag indicating that at least
98465                         ** one row of the input to the aggregator has been
98466                         ** processed */
98467     int iAbortFlag;     /* Mem address which causes query abort if positive */
98468     int groupBySort;    /* Rows come from source in GROUP BY order */
98469     int addrEnd;        /* End of processing for this SELECT */
98470     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98471     int sortOut = 0;    /* Output register from the sorter */
98472
98473     /* Remove any and all aliases between the result set and the
98474     ** GROUP BY clause.
98475     */
98476     if( pGroupBy ){
98477       int k;                        /* Loop counter */
98478       struct ExprList_item *pItem;  /* For looping over expression in a list */
98479
98480       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98481         pItem->iAlias = 0;
98482       }
98483       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98484         pItem->iAlias = 0;
98485       }
98486       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98487     }else{
98488       p->nSelectRow = (double)1;
98489     }
98490
98491  
98492     /* Create a label to jump to when we want to abort the query */
98493     addrEnd = sqlite3VdbeMakeLabel(v);
98494
98495     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98496     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98497     ** SELECT statement.
98498     */
98499     memset(&sNC, 0, sizeof(sNC));
98500     sNC.pParse = pParse;
98501     sNC.pSrcList = pTabList;
98502     sNC.pAggInfo = &sAggInfo;
98503     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98504     sAggInfo.pGroupBy = pGroupBy;
98505     sqlite3ExprAnalyzeAggList(&sNC, pEList);
98506     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
98507     if( pHaving ){
98508       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
98509     }
98510     sAggInfo.nAccumulator = sAggInfo.nColumn;
98511     for(i=0; i<sAggInfo.nFunc; i++){
98512       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98513       sNC.ncFlags |= NC_InAggFunc;
98514       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98515       sNC.ncFlags &= ~NC_InAggFunc;
98516     }
98517     if( db->mallocFailed ) goto select_end;
98518
98519     /* Processing for aggregates with GROUP BY is very different and
98520     ** much more complex than aggregates without a GROUP BY.
98521     */
98522     if( pGroupBy ){
98523       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
98524       int j1;             /* A-vs-B comparision jump */
98525       int addrOutputRow;  /* Start of subroutine that outputs a result row */
98526       int regOutputRow;   /* Return address register for output subroutine */
98527       int addrSetAbort;   /* Set the abort flag and return */
98528       int addrTopOfLoop;  /* Top of the input loop */
98529       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
98530       int addrReset;      /* Subroutine for resetting the accumulator */
98531       int regReset;       /* Return address register for reset subroutine */
98532
98533       /* If there is a GROUP BY clause we might need a sorting index to
98534       ** implement it.  Allocate that sorting index now.  If it turns out
98535       ** that we do not need it after all, the OP_SorterOpen instruction
98536       ** will be converted into a Noop.  
98537       */
98538       sAggInfo.sortingIdx = pParse->nTab++;
98539       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
98540       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
98541           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
98542           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98543
98544       /* Initialize memory locations used by GROUP BY aggregate processing
98545       */
98546       iUseFlag = ++pParse->nMem;
98547       iAbortFlag = ++pParse->nMem;
98548       regOutputRow = ++pParse->nMem;
98549       addrOutputRow = sqlite3VdbeMakeLabel(v);
98550       regReset = ++pParse->nMem;
98551       addrReset = sqlite3VdbeMakeLabel(v);
98552       iAMem = pParse->nMem + 1;
98553       pParse->nMem += pGroupBy->nExpr;
98554       iBMem = pParse->nMem + 1;
98555       pParse->nMem += pGroupBy->nExpr;
98556       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
98557       VdbeComment((v, "clear abort flag"));
98558       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
98559       VdbeComment((v, "indicate accumulator empty"));
98560       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
98561
98562       /* Begin a loop that will extract all source rows in GROUP BY order.
98563       ** This might involve two separate loops with an OP_Sort in between, or
98564       ** it might be a single loop that uses an index to extract information
98565       ** in the right order to begin with.
98566       */
98567       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98568       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
98569       if( pWInfo==0 ) goto select_end;
98570       if( pWInfo->nOBSat==pGroupBy->nExpr ){
98571         /* The optimizer is able to deliver rows in group by order so
98572         ** we do not have to sort.  The OP_OpenEphemeral table will be
98573         ** cancelled later because we still need to use the pKeyInfo
98574         */
98575         groupBySort = 0;
98576       }else{
98577         /* Rows are coming out in undetermined order.  We have to push
98578         ** each row into a sorting index, terminate the first loop,
98579         ** then loop over the sorting index in order to get the output
98580         ** in sorted order
98581         */
98582         int regBase;
98583         int regRecord;
98584         int nCol;
98585         int nGroupBy;
98586
98587         explainTempTable(pParse, 
98588             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
98589                     "DISTINCT" : "GROUP BY");
98590
98591         groupBySort = 1;
98592         nGroupBy = pGroupBy->nExpr;
98593         nCol = nGroupBy + 1;
98594         j = nGroupBy+1;
98595         for(i=0; i<sAggInfo.nColumn; i++){
98596           if( sAggInfo.aCol[i].iSorterColumn>=j ){
98597             nCol++;
98598             j++;
98599           }
98600         }
98601         regBase = sqlite3GetTempRange(pParse, nCol);
98602         sqlite3ExprCacheClear(pParse);
98603         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
98604         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
98605         j = nGroupBy+1;
98606         for(i=0; i<sAggInfo.nColumn; i++){
98607           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
98608           if( pCol->iSorterColumn>=j ){
98609             int r1 = j + regBase;
98610             int r2;
98611
98612             r2 = sqlite3ExprCodeGetColumn(pParse, 
98613                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
98614             if( r1!=r2 ){
98615               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
98616             }
98617             j++;
98618           }
98619         }
98620         regRecord = sqlite3GetTempReg(pParse);
98621         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
98622         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
98623         sqlite3ReleaseTempReg(pParse, regRecord);
98624         sqlite3ReleaseTempRange(pParse, regBase, nCol);
98625         sqlite3WhereEnd(pWInfo);
98626         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
98627         sortOut = sqlite3GetTempReg(pParse);
98628         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
98629         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
98630         VdbeComment((v, "GROUP BY sort"));
98631         sAggInfo.useSortingIdx = 1;
98632         sqlite3ExprCacheClear(pParse);
98633       }
98634
98635       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
98636       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
98637       ** Then compare the current GROUP BY terms against the GROUP BY terms
98638       ** from the previous row currently stored in a0, a1, a2...
98639       */
98640       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
98641       sqlite3ExprCacheClear(pParse);
98642       if( groupBySort ){
98643         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
98644       }
98645       for(j=0; j<pGroupBy->nExpr; j++){
98646         if( groupBySort ){
98647           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
98648           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
98649         }else{
98650           sAggInfo.directMode = 1;
98651           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
98652         }
98653       }
98654       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
98655                           (char*)pKeyInfo, P4_KEYINFO);
98656       j1 = sqlite3VdbeCurrentAddr(v);
98657       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
98658
98659       /* Generate code that runs whenever the GROUP BY changes.
98660       ** Changes in the GROUP BY are detected by the previous code
98661       ** block.  If there were no changes, this block is skipped.
98662       **
98663       ** This code copies current group by terms in b0,b1,b2,...
98664       ** over to a0,a1,a2.  It then calls the output subroutine
98665       ** and resets the aggregate accumulator registers in preparation
98666       ** for the next GROUP BY batch.
98667       */
98668       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
98669       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98670       VdbeComment((v, "output one row"));
98671       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
98672       VdbeComment((v, "check abort flag"));
98673       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98674       VdbeComment((v, "reset accumulator"));
98675
98676       /* Update the aggregate accumulators based on the content of
98677       ** the current row
98678       */
98679       sqlite3VdbeJumpHere(v, j1);
98680       updateAccumulator(pParse, &sAggInfo);
98681       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
98682       VdbeComment((v, "indicate data in accumulator"));
98683
98684       /* End of the loop
98685       */
98686       if( groupBySort ){
98687         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
98688       }else{
98689         sqlite3WhereEnd(pWInfo);
98690         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
98691       }
98692
98693       /* Output the final row of result
98694       */
98695       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98696       VdbeComment((v, "output final row"));
98697
98698       /* Jump over the subroutines
98699       */
98700       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
98701
98702       /* Generate a subroutine that outputs a single row of the result
98703       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
98704       ** is less than or equal to zero, the subroutine is a no-op.  If
98705       ** the processing calls for the query to abort, this subroutine
98706       ** increments the iAbortFlag memory location before returning in
98707       ** order to signal the caller to abort.
98708       */
98709       addrSetAbort = sqlite3VdbeCurrentAddr(v);
98710       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
98711       VdbeComment((v, "set abort flag"));
98712       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98713       sqlite3VdbeResolveLabel(v, addrOutputRow);
98714       addrOutputRow = sqlite3VdbeCurrentAddr(v);
98715       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
98716       VdbeComment((v, "Groupby result generator entry point"));
98717       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98718       finalizeAggFunctions(pParse, &sAggInfo);
98719       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
98720       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
98721                       &sDistinct, pDest,
98722                       addrOutputRow+1, addrSetAbort);
98723       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98724       VdbeComment((v, "end groupby result generator"));
98725
98726       /* Generate a subroutine that will reset the group-by accumulator
98727       */
98728       sqlite3VdbeResolveLabel(v, addrReset);
98729       resetAccumulator(pParse, &sAggInfo);
98730       sqlite3VdbeAddOp1(v, OP_Return, regReset);
98731      
98732     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
98733     else {
98734       ExprList *pDel = 0;
98735 #ifndef SQLITE_OMIT_BTREECOUNT
98736       Table *pTab;
98737       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
98738         /* If isSimpleCount() returns a pointer to a Table structure, then
98739         ** the SQL statement is of the form:
98740         **
98741         **   SELECT count(*) FROM <tbl>
98742         **
98743         ** where the Table structure returned represents table <tbl>.
98744         **
98745         ** This statement is so common that it is optimized specially. The
98746         ** OP_Count instruction is executed either on the intkey table that
98747         ** contains the data for table <tbl> or on one of its indexes. It
98748         ** is better to execute the op on an index, as indexes are almost
98749         ** always spread across less pages than their corresponding tables.
98750         */
98751         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98752         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
98753         Index *pIdx;                         /* Iterator variable */
98754         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
98755         Index *pBest = 0;                    /* Best index found so far */
98756         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
98757
98758         sqlite3CodeVerifySchema(pParse, iDb);
98759         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98760
98761         /* Search for the index that has the least amount of columns. If
98762         ** there is such an index, and it has less columns than the table
98763         ** does, then we can assume that it consumes less space on disk and
98764         ** will therefore be cheaper to scan to determine the query result.
98765         ** In this case set iRoot to the root page number of the index b-tree
98766         ** and pKeyInfo to the KeyInfo structure required to navigate the
98767         ** index.
98768         **
98769         ** (2011-04-15) Do not do a full scan of an unordered index.
98770         **
98771         ** In practice the KeyInfo structure will not be used. It is only 
98772         ** passed to keep OP_OpenRead happy.
98773         */
98774         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98775           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
98776             pBest = pIdx;
98777           }
98778         }
98779         if( pBest && pBest->nColumn<pTab->nCol ){
98780           iRoot = pBest->tnum;
98781           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
98782         }
98783
98784         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
98785         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
98786         if( pKeyInfo ){
98787           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
98788         }
98789         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
98790         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
98791         explainSimpleCount(pParse, pTab, pBest);
98792       }else
98793 #endif /* SQLITE_OMIT_BTREECOUNT */
98794       {
98795         /* Check if the query is of one of the following forms:
98796         **
98797         **   SELECT min(x) FROM ...
98798         **   SELECT max(x) FROM ...
98799         **
98800         ** If it is, then ask the code in where.c to attempt to sort results
98801         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
98802         ** If where.c is able to produce results sorted in this order, then
98803         ** add vdbe code to break out of the processing loop after the 
98804         ** first iteration (since the first iteration of the loop is 
98805         ** guaranteed to operate on the row with the minimum or maximum 
98806         ** value of x, the only row required).
98807         **
98808         ** A special flag must be passed to sqlite3WhereBegin() to slightly
98809         ** modify behaviour as follows:
98810         **
98811         **   + If the query is a "SELECT min(x)", then the loop coded by
98812         **     where.c should not iterate over any values with a NULL value
98813         **     for x.
98814         **
98815         **   + The optimizer code in where.c (the thing that decides which
98816         **     index or indices to use) should place a different priority on 
98817         **     satisfying the 'ORDER BY' clause than it does in other cases.
98818         **     Refer to code and comments in where.c for details.
98819         */
98820         ExprList *pMinMax = 0;
98821         u8 flag = minMaxQuery(p);
98822         if( flag ){
98823           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98824           assert( p->pEList->a[0].pExpr->x.pList->nExpr==1 );
98825           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98826           pDel = pMinMax;
98827           if( pMinMax && !db->mallocFailed ){
98828             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98829             pMinMax->a[0].pExpr->op = TK_COLUMN;
98830           }
98831         }
98832   
98833         /* This case runs if the aggregate has no GROUP BY clause.  The
98834         ** processing is much simpler since there is only a single row
98835         ** of output.
98836         */
98837         resetAccumulator(pParse, &sAggInfo);
98838         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
98839         if( pWInfo==0 ){
98840           sqlite3ExprListDelete(db, pDel);
98841           goto select_end;
98842         }
98843         updateAccumulator(pParse, &sAggInfo);
98844         assert( pMinMax==0 || pMinMax->nExpr==1 );
98845         if( pWInfo->nOBSat>0 ){
98846           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98847           VdbeComment((v, "%s() by index",
98848                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
98849         }
98850         sqlite3WhereEnd(pWInfo);
98851         finalizeAggFunctions(pParse, &sAggInfo);
98852       }
98853
98854       pOrderBy = 0;
98855       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
98856       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, 
98857                       pDest, addrEnd, addrEnd);
98858       sqlite3ExprListDelete(db, pDel);
98859     }
98860     sqlite3VdbeResolveLabel(v, addrEnd);
98861     
98862   } /* endif aggregate query */
98863
98864   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
98865     explainTempTable(pParse, "DISTINCT");
98866   }
98867
98868   /* If there is an ORDER BY clause, then we need to sort the results
98869   ** and send them to the callback one by one.
98870   */
98871   if( pOrderBy ){
98872     explainTempTable(pParse, "ORDER BY");
98873     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
98874   }
98875
98876   /* Jump here to skip this query
98877   */
98878   sqlite3VdbeResolveLabel(v, iEnd);
98879
98880   /* The SELECT was successfully coded.   Set the return code to 0
98881   ** to indicate no errors.
98882   */
98883   rc = 0;
98884
98885   /* Control jumps to here if an error is encountered above, or upon
98886   ** successful coding of the SELECT.
98887   */
98888 select_end:
98889   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98890
98891   /* Identify column names if results of the SELECT are to be output.
98892   */
98893   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
98894     generateColumnNames(pParse, pTabList, pEList);
98895   }
98896
98897   sqlite3DbFree(db, sAggInfo.aCol);
98898   sqlite3DbFree(db, sAggInfo.aFunc);
98899   return rc;
98900 }
98901
98902 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
98903 /*
98904 ** Generate a human-readable description of a the Select object.
98905 */
98906 static void explainOneSelect(Vdbe *pVdbe, Select *p){
98907   sqlite3ExplainPrintf(pVdbe, "SELECT ");
98908   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
98909     if( p->selFlags & SF_Distinct ){
98910       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
98911     }
98912     if( p->selFlags & SF_Aggregate ){
98913       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
98914     }
98915     sqlite3ExplainNL(pVdbe);
98916     sqlite3ExplainPrintf(pVdbe, "   ");
98917   }
98918   sqlite3ExplainExprList(pVdbe, p->pEList);
98919   sqlite3ExplainNL(pVdbe);
98920   if( p->pSrc && p->pSrc->nSrc ){
98921     int i;
98922     sqlite3ExplainPrintf(pVdbe, "FROM ");
98923     sqlite3ExplainPush(pVdbe);
98924     for(i=0; i<p->pSrc->nSrc; i++){
98925       struct SrcList_item *pItem = &p->pSrc->a[i];
98926       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
98927       if( pItem->pSelect ){
98928         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
98929         if( pItem->pTab ){
98930           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
98931         }
98932       }else if( pItem->zName ){
98933         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
98934       }
98935       if( pItem->zAlias ){
98936         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
98937       }
98938       if( pItem->jointype & JT_LEFT ){
98939         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
98940       }
98941       sqlite3ExplainNL(pVdbe);
98942     }
98943     sqlite3ExplainPop(pVdbe);
98944   }
98945   if( p->pWhere ){
98946     sqlite3ExplainPrintf(pVdbe, "WHERE ");
98947     sqlite3ExplainExpr(pVdbe, p->pWhere);
98948     sqlite3ExplainNL(pVdbe);
98949   }
98950   if( p->pGroupBy ){
98951     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
98952     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
98953     sqlite3ExplainNL(pVdbe);
98954   }
98955   if( p->pHaving ){
98956     sqlite3ExplainPrintf(pVdbe, "HAVING ");
98957     sqlite3ExplainExpr(pVdbe, p->pHaving);
98958     sqlite3ExplainNL(pVdbe);
98959   }
98960   if( p->pOrderBy ){
98961     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
98962     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
98963     sqlite3ExplainNL(pVdbe);
98964   }
98965   if( p->pLimit ){
98966     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
98967     sqlite3ExplainExpr(pVdbe, p->pLimit);
98968     sqlite3ExplainNL(pVdbe);
98969   }
98970   if( p->pOffset ){
98971     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
98972     sqlite3ExplainExpr(pVdbe, p->pOffset);
98973     sqlite3ExplainNL(pVdbe);
98974   }
98975 }
98976 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
98977   if( p==0 ){
98978     sqlite3ExplainPrintf(pVdbe, "(null-select)");
98979     return;
98980   }
98981   while( p->pPrior ) p = p->pPrior;
98982   sqlite3ExplainPush(pVdbe);
98983   while( p ){
98984     explainOneSelect(pVdbe, p);
98985     p = p->pNext;
98986     if( p==0 ) break;
98987     sqlite3ExplainNL(pVdbe);
98988     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
98989   }
98990   sqlite3ExplainPrintf(pVdbe, "END");
98991   sqlite3ExplainPop(pVdbe);
98992 }
98993
98994 /* End of the structure debug printing code
98995 *****************************************************************************/
98996 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
98997
98998 /************** End of select.c **********************************************/
98999 /************** Begin file table.c *******************************************/
99000 /*
99001 ** 2001 September 15
99002 **
99003 ** The author disclaims copyright to this source code.  In place of
99004 ** a legal notice, here is a blessing:
99005 **
99006 **    May you do good and not evil.
99007 **    May you find forgiveness for yourself and forgive others.
99008 **    May you share freely, never taking more than you give.
99009 **
99010 *************************************************************************
99011 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
99012 ** interface routines.  These are just wrappers around the main
99013 ** interface routine of sqlite3_exec().
99014 **
99015 ** These routines are in a separate files so that they will not be linked
99016 ** if they are not used.
99017 */
99018 /* #include <stdlib.h> */
99019 /* #include <string.h> */
99020
99021 #ifndef SQLITE_OMIT_GET_TABLE
99022
99023 /*
99024 ** This structure is used to pass data from sqlite3_get_table() through
99025 ** to the callback function is uses to build the result.
99026 */
99027 typedef struct TabResult {
99028   char **azResult;   /* Accumulated output */
99029   char *zErrMsg;     /* Error message text, if an error occurs */
99030   int nAlloc;        /* Slots allocated for azResult[] */
99031   int nRow;          /* Number of rows in the result */
99032   int nColumn;       /* Number of columns in the result */
99033   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
99034   int rc;            /* Return code from sqlite3_exec() */
99035 } TabResult;
99036
99037 /*
99038 ** This routine is called once for each row in the result table.  Its job
99039 ** is to fill in the TabResult structure appropriately, allocating new
99040 ** memory as necessary.
99041 */
99042 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
99043   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
99044   int need;                         /* Slots needed in p->azResult[] */
99045   int i;                            /* Loop counter */
99046   char *z;                          /* A single column of result */
99047
99048   /* Make sure there is enough space in p->azResult to hold everything
99049   ** we need to remember from this invocation of the callback.
99050   */
99051   if( p->nRow==0 && argv!=0 ){
99052     need = nCol*2;
99053   }else{
99054     need = nCol;
99055   }
99056   if( p->nData + need > p->nAlloc ){
99057     char **azNew;
99058     p->nAlloc = p->nAlloc*2 + need;
99059     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
99060     if( azNew==0 ) goto malloc_failed;
99061     p->azResult = azNew;
99062   }
99063
99064   /* If this is the first row, then generate an extra row containing
99065   ** the names of all columns.
99066   */
99067   if( p->nRow==0 ){
99068     p->nColumn = nCol;
99069     for(i=0; i<nCol; i++){
99070       z = sqlite3_mprintf("%s", colv[i]);
99071       if( z==0 ) goto malloc_failed;
99072       p->azResult[p->nData++] = z;
99073     }
99074   }else if( p->nColumn!=nCol ){
99075     sqlite3_free(p->zErrMsg);
99076     p->zErrMsg = sqlite3_mprintf(
99077        "sqlite3_get_table() called with two or more incompatible queries"
99078     );
99079     p->rc = SQLITE_ERROR;
99080     return 1;
99081   }
99082
99083   /* Copy over the row data
99084   */
99085   if( argv!=0 ){
99086     for(i=0; i<nCol; i++){
99087       if( argv[i]==0 ){
99088         z = 0;
99089       }else{
99090         int n = sqlite3Strlen30(argv[i])+1;
99091         z = sqlite3_malloc( n );
99092         if( z==0 ) goto malloc_failed;
99093         memcpy(z, argv[i], n);
99094       }
99095       p->azResult[p->nData++] = z;
99096     }
99097     p->nRow++;
99098   }
99099   return 0;
99100
99101 malloc_failed:
99102   p->rc = SQLITE_NOMEM;
99103   return 1;
99104 }
99105
99106 /*
99107 ** Query the database.  But instead of invoking a callback for each row,
99108 ** malloc() for space to hold the result and return the entire results
99109 ** at the conclusion of the call.
99110 **
99111 ** The result that is written to ***pazResult is held in memory obtained
99112 ** from malloc().  But the caller cannot free this memory directly.  
99113 ** Instead, the entire table should be passed to sqlite3_free_table() when
99114 ** the calling procedure is finished using it.
99115 */
99116 SQLITE_API int sqlite3_get_table(
99117   sqlite3 *db,                /* The database on which the SQL executes */
99118   const char *zSql,           /* The SQL to be executed */
99119   char ***pazResult,          /* Write the result table here */
99120   int *pnRow,                 /* Write the number of rows in the result here */
99121   int *pnColumn,              /* Write the number of columns of result here */
99122   char **pzErrMsg             /* Write error messages here */
99123 ){
99124   int rc;
99125   TabResult res;
99126
99127   *pazResult = 0;
99128   if( pnColumn ) *pnColumn = 0;
99129   if( pnRow ) *pnRow = 0;
99130   if( pzErrMsg ) *pzErrMsg = 0;
99131   res.zErrMsg = 0;
99132   res.nRow = 0;
99133   res.nColumn = 0;
99134   res.nData = 1;
99135   res.nAlloc = 20;
99136   res.rc = SQLITE_OK;
99137   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
99138   if( res.azResult==0 ){
99139      db->errCode = SQLITE_NOMEM;
99140      return SQLITE_NOMEM;
99141   }
99142   res.azResult[0] = 0;
99143   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
99144   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
99145   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
99146   if( (rc&0xff)==SQLITE_ABORT ){
99147     sqlite3_free_table(&res.azResult[1]);
99148     if( res.zErrMsg ){
99149       if( pzErrMsg ){
99150         sqlite3_free(*pzErrMsg);
99151         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
99152       }
99153       sqlite3_free(res.zErrMsg);
99154     }
99155     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
99156     return res.rc;
99157   }
99158   sqlite3_free(res.zErrMsg);
99159   if( rc!=SQLITE_OK ){
99160     sqlite3_free_table(&res.azResult[1]);
99161     return rc;
99162   }
99163   if( res.nAlloc>res.nData ){
99164     char **azNew;
99165     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
99166     if( azNew==0 ){
99167       sqlite3_free_table(&res.azResult[1]);
99168       db->errCode = SQLITE_NOMEM;
99169       return SQLITE_NOMEM;
99170     }
99171     res.azResult = azNew;
99172   }
99173   *pazResult = &res.azResult[1];
99174   if( pnColumn ) *pnColumn = res.nColumn;
99175   if( pnRow ) *pnRow = res.nRow;
99176   return rc;
99177 }
99178
99179 /*
99180 ** This routine frees the space the sqlite3_get_table() malloced.
99181 */
99182 SQLITE_API void sqlite3_free_table(
99183   char **azResult            /* Result returned from from sqlite3_get_table() */
99184 ){
99185   if( azResult ){
99186     int i, n;
99187     azResult--;
99188     assert( azResult!=0 );
99189     n = SQLITE_PTR_TO_INT(azResult[0]);
99190     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
99191     sqlite3_free(azResult);
99192   }
99193 }
99194
99195 #endif /* SQLITE_OMIT_GET_TABLE */
99196
99197 /************** End of table.c ***********************************************/
99198 /************** Begin file trigger.c *****************************************/
99199 /*
99200 **
99201 ** The author disclaims copyright to this source code.  In place of
99202 ** a legal notice, here is a blessing:
99203 **
99204 **    May you do good and not evil.
99205 **    May you find forgiveness for yourself and forgive others.
99206 **    May you share freely, never taking more than you give.
99207 **
99208 *************************************************************************
99209 ** This file contains the implementation for TRIGGERs
99210 */
99211
99212 #ifndef SQLITE_OMIT_TRIGGER
99213 /*
99214 ** Delete a linked list of TriggerStep structures.
99215 */
99216 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
99217   while( pTriggerStep ){
99218     TriggerStep * pTmp = pTriggerStep;
99219     pTriggerStep = pTriggerStep->pNext;
99220
99221     sqlite3ExprDelete(db, pTmp->pWhere);
99222     sqlite3ExprListDelete(db, pTmp->pExprList);
99223     sqlite3SelectDelete(db, pTmp->pSelect);
99224     sqlite3IdListDelete(db, pTmp->pIdList);
99225
99226     sqlite3DbFree(db, pTmp);
99227   }
99228 }
99229
99230 /*
99231 ** Given table pTab, return a list of all the triggers attached to 
99232 ** the table. The list is connected by Trigger.pNext pointers.
99233 **
99234 ** All of the triggers on pTab that are in the same database as pTab
99235 ** are already attached to pTab->pTrigger.  But there might be additional
99236 ** triggers on pTab in the TEMP schema.  This routine prepends all
99237 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99238 ** and returns the combined list.
99239 **
99240 ** To state it another way:  This routine returns a list of all triggers
99241 ** that fire off of pTab.  The list will include any TEMP triggers on
99242 ** pTab as well as the triggers lised in pTab->pTrigger.
99243 */
99244 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
99245   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99246   Trigger *pList = 0;                  /* List of triggers to return */
99247
99248   if( pParse->disableTriggers ){
99249     return 0;
99250   }
99251
99252   if( pTmpSchema!=pTab->pSchema ){
99253     HashElem *p;
99254     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99255     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
99256       Trigger *pTrig = (Trigger *)sqliteHashData(p);
99257       if( pTrig->pTabSchema==pTab->pSchema
99258        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
99259       ){
99260         pTrig->pNext = (pList ? pList : pTab->pTrigger);
99261         pList = pTrig;
99262       }
99263     }
99264   }
99265
99266   return (pList ? pList : pTab->pTrigger);
99267 }
99268
99269 /*
99270 ** This is called by the parser when it sees a CREATE TRIGGER statement
99271 ** up to the point of the BEGIN before the trigger actions.  A Trigger
99272 ** structure is generated based on the information available and stored
99273 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99274 ** sqlite3FinishTrigger() function is called to complete the trigger
99275 ** construction process.
99276 */
99277 SQLITE_PRIVATE void sqlite3BeginTrigger(
99278   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99279   Token *pName1,      /* The name of the trigger */
99280   Token *pName2,      /* The name of the trigger */
99281   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99282   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99283   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99284   SrcList *pTableName,/* The name of the table/view the trigger applies to */
99285   Expr *pWhen,        /* WHEN clause */
99286   int isTemp,         /* True if the TEMPORARY keyword is present */
99287   int noErr           /* Suppress errors if the trigger already exists */
99288 ){
99289   Trigger *pTrigger = 0;  /* The new trigger */
99290   Table *pTab;            /* Table that the trigger fires off of */
99291   char *zName = 0;        /* Name of the trigger */
99292   sqlite3 *db = pParse->db;  /* The database connection */
99293   int iDb;                /* The database to store the trigger in */
99294   Token *pName;           /* The unqualified db name */
99295   DbFixer sFix;           /* State vector for the DB fixer */
99296   int iTabDb;             /* Index of the database holding pTab */
99297
99298   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99299   assert( pName2!=0 );
99300   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99301   assert( op>0 && op<0xff );
99302   if( isTemp ){
99303     /* If TEMP was specified, then the trigger name may not be qualified. */
99304     if( pName2->n>0 ){
99305       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99306       goto trigger_cleanup;
99307     }
99308     iDb = 1;
99309     pName = pName1;
99310   }else{
99311     /* Figure out the db that the trigger will be created in */
99312     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99313     if( iDb<0 ){
99314       goto trigger_cleanup;
99315     }
99316   }
99317   if( !pTableName || db->mallocFailed ){
99318     goto trigger_cleanup;
99319   }
99320
99321   /* A long-standing parser bug is that this syntax was allowed:
99322   **
99323   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99324   **                                                 ^^^^^^^^
99325   **
99326   ** To maintain backwards compatibility, ignore the database
99327   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
99328   */
99329   if( db->init.busy && iDb!=1 ){
99330     sqlite3DbFree(db, pTableName->a[0].zDatabase);
99331     pTableName->a[0].zDatabase = 0;
99332   }
99333
99334   /* If the trigger name was unqualified, and the table is a temp table,
99335   ** then set iDb to 1 to create the trigger in the temporary database.
99336   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
99337   ** exist, the error is caught by the block below.
99338   */
99339   pTab = sqlite3SrcListLookup(pParse, pTableName);
99340   if( db->init.busy==0 && pName2->n==0 && pTab
99341         && pTab->pSchema==db->aDb[1].pSchema ){
99342     iDb = 1;
99343   }
99344
99345   /* Ensure the table name matches database name and that the table exists */
99346   if( db->mallocFailed ) goto trigger_cleanup;
99347   assert( pTableName->nSrc==1 );
99348   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
99349       sqlite3FixSrcList(&sFix, pTableName) ){
99350     goto trigger_cleanup;
99351   }
99352   pTab = sqlite3SrcListLookup(pParse, pTableName);
99353   if( !pTab ){
99354     /* The table does not exist. */
99355     if( db->init.iDb==1 ){
99356       /* Ticket #3810.
99357       ** Normally, whenever a table is dropped, all associated triggers are
99358       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99359       ** and the table is dropped by a different database connection, the
99360       ** trigger is not visible to the database connection that does the
99361       ** drop so the trigger cannot be dropped.  This results in an
99362       ** "orphaned trigger" - a trigger whose associated table is missing.
99363       */
99364       db->init.orphanTrigger = 1;
99365     }
99366     goto trigger_cleanup;
99367   }
99368   if( IsVirtual(pTab) ){
99369     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99370     goto trigger_cleanup;
99371   }
99372
99373   /* Check that the trigger name is not reserved and that no trigger of the
99374   ** specified name exists */
99375   zName = sqlite3NameFromToken(db, pName);
99376   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99377     goto trigger_cleanup;
99378   }
99379   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99380   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99381                       zName, sqlite3Strlen30(zName)) ){
99382     if( !noErr ){
99383       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
99384     }else{
99385       assert( !db->init.busy );
99386       sqlite3CodeVerifySchema(pParse, iDb);
99387     }
99388     goto trigger_cleanup;
99389   }
99390
99391   /* Do not create a trigger on a system table */
99392   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
99393     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
99394     pParse->nErr++;
99395     goto trigger_cleanup;
99396   }
99397
99398   /* INSTEAD of triggers are only for views and views only support INSTEAD
99399   ** of triggers.
99400   */
99401   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99402     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
99403         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99404     goto trigger_cleanup;
99405   }
99406   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99407     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
99408         " trigger on table: %S", pTableName, 0);
99409     goto trigger_cleanup;
99410   }
99411   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99412
99413 #ifndef SQLITE_OMIT_AUTHORIZATION
99414   {
99415     int code = SQLITE_CREATE_TRIGGER;
99416     const char *zDb = db->aDb[iTabDb].zName;
99417     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99418     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
99419     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99420       goto trigger_cleanup;
99421     }
99422     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99423       goto trigger_cleanup;
99424     }
99425   }
99426 #endif
99427
99428   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99429   ** cannot appear on views.  So we might as well translate every
99430   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99431   ** elsewhere.
99432   */
99433   if (tr_tm == TK_INSTEAD){
99434     tr_tm = TK_BEFORE;
99435   }
99436
99437   /* Build the Trigger object */
99438   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
99439   if( pTrigger==0 ) goto trigger_cleanup;
99440   pTrigger->zName = zName;
99441   zName = 0;
99442   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
99443   pTrigger->pSchema = db->aDb[iDb].pSchema;
99444   pTrigger->pTabSchema = pTab->pSchema;
99445   pTrigger->op = (u8)op;
99446   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99447   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99448   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
99449   assert( pParse->pNewTrigger==0 );
99450   pParse->pNewTrigger = pTrigger;
99451
99452 trigger_cleanup:
99453   sqlite3DbFree(db, zName);
99454   sqlite3SrcListDelete(db, pTableName);
99455   sqlite3IdListDelete(db, pColumns);
99456   sqlite3ExprDelete(db, pWhen);
99457   if( !pParse->pNewTrigger ){
99458     sqlite3DeleteTrigger(db, pTrigger);
99459   }else{
99460     assert( pParse->pNewTrigger==pTrigger );
99461   }
99462 }
99463
99464 /*
99465 ** This routine is called after all of the trigger actions have been parsed
99466 ** in order to complete the process of building the trigger.
99467 */
99468 SQLITE_PRIVATE void sqlite3FinishTrigger(
99469   Parse *pParse,          /* Parser context */
99470   TriggerStep *pStepList, /* The triggered program */
99471   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99472 ){
99473   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99474   char *zName;                            /* Name of trigger */
99475   sqlite3 *db = pParse->db;               /* The database */
99476   DbFixer sFix;                           /* Fixer object */
99477   int iDb;                                /* Database containing the trigger */
99478   Token nameToken;                        /* Trigger name for error reporting */
99479
99480   pParse->pNewTrigger = 0;
99481   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99482   zName = pTrig->zName;
99483   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
99484   pTrig->step_list = pStepList;
99485   while( pStepList ){
99486     pStepList->pTrig = pTrig;
99487     pStepList = pStepList->pNext;
99488   }
99489   nameToken.z = pTrig->zName;
99490   nameToken.n = sqlite3Strlen30(nameToken.z);
99491   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
99492           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
99493     goto triggerfinish_cleanup;
99494   }
99495
99496   /* if we are not initializing,
99497   ** build the sqlite_master entry
99498   */
99499   if( !db->init.busy ){
99500     Vdbe *v;
99501     char *z;
99502
99503     /* Make an entry in the sqlite_master table */
99504     v = sqlite3GetVdbe(pParse);
99505     if( v==0 ) goto triggerfinish_cleanup;
99506     sqlite3BeginWriteOperation(pParse, 0, iDb);
99507     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
99508     sqlite3NestedParse(pParse,
99509        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99510        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
99511        pTrig->table, z);
99512     sqlite3DbFree(db, z);
99513     sqlite3ChangeCookie(pParse, iDb);
99514     sqlite3VdbeAddParseSchemaOp(v, iDb,
99515         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
99516   }
99517
99518   if( db->init.busy ){
99519     Trigger *pLink = pTrig;
99520     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
99521     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99522     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
99523     if( pTrig ){
99524       db->mallocFailed = 1;
99525     }else if( pLink->pSchema==pLink->pTabSchema ){
99526       Table *pTab;
99527       int n = sqlite3Strlen30(pLink->table);
99528       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
99529       assert( pTab!=0 );
99530       pLink->pNext = pTab->pTrigger;
99531       pTab->pTrigger = pLink;
99532     }
99533   }
99534
99535 triggerfinish_cleanup:
99536   sqlite3DeleteTrigger(db, pTrig);
99537   assert( !pParse->pNewTrigger );
99538   sqlite3DeleteTriggerStep(db, pStepList);
99539 }
99540
99541 /*
99542 ** Turn a SELECT statement (that the pSelect parameter points to) into
99543 ** a trigger step.  Return a pointer to a TriggerStep structure.
99544 **
99545 ** The parser calls this routine when it finds a SELECT statement in
99546 ** body of a TRIGGER.  
99547 */
99548 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
99549   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
99550   if( pTriggerStep==0 ) {
99551     sqlite3SelectDelete(db, pSelect);
99552     return 0;
99553   }
99554   pTriggerStep->op = TK_SELECT;
99555   pTriggerStep->pSelect = pSelect;
99556   pTriggerStep->orconf = OE_Default;
99557   return pTriggerStep;
99558 }
99559
99560 /*
99561 ** Allocate space to hold a new trigger step.  The allocated space
99562 ** holds both the TriggerStep object and the TriggerStep.target.z string.
99563 **
99564 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
99565 */
99566 static TriggerStep *triggerStepAllocate(
99567   sqlite3 *db,                /* Database connection */
99568   u8 op,                      /* Trigger opcode */
99569   Token *pName                /* The target name */
99570 ){
99571   TriggerStep *pTriggerStep;
99572
99573   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
99574   if( pTriggerStep ){
99575     char *z = (char*)&pTriggerStep[1];
99576     memcpy(z, pName->z, pName->n);
99577     pTriggerStep->target.z = z;
99578     pTriggerStep->target.n = pName->n;
99579     pTriggerStep->op = op;
99580   }
99581   return pTriggerStep;
99582 }
99583
99584 /*
99585 ** Build a trigger step out of an INSERT statement.  Return a pointer
99586 ** to the new trigger step.
99587 **
99588 ** The parser calls this routine when it sees an INSERT inside the
99589 ** body of a trigger.
99590 */
99591 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
99592   sqlite3 *db,        /* The database connection */
99593   Token *pTableName,  /* Name of the table into which we insert */
99594   IdList *pColumn,    /* List of columns in pTableName to insert into */
99595   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
99596   Select *pSelect,    /* A SELECT statement that supplies values */
99597   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
99598 ){
99599   TriggerStep *pTriggerStep;
99600
99601   assert(pEList == 0 || pSelect == 0);
99602   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
99603
99604   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
99605   if( pTriggerStep ){
99606     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99607     pTriggerStep->pIdList = pColumn;
99608     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99609     pTriggerStep->orconf = orconf;
99610   }else{
99611     sqlite3IdListDelete(db, pColumn);
99612   }
99613   sqlite3ExprListDelete(db, pEList);
99614   sqlite3SelectDelete(db, pSelect);
99615
99616   return pTriggerStep;
99617 }
99618
99619 /*
99620 ** Construct a trigger step that implements an UPDATE statement and return
99621 ** a pointer to that trigger step.  The parser calls this routine when it
99622 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
99623 */
99624 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
99625   sqlite3 *db,         /* The database connection */
99626   Token *pTableName,   /* Name of the table to be updated */
99627   ExprList *pEList,    /* The SET clause: list of column and new values */
99628   Expr *pWhere,        /* The WHERE clause */
99629   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
99630 ){
99631   TriggerStep *pTriggerStep;
99632
99633   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
99634   if( pTriggerStep ){
99635     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99636     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99637     pTriggerStep->orconf = orconf;
99638   }
99639   sqlite3ExprListDelete(db, pEList);
99640   sqlite3ExprDelete(db, pWhere);
99641   return pTriggerStep;
99642 }
99643
99644 /*
99645 ** Construct a trigger step that implements a DELETE statement and return
99646 ** a pointer to that trigger step.  The parser calls this routine when it
99647 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
99648 */
99649 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
99650   sqlite3 *db,            /* Database connection */
99651   Token *pTableName,      /* The table from which rows are deleted */
99652   Expr *pWhere            /* The WHERE clause */
99653 ){
99654   TriggerStep *pTriggerStep;
99655
99656   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
99657   if( pTriggerStep ){
99658     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99659     pTriggerStep->orconf = OE_Default;
99660   }
99661   sqlite3ExprDelete(db, pWhere);
99662   return pTriggerStep;
99663 }
99664
99665 /* 
99666 ** Recursively delete a Trigger structure
99667 */
99668 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
99669   if( pTrigger==0 ) return;
99670   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
99671   sqlite3DbFree(db, pTrigger->zName);
99672   sqlite3DbFree(db, pTrigger->table);
99673   sqlite3ExprDelete(db, pTrigger->pWhen);
99674   sqlite3IdListDelete(db, pTrigger->pColumns);
99675   sqlite3DbFree(db, pTrigger);
99676 }
99677
99678 /*
99679 ** This function is called to drop a trigger from the database schema. 
99680 **
99681 ** This may be called directly from the parser and therefore identifies
99682 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
99683 ** same job as this routine except it takes a pointer to the trigger
99684 ** instead of the trigger name.
99685 **/
99686 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
99687   Trigger *pTrigger = 0;
99688   int i;
99689   const char *zDb;
99690   const char *zName;
99691   int nName;
99692   sqlite3 *db = pParse->db;
99693
99694   if( db->mallocFailed ) goto drop_trigger_cleanup;
99695   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99696     goto drop_trigger_cleanup;
99697   }
99698
99699   assert( pName->nSrc==1 );
99700   zDb = pName->a[0].zDatabase;
99701   zName = pName->a[0].zName;
99702   nName = sqlite3Strlen30(zName);
99703   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
99704   for(i=OMIT_TEMPDB; i<db->nDb; i++){
99705     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99706     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
99707     assert( sqlite3SchemaMutexHeld(db, j, 0) );
99708     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
99709     if( pTrigger ) break;
99710   }
99711   if( !pTrigger ){
99712     if( !noErr ){
99713       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
99714     }else{
99715       sqlite3CodeVerifyNamedSchema(pParse, zDb);
99716     }
99717     pParse->checkSchema = 1;
99718     goto drop_trigger_cleanup;
99719   }
99720   sqlite3DropTriggerPtr(pParse, pTrigger);
99721
99722 drop_trigger_cleanup:
99723   sqlite3SrcListDelete(db, pName);
99724 }
99725
99726 /*
99727 ** Return a pointer to the Table structure for the table that a trigger
99728 ** is set on.
99729 */
99730 static Table *tableOfTrigger(Trigger *pTrigger){
99731   int n = sqlite3Strlen30(pTrigger->table);
99732   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
99733 }
99734
99735
99736 /*
99737 ** Drop a trigger given a pointer to that trigger. 
99738 */
99739 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
99740   Table   *pTable;
99741   Vdbe *v;
99742   sqlite3 *db = pParse->db;
99743   int iDb;
99744
99745   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
99746   assert( iDb>=0 && iDb<db->nDb );
99747   pTable = tableOfTrigger(pTrigger);
99748   assert( pTable );
99749   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
99750 #ifndef SQLITE_OMIT_AUTHORIZATION
99751   {
99752     int code = SQLITE_DROP_TRIGGER;
99753     const char *zDb = db->aDb[iDb].zName;
99754     const char *zTab = SCHEMA_TABLE(iDb);
99755     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
99756     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
99757       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
99758       return;
99759     }
99760   }
99761 #endif
99762
99763   /* Generate code to destroy the database record of the trigger.
99764   */
99765   assert( pTable!=0 );
99766   if( (v = sqlite3GetVdbe(pParse))!=0 ){
99767     int base;
99768     static const VdbeOpList dropTrigger[] = {
99769       { OP_Rewind,     0, ADDR(9),  0},
99770       { OP_String8,    0, 1,        0}, /* 1 */
99771       { OP_Column,     0, 1,        2},
99772       { OP_Ne,         2, ADDR(8),  1},
99773       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
99774       { OP_Column,     0, 0,        2},
99775       { OP_Ne,         2, ADDR(8),  1},
99776       { OP_Delete,     0, 0,        0},
99777       { OP_Next,       0, ADDR(1),  0}, /* 8 */
99778     };
99779
99780     sqlite3BeginWriteOperation(pParse, 0, iDb);
99781     sqlite3OpenMasterTable(pParse, iDb);
99782     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
99783     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
99784     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
99785     sqlite3ChangeCookie(pParse, iDb);
99786     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
99787     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
99788     if( pParse->nMem<3 ){
99789       pParse->nMem = 3;
99790     }
99791   }
99792 }
99793
99794 /*
99795 ** Remove a trigger from the hash tables of the sqlite* pointer.
99796 */
99797 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
99798   Trigger *pTrigger;
99799   Hash *pHash;
99800
99801   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99802   pHash = &(db->aDb[iDb].pSchema->trigHash);
99803   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
99804   if( ALWAYS(pTrigger) ){
99805     if( pTrigger->pSchema==pTrigger->pTabSchema ){
99806       Table *pTab = tableOfTrigger(pTrigger);
99807       Trigger **pp;
99808       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99809       *pp = (*pp)->pNext;
99810     }
99811     sqlite3DeleteTrigger(db, pTrigger);
99812     db->flags |= SQLITE_InternChanges;
99813   }
99814 }
99815
99816 /*
99817 ** pEList is the SET clause of an UPDATE statement.  Each entry
99818 ** in pEList is of the format <id>=<expr>.  If any of the entries
99819 ** in pEList have an <id> which matches an identifier in pIdList,
99820 ** then return TRUE.  If pIdList==NULL, then it is considered a
99821 ** wildcard that matches anything.  Likewise if pEList==NULL then
99822 ** it matches anything so always return true.  Return false only
99823 ** if there is no match.
99824 */
99825 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99826   int e;
99827   if( pIdList==0 || NEVER(pEList==0) ) return 1;
99828   for(e=0; e<pEList->nExpr; e++){
99829     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99830   }
99831   return 0; 
99832 }
99833
99834 /*
99835 ** Return a list of all triggers on table pTab if there exists at least
99836 ** one trigger that must be fired when an operation of type 'op' is 
99837 ** performed on the table, and, if that operation is an UPDATE, if at
99838 ** least one of the columns in pChanges is being modified.
99839 */
99840 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
99841   Parse *pParse,          /* Parse context */
99842   Table *pTab,            /* The table the contains the triggers */
99843   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99844   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99845   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99846 ){
99847   int mask = 0;
99848   Trigger *pList = 0;
99849   Trigger *p;
99850
99851   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
99852     pList = sqlite3TriggerList(pParse, pTab);
99853   }
99854   assert( pList==0 || IsVirtual(pTab)==0 );
99855   for(p=pList; p; p=p->pNext){
99856     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99857       mask |= p->tr_tm;
99858     }
99859   }
99860   if( pMask ){
99861     *pMask = mask;
99862   }
99863   return (mask ? pList : 0);
99864 }
99865
99866 /*
99867 ** Convert the pStep->target token into a SrcList and return a pointer
99868 ** to that SrcList.
99869 **
99870 ** This routine adds a specific database name, if needed, to the target when
99871 ** forming the SrcList.  This prevents a trigger in one database from
99872 ** referring to a target in another database.  An exception is when the
99873 ** trigger is in TEMP in which case it can refer to any other database it
99874 ** wants.
99875 */
99876 static SrcList *targetSrcList(
99877   Parse *pParse,       /* The parsing context */
99878   TriggerStep *pStep   /* The trigger containing the target token */
99879 ){
99880   int iDb;             /* Index of the database to use */
99881   SrcList *pSrc;       /* SrcList to be returned */
99882
99883   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
99884   if( pSrc ){
99885     assert( pSrc->nSrc>0 );
99886     assert( pSrc->a!=0 );
99887     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
99888     if( iDb==0 || iDb>=2 ){
99889       sqlite3 *db = pParse->db;
99890       assert( iDb<pParse->db->nDb );
99891       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
99892     }
99893   }
99894   return pSrc;
99895 }
99896
99897 /*
99898 ** Generate VDBE code for the statements inside the body of a single 
99899 ** trigger.
99900 */
99901 static int codeTriggerProgram(
99902   Parse *pParse,            /* The parser context */
99903   TriggerStep *pStepList,   /* List of statements inside the trigger body */
99904   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
99905 ){
99906   TriggerStep *pStep;
99907   Vdbe *v = pParse->pVdbe;
99908   sqlite3 *db = pParse->db;
99909
99910   assert( pParse->pTriggerTab && pParse->pToplevel );
99911   assert( pStepList );
99912   assert( v!=0 );
99913   for(pStep=pStepList; pStep; pStep=pStep->pNext){
99914     /* Figure out the ON CONFLICT policy that will be used for this step
99915     ** of the trigger program. If the statement that caused this trigger
99916     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
99917     ** the ON CONFLICT policy that was specified as part of the trigger
99918     ** step statement. Example:
99919     **
99920     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
99921     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
99922     **   END;
99923     **
99924     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
99925     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
99926     */
99927     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
99928
99929     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto 
99930     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
99931     ** that it is not safe to refactor constants (this happens after the
99932     ** start of the first loop in the SQL statement is coded - at that 
99933     ** point code may be conditionally executed, so it is no longer safe to 
99934     ** initialize constant register values).  */
99935     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
99936     pParse->cookieGoto = 0;
99937
99938     switch( pStep->op ){
99939       case TK_UPDATE: {
99940         sqlite3Update(pParse, 
99941           targetSrcList(pParse, pStep),
99942           sqlite3ExprListDup(db, pStep->pExprList, 0), 
99943           sqlite3ExprDup(db, pStep->pWhere, 0), 
99944           pParse->eOrconf
99945         );
99946         break;
99947       }
99948       case TK_INSERT: {
99949         sqlite3Insert(pParse, 
99950           targetSrcList(pParse, pStep),
99951           sqlite3ExprListDup(db, pStep->pExprList, 0), 
99952           sqlite3SelectDup(db, pStep->pSelect, 0), 
99953           sqlite3IdListDup(db, pStep->pIdList), 
99954           pParse->eOrconf
99955         );
99956         break;
99957       }
99958       case TK_DELETE: {
99959         sqlite3DeleteFrom(pParse, 
99960           targetSrcList(pParse, pStep),
99961           sqlite3ExprDup(db, pStep->pWhere, 0)
99962         );
99963         break;
99964       }
99965       default: assert( pStep->op==TK_SELECT ); {
99966         SelectDest sDest;
99967         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
99968         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
99969         sqlite3Select(pParse, pSelect, &sDest);
99970         sqlite3SelectDelete(db, pSelect);
99971         break;
99972       }
99973     } 
99974     if( pStep->op!=TK_SELECT ){
99975       sqlite3VdbeAddOp0(v, OP_ResetCount);
99976     }
99977   }
99978
99979   return 0;
99980 }
99981
99982 #ifdef SQLITE_DEBUG
99983 /*
99984 ** This function is used to add VdbeComment() annotations to a VDBE
99985 ** program. It is not used in production code, only for debugging.
99986 */
99987 static const char *onErrorText(int onError){
99988   switch( onError ){
99989     case OE_Abort:    return "abort";
99990     case OE_Rollback: return "rollback";
99991     case OE_Fail:     return "fail";
99992     case OE_Replace:  return "replace";
99993     case OE_Ignore:   return "ignore";
99994     case OE_Default:  return "default";
99995   }
99996   return "n/a";
99997 }
99998 #endif
99999
100000 /*
100001 ** Parse context structure pFrom has just been used to create a sub-vdbe
100002 ** (trigger program). If an error has occurred, transfer error information
100003 ** from pFrom to pTo.
100004 */
100005 static void transferParseError(Parse *pTo, Parse *pFrom){
100006   assert( pFrom->zErrMsg==0 || pFrom->nErr );
100007   assert( pTo->zErrMsg==0 || pTo->nErr );
100008   if( pTo->nErr==0 ){
100009     pTo->zErrMsg = pFrom->zErrMsg;
100010     pTo->nErr = pFrom->nErr;
100011   }else{
100012     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
100013   }
100014 }
100015
100016 /*
100017 ** Create and populate a new TriggerPrg object with a sub-program 
100018 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
100019 */
100020 static TriggerPrg *codeRowTrigger(
100021   Parse *pParse,       /* Current parse context */
100022   Trigger *pTrigger,   /* Trigger to code */
100023   Table *pTab,         /* The table pTrigger is attached to */
100024   int orconf           /* ON CONFLICT policy to code trigger program with */
100025 ){
100026   Parse *pTop = sqlite3ParseToplevel(pParse);
100027   sqlite3 *db = pParse->db;   /* Database handle */
100028   TriggerPrg *pPrg;           /* Value to return */
100029   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
100030   Vdbe *v;                    /* Temporary VM */
100031   NameContext sNC;            /* Name context for sub-vdbe */
100032   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
100033   Parse *pSubParse;           /* Parse context for sub-vdbe */
100034   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
100035
100036   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100037   assert( pTop->pVdbe );
100038
100039   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
100040   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
100041   ** list of the top-level Parse object sooner rather than later.  */
100042   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
100043   if( !pPrg ) return 0;
100044   pPrg->pNext = pTop->pTriggerPrg;
100045   pTop->pTriggerPrg = pPrg;
100046   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
100047   if( !pProgram ) return 0;
100048   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
100049   pPrg->pTrigger = pTrigger;
100050   pPrg->orconf = orconf;
100051   pPrg->aColmask[0] = 0xffffffff;
100052   pPrg->aColmask[1] = 0xffffffff;
100053
100054   /* Allocate and populate a new Parse context to use for coding the 
100055   ** trigger sub-program.  */
100056   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
100057   if( !pSubParse ) return 0;
100058   memset(&sNC, 0, sizeof(sNC));
100059   sNC.pParse = pSubParse;
100060   pSubParse->db = db;
100061   pSubParse->pTriggerTab = pTab;
100062   pSubParse->pToplevel = pTop;
100063   pSubParse->zAuthContext = pTrigger->zName;
100064   pSubParse->eTriggerOp = pTrigger->op;
100065   pSubParse->nQueryLoop = pParse->nQueryLoop;
100066
100067   v = sqlite3GetVdbe(pSubParse);
100068   if( v ){
100069     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
100070       pTrigger->zName, onErrorText(orconf),
100071       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
100072         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
100073         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
100074         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
100075       pTab->zName
100076     ));
100077 #ifndef SQLITE_OMIT_TRACE
100078     sqlite3VdbeChangeP4(v, -1, 
100079       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
100080     );
100081 #endif
100082
100083     /* If one was specified, code the WHEN clause. If it evaluates to false
100084     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
100085     ** OP_Halt inserted at the end of the program.  */
100086     if( pTrigger->pWhen ){
100087       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
100088       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
100089        && db->mallocFailed==0 
100090       ){
100091         iEndTrigger = sqlite3VdbeMakeLabel(v);
100092         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
100093       }
100094       sqlite3ExprDelete(db, pWhen);
100095     }
100096
100097     /* Code the trigger program into the sub-vdbe. */
100098     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
100099
100100     /* Insert an OP_Halt at the end of the sub-program. */
100101     if( iEndTrigger ){
100102       sqlite3VdbeResolveLabel(v, iEndTrigger);
100103     }
100104     sqlite3VdbeAddOp0(v, OP_Halt);
100105     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
100106
100107     transferParseError(pParse, pSubParse);
100108     if( db->mallocFailed==0 ){
100109       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
100110     }
100111     pProgram->nMem = pSubParse->nMem;
100112     pProgram->nCsr = pSubParse->nTab;
100113     pProgram->nOnce = pSubParse->nOnce;
100114     pProgram->token = (void *)pTrigger;
100115     pPrg->aColmask[0] = pSubParse->oldmask;
100116     pPrg->aColmask[1] = pSubParse->newmask;
100117     sqlite3VdbeDelete(v);
100118   }
100119
100120   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
100121   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
100122   sqlite3StackFree(db, pSubParse);
100123
100124   return pPrg;
100125 }
100126     
100127 /*
100128 ** Return a pointer to a TriggerPrg object containing the sub-program for
100129 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
100130 ** TriggerPrg object exists, a new object is allocated and populated before
100131 ** being returned.
100132 */
100133 static TriggerPrg *getRowTrigger(
100134   Parse *pParse,       /* Current parse context */
100135   Trigger *pTrigger,   /* Trigger to code */
100136   Table *pTab,         /* The table trigger pTrigger is attached to */
100137   int orconf           /* ON CONFLICT algorithm. */
100138 ){
100139   Parse *pRoot = sqlite3ParseToplevel(pParse);
100140   TriggerPrg *pPrg;
100141
100142   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100143
100144   /* It may be that this trigger has already been coded (or is in the
100145   ** process of being coded). If this is the case, then an entry with
100146   ** a matching TriggerPrg.pTrigger field will be present somewhere
100147   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
100148   for(pPrg=pRoot->pTriggerPrg; 
100149       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
100150       pPrg=pPrg->pNext
100151   );
100152
100153   /* If an existing TriggerPrg could not be located, create a new one. */
100154   if( !pPrg ){
100155     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
100156   }
100157
100158   return pPrg;
100159 }
100160
100161 /*
100162 ** Generate code for the trigger program associated with trigger p on 
100163 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
100164 ** function are the same as those described in the header function for
100165 ** sqlite3CodeRowTrigger()
100166 */
100167 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
100168   Parse *pParse,       /* Parse context */
100169   Trigger *p,          /* Trigger to code */
100170   Table *pTab,         /* The table to code triggers from */
100171   int reg,             /* Reg array containing OLD.* and NEW.* values */
100172   int orconf,          /* ON CONFLICT policy */
100173   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100174 ){
100175   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
100176   TriggerPrg *pPrg;
100177   pPrg = getRowTrigger(pParse, p, pTab, orconf);
100178   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
100179
100180   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
100181   ** is a pointer to the sub-vdbe containing the trigger program.  */
100182   if( pPrg ){
100183     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
100184
100185     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
100186     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
100187     VdbeComment(
100188         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
100189
100190     /* Set the P5 operand of the OP_Program instruction to non-zero if
100191     ** recursive invocation of this trigger program is disallowed. Recursive
100192     ** invocation is disallowed if (a) the sub-program is really a trigger,
100193     ** not a foreign key action, and (b) the flag to enable recursive triggers
100194     ** is clear.  */
100195     sqlite3VdbeChangeP5(v, (u8)bRecursive);
100196   }
100197 }
100198
100199 /*
100200 ** This is called to code the required FOR EACH ROW triggers for an operation
100201 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
100202 ** is given by the op paramater. The tr_tm parameter determines whether the
100203 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
100204 ** parameter pChanges is passed the list of columns being modified.
100205 **
100206 ** If there are no triggers that fire at the specified time for the specified
100207 ** operation on pTab, this function is a no-op.
100208 **
100209 ** The reg argument is the address of the first in an array of registers 
100210 ** that contain the values substituted for the new.* and old.* references
100211 ** in the trigger program. If N is the number of columns in table pTab
100212 ** (a copy of pTab->nCol), then registers are populated as follows:
100213 **
100214 **   Register       Contains
100215 **   ------------------------------------------------------
100216 **   reg+0          OLD.rowid
100217 **   reg+1          OLD.* value of left-most column of pTab
100218 **   ...            ...
100219 **   reg+N          OLD.* value of right-most column of pTab
100220 **   reg+N+1        NEW.rowid
100221 **   reg+N+2        OLD.* value of left-most column of pTab
100222 **   ...            ...
100223 **   reg+N+N+1      NEW.* value of right-most column of pTab
100224 **
100225 ** For ON DELETE triggers, the registers containing the NEW.* values will
100226 ** never be accessed by the trigger program, so they are not allocated or 
100227 ** populated by the caller (there is no data to populate them with anyway). 
100228 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
100229 ** are never accessed, and so are not allocated by the caller. So, for an
100230 ** ON INSERT trigger, the value passed to this function as parameter reg
100231 ** is not a readable register, although registers (reg+N) through 
100232 ** (reg+N+N+1) are.
100233 **
100234 ** Parameter orconf is the default conflict resolution algorithm for the
100235 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
100236 ** is the instruction that control should jump to if a trigger program
100237 ** raises an IGNORE exception.
100238 */
100239 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
100240   Parse *pParse,       /* Parse context */
100241   Trigger *pTrigger,   /* List of triggers on table pTab */
100242   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
100243   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100244   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100245   Table *pTab,         /* The table to code triggers from */
100246   int reg,             /* The first in an array of registers (see above) */
100247   int orconf,          /* ON CONFLICT policy */
100248   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100249 ){
100250   Trigger *p;          /* Used to iterate through pTrigger list */
100251
100252   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100253   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100254   assert( (op==TK_UPDATE)==(pChanges!=0) );
100255
100256   for(p=pTrigger; p; p=p->pNext){
100257
100258     /* Sanity checking:  The schema for the trigger and for the table are
100259     ** always defined.  The trigger must be in the same schema as the table
100260     ** or else it must be a TEMP trigger. */
100261     assert( p->pSchema!=0 );
100262     assert( p->pTabSchema!=0 );
100263     assert( p->pSchema==p->pTabSchema 
100264          || p->pSchema==pParse->db->aDb[1].pSchema );
100265
100266     /* Determine whether we should code this trigger */
100267     if( p->op==op 
100268      && p->tr_tm==tr_tm 
100269      && checkColumnOverlap(p->pColumns, pChanges)
100270     ){
100271       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100272     }
100273   }
100274 }
100275
100276 /*
100277 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
100278 ** This function returns a 32-bit bitmask indicating which columns of the 
100279 ** old.* or new.* tables actually are used by triggers. This information 
100280 ** may be used by the caller, for example, to avoid having to load the entire
100281 ** old.* record into memory when executing an UPDATE or DELETE command.
100282 **
100283 ** Bit 0 of the returned mask is set if the left-most column of the
100284 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100285 ** the second leftmost column value is required, and so on. If there
100286 ** are more than 32 columns in the table, and at least one of the columns
100287 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
100288 **
100289 ** It is not possible to determine if the old.rowid or new.rowid column is 
100290 ** accessed by triggers. The caller must always assume that it is.
100291 **
100292 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100293 ** applies to the old.* table. If 1, the new.* table.
100294 **
100295 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100296 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100297 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100298 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100299 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100300 */
100301 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
100302   Parse *pParse,       /* Parse context */
100303   Trigger *pTrigger,   /* List of triggers on table pTab */
100304   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100305   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100306   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100307   Table *pTab,         /* The table to code triggers from */
100308   int orconf           /* Default ON CONFLICT policy for trigger steps */
100309 ){
100310   const int op = pChanges ? TK_UPDATE : TK_DELETE;
100311   u32 mask = 0;
100312   Trigger *p;
100313
100314   assert( isNew==1 || isNew==0 );
100315   for(p=pTrigger; p; p=p->pNext){
100316     if( p->op==op && (tr_tm&p->tr_tm)
100317      && checkColumnOverlap(p->pColumns,pChanges)
100318     ){
100319       TriggerPrg *pPrg;
100320       pPrg = getRowTrigger(pParse, p, pTab, orconf);
100321       if( pPrg ){
100322         mask |= pPrg->aColmask[isNew];
100323       }
100324     }
100325   }
100326
100327   return mask;
100328 }
100329
100330 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
100331
100332 /************** End of trigger.c *********************************************/
100333 /************** Begin file update.c ******************************************/
100334 /*
100335 ** 2001 September 15
100336 **
100337 ** The author disclaims copyright to this source code.  In place of
100338 ** a legal notice, here is a blessing:
100339 **
100340 **    May you do good and not evil.
100341 **    May you find forgiveness for yourself and forgive others.
100342 **    May you share freely, never taking more than you give.
100343 **
100344 *************************************************************************
100345 ** This file contains C code routines that are called by the parser
100346 ** to handle UPDATE statements.
100347 */
100348
100349 #ifndef SQLITE_OMIT_VIRTUALTABLE
100350 /* Forward declaration */
100351 static void updateVirtualTable(
100352   Parse *pParse,       /* The parsing context */
100353   SrcList *pSrc,       /* The virtual table to be modified */
100354   Table *pTab,         /* The virtual table */
100355   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100356   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100357   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100358   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100359   int onError          /* ON CONFLICT strategy */
100360 );
100361 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100362
100363 /*
100364 ** The most recently coded instruction was an OP_Column to retrieve the
100365 ** i-th column of table pTab. This routine sets the P4 parameter of the 
100366 ** OP_Column to the default value, if any.
100367 **
100368 ** The default value of a column is specified by a DEFAULT clause in the 
100369 ** column definition. This was either supplied by the user when the table
100370 ** was created, or added later to the table definition by an ALTER TABLE
100371 ** command. If the latter, then the row-records in the table btree on disk
100372 ** may not contain a value for the column and the default value, taken
100373 ** from the P4 parameter of the OP_Column instruction, is returned instead.
100374 ** If the former, then all row-records are guaranteed to include a value
100375 ** for the column and the P4 value is not required.
100376 **
100377 ** Column definitions created by an ALTER TABLE command may only have 
100378 ** literal default values specified: a number, null or a string. (If a more
100379 ** complicated default expression value was provided, it is evaluated 
100380 ** when the ALTER TABLE is executed and one of the literal values written
100381 ** into the sqlite_master table.)
100382 **
100383 ** Therefore, the P4 parameter is only required if the default value for
100384 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
100385 ** function is capable of transforming these types of expressions into
100386 ** sqlite3_value objects.
100387 **
100388 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
100389 ** on register iReg. This is used when an equivalent integer value is 
100390 ** stored in place of an 8-byte floating point value in order to save 
100391 ** space.
100392 */
100393 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100394   assert( pTab!=0 );
100395   if( !pTab->pSelect ){
100396     sqlite3_value *pValue;
100397     u8 enc = ENC(sqlite3VdbeDb(v));
100398     Column *pCol = &pTab->aCol[i];
100399     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100400     assert( i<pTab->nCol );
100401     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
100402                          pCol->affinity, &pValue);
100403     if( pValue ){
100404       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100405     }
100406 #ifndef SQLITE_OMIT_FLOATING_POINT
100407     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
100408       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
100409     }
100410 #endif
100411   }
100412 }
100413
100414 /*
100415 ** Process an UPDATE statement.
100416 **
100417 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100418 **          \_______/ \________/     \______/       \________________/
100419 *            onError   pTabList      pChanges             pWhere
100420 */
100421 SQLITE_PRIVATE void sqlite3Update(
100422   Parse *pParse,         /* The parser context */
100423   SrcList *pTabList,     /* The table in which we should change things */
100424   ExprList *pChanges,    /* Things to be changed */
100425   Expr *pWhere,          /* The WHERE clause.  May be null */
100426   int onError            /* How to handle constraint errors */
100427 ){
100428   int i, j;              /* Loop counters */
100429   Table *pTab;           /* The table to be updated */
100430   int addr = 0;          /* VDBE instruction address of the start of the loop */
100431   WhereInfo *pWInfo;     /* Information about the WHERE clause */
100432   Vdbe *v;               /* The virtual database engine */
100433   Index *pIdx;           /* For looping over indices */
100434   int nIdx;              /* Number of indices that need updating */
100435   int iCur;              /* VDBE Cursor number of pTab */
100436   sqlite3 *db;           /* The database structure */
100437   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100438   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100439                          ** an expression for the i-th column of the table.
100440                          ** aXRef[i]==-1 if the i-th column is not changed. */
100441   int chngRowid;         /* True if the record number is being changed */
100442   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100443   int openAll = 0;       /* True if all indices need to be opened */
100444   AuthContext sContext;  /* The authorization context */
100445   NameContext sNC;       /* The name-context to resolve expressions in */
100446   int iDb;               /* Database containing the table being updated */
100447   int okOnePass;         /* True for one-pass algorithm without the FIFO */
100448   int hasFK;             /* True if foreign key processing is required */
100449
100450 #ifndef SQLITE_OMIT_TRIGGER
100451   int isView;            /* True when updating a view (INSTEAD OF trigger) */
100452   Trigger *pTrigger;     /* List of triggers on pTab, if required */
100453   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100454 #endif
100455   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100456
100457   /* Register Allocations */
100458   int regRowCount = 0;   /* A count of rows changed */
100459   int regOldRowid;       /* The old rowid */
100460   int regNewRowid;       /* The new rowid */
100461   int regNew;            /* Content of the NEW.* table in triggers */
100462   int regOld = 0;        /* Content of OLD.* table in triggers */
100463   int regRowSet = 0;     /* Rowset of rows to be updated */
100464
100465   memset(&sContext, 0, sizeof(sContext));
100466   db = pParse->db;
100467   if( pParse->nErr || db->mallocFailed ){
100468     goto update_cleanup;
100469   }
100470   assert( pTabList->nSrc==1 );
100471
100472   /* Locate the table which we want to update. 
100473   */
100474   pTab = sqlite3SrcListLookup(pParse, pTabList);
100475   if( pTab==0 ) goto update_cleanup;
100476   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100477
100478   /* Figure out if we have any triggers and if the table being
100479   ** updated is a view.
100480   */
100481 #ifndef SQLITE_OMIT_TRIGGER
100482   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100483   isView = pTab->pSelect!=0;
100484   assert( pTrigger || tmask==0 );
100485 #else
100486 # define pTrigger 0
100487 # define isView 0
100488 # define tmask 0
100489 #endif
100490 #ifdef SQLITE_OMIT_VIEW
100491 # undef isView
100492 # define isView 0
100493 #endif
100494
100495   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100496     goto update_cleanup;
100497   }
100498   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100499     goto update_cleanup;
100500   }
100501   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100502   if( aXRef==0 ) goto update_cleanup;
100503   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100504
100505   /* Allocate a cursors for the main database table and for all indices.
100506   ** The index cursors might not be used, but if they are used they
100507   ** need to occur right after the database cursor.  So go ahead and
100508   ** allocate enough space, just in case.
100509   */
100510   pTabList->a[0].iCursor = iCur = pParse->nTab++;
100511   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100512     pParse->nTab++;
100513   }
100514
100515   /* Initialize the name-context */
100516   memset(&sNC, 0, sizeof(sNC));
100517   sNC.pParse = pParse;
100518   sNC.pSrcList = pTabList;
100519
100520   /* Resolve the column names in all the expressions of the
100521   ** of the UPDATE statement.  Also find the column index
100522   ** for each column to be updated in the pChanges array.  For each
100523   ** column to be updated, make sure we have authorization to change
100524   ** that column.
100525   */
100526   chngRowid = 0;
100527   for(i=0; i<pChanges->nExpr; i++){
100528     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
100529       goto update_cleanup;
100530     }
100531     for(j=0; j<pTab->nCol; j++){
100532       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
100533         if( j==pTab->iPKey ){
100534           chngRowid = 1;
100535           pRowidExpr = pChanges->a[i].pExpr;
100536         }
100537         aXRef[j] = i;
100538         break;
100539       }
100540     }
100541     if( j>=pTab->nCol ){
100542       if( sqlite3IsRowid(pChanges->a[i].zName) ){
100543         chngRowid = 1;
100544         pRowidExpr = pChanges->a[i].pExpr;
100545       }else{
100546         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
100547         pParse->checkSchema = 1;
100548         goto update_cleanup;
100549       }
100550     }
100551 #ifndef SQLITE_OMIT_AUTHORIZATION
100552     {
100553       int rc;
100554       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
100555                            pTab->aCol[j].zName, db->aDb[iDb].zName);
100556       if( rc==SQLITE_DENY ){
100557         goto update_cleanup;
100558       }else if( rc==SQLITE_IGNORE ){
100559         aXRef[j] = -1;
100560       }
100561     }
100562 #endif
100563   }
100564
100565   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
100566
100567   /* Allocate memory for the array aRegIdx[].  There is one entry in the
100568   ** array for each index associated with table being updated.  Fill in
100569   ** the value with a register number for indices that are to be used
100570   ** and with zero for unused indices.
100571   */
100572   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
100573   if( nIdx>0 ){
100574     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
100575     if( aRegIdx==0 ) goto update_cleanup;
100576   }
100577   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
100578     int reg;
100579     if( hasFK || chngRowid ){
100580       reg = ++pParse->nMem;
100581     }else{
100582       reg = 0;
100583       for(i=0; i<pIdx->nColumn; i++){
100584         if( aXRef[pIdx->aiColumn[i]]>=0 ){
100585           reg = ++pParse->nMem;
100586           break;
100587         }
100588       }
100589     }
100590     aRegIdx[j] = reg;
100591   }
100592
100593   /* Begin generating code. */
100594   v = sqlite3GetVdbe(pParse);
100595   if( v==0 ) goto update_cleanup;
100596   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
100597   sqlite3BeginWriteOperation(pParse, 1, iDb);
100598
100599 #ifndef SQLITE_OMIT_VIRTUALTABLE
100600   /* Virtual tables must be handled separately */
100601   if( IsVirtual(pTab) ){
100602     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
100603                        pWhere, onError);
100604     pWhere = 0;
100605     pTabList = 0;
100606     goto update_cleanup;
100607   }
100608 #endif
100609
100610   /* Allocate required registers. */
100611   regRowSet = ++pParse->nMem;
100612   regOldRowid = regNewRowid = ++pParse->nMem;
100613   if( pTrigger || hasFK ){
100614     regOld = pParse->nMem + 1;
100615     pParse->nMem += pTab->nCol;
100616   }
100617   if( chngRowid || pTrigger || hasFK ){
100618     regNewRowid = ++pParse->nMem;
100619   }
100620   regNew = pParse->nMem + 1;
100621   pParse->nMem += pTab->nCol;
100622
100623   /* Start the view context. */
100624   if( isView ){
100625     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
100626   }
100627
100628   /* If we are trying to update a view, realize that view into
100629   ** a ephemeral table.
100630   */
100631 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
100632   if( isView ){
100633     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
100634   }
100635 #endif
100636
100637   /* Resolve the column names in all the expressions in the
100638   ** WHERE clause.
100639   */
100640   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
100641     goto update_cleanup;
100642   }
100643
100644   /* Begin the database scan
100645   */
100646   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
100647   pWInfo = sqlite3WhereBegin(
100648       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
100649   );
100650   if( pWInfo==0 ) goto update_cleanup;
100651   okOnePass = pWInfo->okOnePass;
100652
100653   /* Remember the rowid of every item to be updated.
100654   */
100655   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
100656   if( !okOnePass ){
100657     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
100658   }
100659
100660   /* End the database scan loop.
100661   */
100662   sqlite3WhereEnd(pWInfo);
100663
100664   /* Initialize the count of updated rows
100665   */
100666   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
100667     regRowCount = ++pParse->nMem;
100668     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100669   }
100670
100671   if( !isView ){
100672     /* 
100673     ** Open every index that needs updating.  Note that if any
100674     ** index could potentially invoke a REPLACE conflict resolution 
100675     ** action, then we need to open all indices because we might need
100676     ** to be deleting some records.
100677     */
100678     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
100679     if( onError==OE_Replace ){
100680       openAll = 1;
100681     }else{
100682       openAll = 0;
100683       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100684         if( pIdx->onError==OE_Replace ){
100685           openAll = 1;
100686           break;
100687         }
100688       }
100689     }
100690     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100691       assert( aRegIdx );
100692       if( openAll || aRegIdx[i]>0 ){
100693         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
100694         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
100695                        (char*)pKey, P4_KEYINFO_HANDOFF);
100696         assert( pParse->nTab>iCur+i+1 );
100697       }
100698     }
100699   }
100700
100701   /* Top of the update loop */
100702   if( okOnePass ){
100703     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
100704     addr = sqlite3VdbeAddOp0(v, OP_Goto);
100705     sqlite3VdbeJumpHere(v, a1);
100706   }else{
100707     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
100708   }
100709
100710   /* Make cursor iCur point to the record that is being updated. If
100711   ** this record does not exist for some reason (deleted by a trigger,
100712   ** for example, then jump to the next iteration of the RowSet loop.  */
100713   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100714
100715   /* If the record number will change, set register regNewRowid to
100716   ** contain the new value. If the record number is not being modified,
100717   ** then regNewRowid is the same register as regOldRowid, which is
100718   ** already populated.  */
100719   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
100720   if( chngRowid ){
100721     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
100722     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
100723   }
100724
100725   /* If there are triggers on this table, populate an array of registers 
100726   ** with the required old.* column data.  */
100727   if( hasFK || pTrigger ){
100728     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
100729     oldmask |= sqlite3TriggerColmask(pParse, 
100730         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
100731     );
100732     for(i=0; i<pTab->nCol; i++){
100733       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
100734         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
100735       }else{
100736         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
100737       }
100738     }
100739     if( chngRowid==0 ){
100740       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
100741     }
100742   }
100743
100744   /* Populate the array of registers beginning at regNew with the new
100745   ** row data. This array is used to check constaints, create the new
100746   ** table and index records, and as the values for any new.* references
100747   ** made by triggers.
100748   **
100749   ** If there are one or more BEFORE triggers, then do not populate the
100750   ** registers associated with columns that are (a) not modified by
100751   ** this UPDATE statement and (b) not accessed by new.* references. The
100752   ** values for registers not modified by the UPDATE must be reloaded from 
100753   ** the database after the BEFORE triggers are fired anyway (as the trigger 
100754   ** may have modified them). So not loading those that are not going to
100755   ** be used eliminates some redundant opcodes.
100756   */
100757   newmask = sqlite3TriggerColmask(
100758       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
100759   );
100760   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
100761   for(i=0; i<pTab->nCol; i++){
100762     if( i==pTab->iPKey ){
100763       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
100764     }else{
100765       j = aXRef[i];
100766       if( j>=0 ){
100767         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
100768       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
100769         /* This branch loads the value of a column that will not be changed 
100770         ** into a register. This is done if there are no BEFORE triggers, or
100771         ** if there are one or more BEFORE triggers that use this value via
100772         ** a new.* reference in a trigger program.
100773         */
100774         testcase( i==31 );
100775         testcase( i==32 );
100776         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100777         sqlite3ColumnDefault(v, pTab, i, regNew+i);
100778       }
100779     }
100780   }
100781
100782   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
100783   ** verified. One could argue that this is wrong.
100784   */
100785   if( tmask&TRIGGER_BEFORE ){
100786     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
100787     sqlite3TableAffinityStr(v, pTab);
100788     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100789         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
100790
100791     /* The row-trigger may have deleted the row being updated. In this
100792     ** case, jump to the next row. No updates or AFTER triggers are 
100793     ** required. This behaviour - what happens when the row being updated
100794     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
100795     ** documentation.
100796     */
100797     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100798
100799     /* If it did not delete it, the row-trigger may still have modified 
100800     ** some of the columns of the row being updated. Load the values for 
100801     ** all columns not modified by the update statement into their 
100802     ** registers in case this has happened.
100803     */
100804     for(i=0; i<pTab->nCol; i++){
100805       if( aXRef[i]<0 && i!=pTab->iPKey ){
100806         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100807         sqlite3ColumnDefault(v, pTab, i, regNew+i);
100808       }
100809     }
100810   }
100811
100812   if( !isView ){
100813     int j1;                       /* Address of jump instruction */
100814
100815     /* Do constraint checks. */
100816     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100817         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100818
100819     /* Do FK constraint checks. */
100820     if( hasFK ){
100821       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
100822     }
100823
100824     /* Delete the index entries associated with the current record.  */
100825     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100826     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100827   
100828     /* If changing the record number, delete the old record.  */
100829     if( hasFK || chngRowid ){
100830       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
100831     }
100832     sqlite3VdbeJumpHere(v, j1);
100833
100834     if( hasFK ){
100835       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
100836     }
100837   
100838     /* Insert the new index entries and the new record. */
100839     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100840
100841     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100842     ** handle rows (possibly in other tables) that refer via a foreign key
100843     ** to the row just updated. */ 
100844     if( hasFK ){
100845       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
100846     }
100847   }
100848
100849   /* Increment the row counter 
100850   */
100851   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
100852     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100853   }
100854
100855   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
100856       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100857
100858   /* Repeat the above with the next record to be updated, until
100859   ** all record selected by the WHERE clause have been updated.
100860   */
100861   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
100862   sqlite3VdbeJumpHere(v, addr);
100863
100864   /* Close all tables */
100865   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100866     assert( aRegIdx );
100867     if( openAll || aRegIdx[i]>0 ){
100868       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100869     }
100870   }
100871   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
100872
100873   /* Update the sqlite_sequence table by storing the content of the
100874   ** maximum rowid counter values recorded while inserting into
100875   ** autoincrement tables.
100876   */
100877   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100878     sqlite3AutoincrementEnd(pParse);
100879   }
100880
100881   /*
100882   ** Return the number of rows that were changed. If this routine is 
100883   ** generating code because of a call to sqlite3NestedParse(), do not
100884   ** invoke the callback function.
100885   */
100886   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
100887     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100888     sqlite3VdbeSetNumCols(v, 1);
100889     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
100890   }
100891
100892 update_cleanup:
100893   sqlite3AuthContextPop(&sContext);
100894   sqlite3DbFree(db, aRegIdx);
100895   sqlite3DbFree(db, aXRef);
100896   sqlite3SrcListDelete(db, pTabList);
100897   sqlite3ExprListDelete(db, pChanges);
100898   sqlite3ExprDelete(db, pWhere);
100899   return;
100900 }
100901 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100902 ** thely may interfere with compilation of other functions in this file
100903 ** (or in another file, if this file becomes part of the amalgamation).  */
100904 #ifdef isView
100905  #undef isView
100906 #endif
100907 #ifdef pTrigger
100908  #undef pTrigger
100909 #endif
100910
100911 #ifndef SQLITE_OMIT_VIRTUALTABLE
100912 /*
100913 ** Generate code for an UPDATE of a virtual table.
100914 **
100915 ** The strategy is that we create an ephemerial table that contains
100916 ** for each row to be changed:
100917 **
100918 **   (A)  The original rowid of that row.
100919 **   (B)  The revised rowid for the row. (note1)
100920 **   (C)  The content of every column in the row.
100921 **
100922 ** Then we loop over this ephemeral table and for each row in
100923 ** the ephermeral table call VUpdate.
100924 **
100925 ** When finished, drop the ephemeral table.
100926 **
100927 ** (note1) Actually, if we know in advance that (A) is always the same
100928 ** as (B) we only store (A), then duplicate (A) when pulling
100929 ** it out of the ephemeral table before calling VUpdate.
100930 */
100931 static void updateVirtualTable(
100932   Parse *pParse,       /* The parsing context */
100933   SrcList *pSrc,       /* The virtual table to be modified */
100934   Table *pTab,         /* The virtual table */
100935   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100936   Expr *pRowid,        /* Expression used to recompute the rowid */
100937   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100938   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100939   int onError          /* ON CONFLICT strategy */
100940 ){
100941   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
100942   ExprList *pEList = 0;     /* The result set of the SELECT statement */
100943   Select *pSelect = 0;      /* The SELECT statement */
100944   Expr *pExpr;              /* Temporary expression */
100945   int ephemTab;             /* Table holding the result of the SELECT */
100946   int i;                    /* Loop counter */
100947   int addr;                 /* Address of top of loop */
100948   int iReg;                 /* First register in set passed to OP_VUpdate */
100949   sqlite3 *db = pParse->db; /* Database connection */
100950   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
100951   SelectDest dest;
100952
100953   /* Construct the SELECT statement that will find the new values for
100954   ** all updated rows. 
100955   */
100956   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
100957   if( pRowid ){
100958     pEList = sqlite3ExprListAppend(pParse, pEList,
100959                                    sqlite3ExprDup(db, pRowid, 0));
100960   }
100961   assert( pTab->iPKey<0 );
100962   for(i=0; i<pTab->nCol; i++){
100963     if( aXRef[i]>=0 ){
100964       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
100965     }else{
100966       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
100967     }
100968     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
100969   }
100970   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
100971   
100972   /* Create the ephemeral table into which the update results will
100973   ** be stored.
100974   */
100975   assert( v );
100976   ephemTab = pParse->nTab++;
100977   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
100978   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100979
100980   /* fill the ephemeral table 
100981   */
100982   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
100983   sqlite3Select(pParse, pSelect, &dest);
100984
100985   /* Generate code to scan the ephemeral table and call VUpdate. */
100986   iReg = ++pParse->nMem;
100987   pParse->nMem += pTab->nCol+1;
100988   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
100989   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
100990   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
100991   for(i=0; i<pTab->nCol; i++){
100992     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
100993   }
100994   sqlite3VtabMakeWritable(pParse, pTab);
100995   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
100996   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100997   sqlite3MayAbort(pParse);
100998   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
100999   sqlite3VdbeJumpHere(v, addr);
101000   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
101001
101002   /* Cleanup */
101003   sqlite3SelectDelete(db, pSelect);  
101004 }
101005 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101006
101007 /************** End of update.c **********************************************/
101008 /************** Begin file vacuum.c ******************************************/
101009 /*
101010 ** 2003 April 6
101011 **
101012 ** The author disclaims copyright to this source code.  In place of
101013 ** a legal notice, here is a blessing:
101014 **
101015 **    May you do good and not evil.
101016 **    May you find forgiveness for yourself and forgive others.
101017 **    May you share freely, never taking more than you give.
101018 **
101019 *************************************************************************
101020 ** This file contains code used to implement the VACUUM command.
101021 **
101022 ** Most of the code in this file may be omitted by defining the
101023 ** SQLITE_OMIT_VACUUM macro.
101024 */
101025
101026 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101027 /*
101028 ** Finalize a prepared statement.  If there was an error, store the
101029 ** text of the error message in *pzErrMsg.  Return the result code.
101030 */
101031 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
101032   int rc;
101033   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
101034   if( rc ){
101035     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101036   }
101037   return rc;
101038 }
101039
101040 /*
101041 ** Execute zSql on database db. Return an error code.
101042 */
101043 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101044   sqlite3_stmt *pStmt;
101045   VVA_ONLY( int rc; )
101046   if( !zSql ){
101047     return SQLITE_NOMEM;
101048   }
101049   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
101050     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101051     return sqlite3_errcode(db);
101052   }
101053   VVA_ONLY( rc = ) sqlite3_step(pStmt);
101054   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
101055   return vacuumFinalize(db, pStmt, pzErrMsg);
101056 }
101057
101058 /*
101059 ** Execute zSql on database db. The statement returns exactly
101060 ** one column. Execute this as SQL on the same database.
101061 */
101062 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101063   sqlite3_stmt *pStmt;
101064   int rc;
101065
101066   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
101067   if( rc!=SQLITE_OK ) return rc;
101068
101069   while( SQLITE_ROW==sqlite3_step(pStmt) ){
101070     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
101071     if( rc!=SQLITE_OK ){
101072       vacuumFinalize(db, pStmt, pzErrMsg);
101073       return rc;
101074     }
101075   }
101076
101077   return vacuumFinalize(db, pStmt, pzErrMsg);
101078 }
101079
101080 /*
101081 ** The non-standard VACUUM command is used to clean up the database,
101082 ** collapse free space, etc.  It is modelled after the VACUUM command
101083 ** in PostgreSQL.
101084 **
101085 ** In version 1.0.x of SQLite, the VACUUM command would call
101086 ** gdbm_reorganize() on all the database tables.  But beginning
101087 ** with 2.0.0, SQLite no longer uses GDBM so this command has
101088 ** become a no-op.
101089 */
101090 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
101091   Vdbe *v = sqlite3GetVdbe(pParse);
101092   if( v ){
101093     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
101094     sqlite3VdbeUsesBtree(v, 0);
101095   }
101096   return;
101097 }
101098
101099 /*
101100 ** This routine implements the OP_Vacuum opcode of the VDBE.
101101 */
101102 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
101103   int rc = SQLITE_OK;     /* Return code from service routines */
101104   Btree *pMain;           /* The database being vacuumed */
101105   Btree *pTemp;           /* The temporary database we vacuum into */
101106   char *zSql = 0;         /* SQL statements */
101107   int saved_flags;        /* Saved value of the db->flags */
101108   int saved_nChange;      /* Saved value of db->nChange */
101109   int saved_nTotalChange; /* Saved value of db->nTotalChange */
101110   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
101111   Db *pDb = 0;            /* Database to detach at end of vacuum */
101112   int isMemDb;            /* True if vacuuming a :memory: database */
101113   int nRes;               /* Bytes of reserved space at the end of each page */
101114   int nDb;                /* Number of attached databases */
101115
101116   if( !db->autoCommit ){
101117     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
101118     return SQLITE_ERROR;
101119   }
101120   if( db->activeVdbeCnt>1 ){
101121     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
101122     return SQLITE_ERROR;
101123   }
101124
101125   /* Save the current value of the database flags so that it can be 
101126   ** restored before returning. Then set the writable-schema flag, and
101127   ** disable CHECK and foreign key constraints.  */
101128   saved_flags = db->flags;
101129   saved_nChange = db->nChange;
101130   saved_nTotalChange = db->nTotalChange;
101131   saved_xTrace = db->xTrace;
101132   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
101133   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
101134   db->xTrace = 0;
101135
101136   pMain = db->aDb[0].pBt;
101137   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
101138
101139   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
101140   ** can be set to 'off' for this file, as it is not recovered if a crash
101141   ** occurs anyway. The integrity of the database is maintained by a
101142   ** (possibly synchronous) transaction opened on the main database before
101143   ** sqlite3BtreeCopyFile() is called.
101144   **
101145   ** An optimisation would be to use a non-journaled pager.
101146   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
101147   ** that actually made the VACUUM run slower.  Very little journalling
101148   ** actually occurs when doing a vacuum since the vacuum_db is initially
101149   ** empty.  Only the journal header is written.  Apparently it takes more
101150   ** time to parse and run the PRAGMA to turn journalling off than it does
101151   ** to write the journal header file.
101152   */
101153   nDb = db->nDb;
101154   if( sqlite3TempInMemory(db) ){
101155     zSql = "ATTACH ':memory:' AS vacuum_db;";
101156   }else{
101157     zSql = "ATTACH '' AS vacuum_db;";
101158   }
101159   rc = execSql(db, pzErrMsg, zSql);
101160   if( db->nDb>nDb ){
101161     pDb = &db->aDb[db->nDb-1];
101162     assert( strcmp(pDb->zName,"vacuum_db")==0 );
101163   }
101164   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101165   pTemp = db->aDb[db->nDb-1].pBt;
101166
101167   /* The call to execSql() to attach the temp database has left the file
101168   ** locked (as there was more than one active statement when the transaction
101169   ** to read the schema was concluded. Unlock it here so that this doesn't
101170   ** cause problems for the call to BtreeSetPageSize() below.  */
101171   sqlite3BtreeCommit(pTemp);
101172
101173   nRes = sqlite3BtreeGetReserve(pMain);
101174
101175   /* A VACUUM cannot change the pagesize of an encrypted database. */
101176 #ifdef SQLITE_HAS_CODEC
101177   if( db->nextPagesize ){
101178     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
101179     int nKey;
101180     char *zKey;
101181     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
101182     if( nKey ) db->nextPagesize = 0;
101183   }
101184 #endif
101185
101186   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
101187   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101188
101189   /* Begin a transaction and take an exclusive lock on the main database
101190   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
101191   ** to ensure that we do not try to change the page-size on a WAL database.
101192   */
101193   rc = execSql(db, pzErrMsg, "BEGIN;");
101194   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101195   rc = sqlite3BtreeBeginTrans(pMain, 2);
101196   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101197
101198   /* Do not attempt to change the page size for a WAL database */
101199   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
101200                                                ==PAGER_JOURNALMODE_WAL ){
101201     db->nextPagesize = 0;
101202   }
101203
101204   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
101205    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
101206    || NEVER(db->mallocFailed)
101207   ){
101208     rc = SQLITE_NOMEM;
101209     goto end_of_vacuum;
101210   }
101211
101212 #ifndef SQLITE_OMIT_AUTOVACUUM
101213   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
101214                                            sqlite3BtreeGetAutoVacuum(pMain));
101215 #endif
101216
101217   /* Query the schema of the main database. Create a mirror schema
101218   ** in the temporary database.
101219   */
101220   rc = execExecSql(db, pzErrMsg,
101221       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
101222       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
101223       "   AND rootpage>0"
101224   );
101225   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101226   rc = execExecSql(db, pzErrMsg,
101227       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
101228       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
101229   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101230   rc = execExecSql(db, pzErrMsg,
101231       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
101232       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
101233   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101234
101235   /* Loop through the tables in the main database. For each, do
101236   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
101237   ** the contents to the temporary database.
101238   */
101239   rc = execExecSql(db, pzErrMsg,
101240       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101241       "|| ' SELECT * FROM main.' || quote(name) || ';'"
101242       "FROM main.sqlite_master "
101243       "WHERE type = 'table' AND name!='sqlite_sequence' "
101244       "  AND rootpage>0"
101245   );
101246   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101247
101248   /* Copy over the sequence table
101249   */
101250   rc = execExecSql(db, pzErrMsg,
101251       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101252       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
101253   );
101254   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101255   rc = execExecSql(db, pzErrMsg,
101256       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101257       "|| ' SELECT * FROM main.' || quote(name) || ';' "
101258       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
101259   );
101260   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101261
101262
101263   /* Copy the triggers, views, and virtual tables from the main database
101264   ** over to the temporary database.  None of these objects has any
101265   ** associated storage, so all we have to do is copy their entries
101266   ** from the SQLITE_MASTER table.
101267   */
101268   rc = execSql(db, pzErrMsg,
101269       "INSERT INTO vacuum_db.sqlite_master "
101270       "  SELECT type, name, tbl_name, rootpage, sql"
101271       "    FROM main.sqlite_master"
101272       "   WHERE type='view' OR type='trigger'"
101273       "      OR (type='table' AND rootpage=0)"
101274   );
101275   if( rc ) goto end_of_vacuum;
101276
101277   /* At this point, there is a write transaction open on both the 
101278   ** vacuum database and the main database. Assuming no error occurs,
101279   ** both transactions are closed by this block - the main database
101280   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
101281   ** call to sqlite3BtreeCommit().
101282   */
101283   {
101284     u32 meta;
101285     int i;
101286
101287     /* This array determines which meta meta values are preserved in the
101288     ** vacuum.  Even entries are the meta value number and odd entries
101289     ** are an increment to apply to the meta value after the vacuum.
101290     ** The increment is used to increase the schema cookie so that other
101291     ** connections to the same database will know to reread the schema.
101292     */
101293     static const unsigned char aCopy[] = {
101294        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101295        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101296        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101297        BTREE_USER_VERSION,       0,  /* Preserve the user version */
101298     };
101299
101300     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
101301     assert( 1==sqlite3BtreeIsInTrans(pMain) );
101302
101303     /* Copy Btree meta values */
101304     for(i=0; i<ArraySize(aCopy); i+=2){
101305       /* GetMeta() and UpdateMeta() cannot fail in this context because
101306       ** we already have page 1 loaded into cache and marked dirty. */
101307       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
101308       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101309       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
101310     }
101311
101312     rc = sqlite3BtreeCopyFile(pMain, pTemp);
101313     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101314     rc = sqlite3BtreeCommit(pTemp);
101315     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101316 #ifndef SQLITE_OMIT_AUTOVACUUM
101317     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
101318 #endif
101319   }
101320
101321   assert( rc==SQLITE_OK );
101322   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
101323
101324 end_of_vacuum:
101325   /* Restore the original value of db->flags */
101326   db->flags = saved_flags;
101327   db->nChange = saved_nChange;
101328   db->nTotalChange = saved_nTotalChange;
101329   db->xTrace = saved_xTrace;
101330   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
101331
101332   /* Currently there is an SQL level transaction open on the vacuum
101333   ** database. No locks are held on any other files (since the main file
101334   ** was committed at the btree level). So it safe to end the transaction
101335   ** by manually setting the autoCommit flag to true and detaching the
101336   ** vacuum database. The vacuum_db journal file is deleted when the pager
101337   ** is closed by the DETACH.
101338   */
101339   db->autoCommit = 1;
101340
101341   if( pDb ){
101342     sqlite3BtreeClose(pDb->pBt);
101343     pDb->pBt = 0;
101344     pDb->pSchema = 0;
101345   }
101346
101347   /* This both clears the schemas and reduces the size of the db->aDb[]
101348   ** array. */ 
101349   sqlite3ResetAllSchemasOfConnection(db);
101350
101351   return rc;
101352 }
101353
101354 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
101355
101356 /************** End of vacuum.c **********************************************/
101357 /************** Begin file vtab.c ********************************************/
101358 /*
101359 ** 2006 June 10
101360 **
101361 ** The author disclaims copyright to this source code.  In place of
101362 ** a legal notice, here is a blessing:
101363 **
101364 **    May you do good and not evil.
101365 **    May you find forgiveness for yourself and forgive others.
101366 **    May you share freely, never taking more than you give.
101367 **
101368 *************************************************************************
101369 ** This file contains code used to help implement virtual tables.
101370 */
101371 #ifndef SQLITE_OMIT_VIRTUALTABLE
101372
101373 /*
101374 ** Before a virtual table xCreate() or xConnect() method is invoked, the
101375 ** sqlite3.pVtabCtx member variable is set to point to an instance of
101376 ** this struct allocated on the stack. It is used by the implementation of 
101377 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
101378 ** are invoked only from within xCreate and xConnect methods.
101379 */
101380 struct VtabCtx {
101381   VTable *pVTable;    /* The virtual table being constructed */
101382   Table *pTab;        /* The Table object to which the virtual table belongs */
101383 };
101384
101385 /*
101386 ** The actual function that does the work of creating a new module.
101387 ** This function implements the sqlite3_create_module() and
101388 ** sqlite3_create_module_v2() interfaces.
101389 */
101390 static int createModule(
101391   sqlite3 *db,                    /* Database in which module is registered */
101392   const char *zName,              /* Name assigned to this module */
101393   const sqlite3_module *pModule,  /* The definition of the module */
101394   void *pAux,                     /* Context pointer for xCreate/xConnect */
101395   void (*xDestroy)(void *)        /* Module destructor function */
101396 ){
101397   int rc = SQLITE_OK;
101398   int nName;
101399
101400   sqlite3_mutex_enter(db->mutex);
101401   nName = sqlite3Strlen30(zName);
101402   if( sqlite3HashFind(&db->aModule, zName, nName) ){
101403     rc = SQLITE_MISUSE_BKPT;
101404   }else{
101405     Module *pMod;
101406     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
101407     if( pMod ){
101408       Module *pDel;
101409       char *zCopy = (char *)(&pMod[1]);
101410       memcpy(zCopy, zName, nName+1);
101411       pMod->zName = zCopy;
101412       pMod->pModule = pModule;
101413       pMod->pAux = pAux;
101414       pMod->xDestroy = xDestroy;
101415       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
101416       assert( pDel==0 || pDel==pMod );
101417       if( pDel ){
101418         db->mallocFailed = 1;
101419         sqlite3DbFree(db, pDel);
101420       }
101421     }
101422   }
101423   rc = sqlite3ApiExit(db, rc);
101424   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
101425
101426   sqlite3_mutex_leave(db->mutex);
101427   return rc;
101428 }
101429
101430
101431 /*
101432 ** External API function used to create a new virtual-table module.
101433 */
101434 SQLITE_API int sqlite3_create_module(
101435   sqlite3 *db,                    /* Database in which module is registered */
101436   const char *zName,              /* Name assigned to this module */
101437   const sqlite3_module *pModule,  /* The definition of the module */
101438   void *pAux                      /* Context pointer for xCreate/xConnect */
101439 ){
101440   return createModule(db, zName, pModule, pAux, 0);
101441 }
101442
101443 /*
101444 ** External API function used to create a new virtual-table module.
101445 */
101446 SQLITE_API int sqlite3_create_module_v2(
101447   sqlite3 *db,                    /* Database in which module is registered */
101448   const char *zName,              /* Name assigned to this module */
101449   const sqlite3_module *pModule,  /* The definition of the module */
101450   void *pAux,                     /* Context pointer for xCreate/xConnect */
101451   void (*xDestroy)(void *)        /* Module destructor function */
101452 ){
101453   return createModule(db, zName, pModule, pAux, xDestroy);
101454 }
101455
101456 /*
101457 ** Lock the virtual table so that it cannot be disconnected.
101458 ** Locks nest.  Every lock should have a corresponding unlock.
101459 ** If an unlock is omitted, resources leaks will occur.  
101460 **
101461 ** If a disconnect is attempted while a virtual table is locked,
101462 ** the disconnect is deferred until all locks have been removed.
101463 */
101464 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
101465   pVTab->nRef++;
101466 }
101467
101468
101469 /*
101470 ** pTab is a pointer to a Table structure representing a virtual-table.
101471 ** Return a pointer to the VTable object used by connection db to access 
101472 ** this virtual-table, if one has been created, or NULL otherwise.
101473 */
101474 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
101475   VTable *pVtab;
101476   assert( IsVirtual(pTab) );
101477   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101478   return pVtab;
101479 }
101480
101481 /*
101482 ** Decrement the ref-count on a virtual table object. When the ref-count
101483 ** reaches zero, call the xDisconnect() method to delete the object.
101484 */
101485 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
101486   sqlite3 *db = pVTab->db;
101487
101488   assert( db );
101489   assert( pVTab->nRef>0 );
101490   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
101491
101492   pVTab->nRef--;
101493   if( pVTab->nRef==0 ){
101494     sqlite3_vtab *p = pVTab->pVtab;
101495     if( p ){
101496       p->pModule->xDisconnect(p);
101497     }
101498     sqlite3DbFree(db, pVTab);
101499   }
101500 }
101501
101502 /*
101503 ** Table p is a virtual table. This function moves all elements in the
101504 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
101505 ** database connections to be disconnected at the next opportunity. 
101506 ** Except, if argument db is not NULL, then the entry associated with
101507 ** connection db is left in the p->pVTable list.
101508 */
101509 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
101510   VTable *pRet = 0;
101511   VTable *pVTable = p->pVTable;
101512   p->pVTable = 0;
101513
101514   /* Assert that the mutex (if any) associated with the BtShared database 
101515   ** that contains table p is held by the caller. See header comments 
101516   ** above function sqlite3VtabUnlockList() for an explanation of why
101517   ** this makes it safe to access the sqlite3.pDisconnect list of any
101518   ** database connection that may have an entry in the p->pVTable list.
101519   */
101520   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
101521
101522   while( pVTable ){
101523     sqlite3 *db2 = pVTable->db;
101524     VTable *pNext = pVTable->pNext;
101525     assert( db2 );
101526     if( db2==db ){
101527       pRet = pVTable;
101528       p->pVTable = pRet;
101529       pRet->pNext = 0;
101530     }else{
101531       pVTable->pNext = db2->pDisconnect;
101532       db2->pDisconnect = pVTable;
101533     }
101534     pVTable = pNext;
101535   }
101536
101537   assert( !db || pRet );
101538   return pRet;
101539 }
101540
101541 /*
101542 ** Table *p is a virtual table. This function removes the VTable object
101543 ** for table *p associated with database connection db from the linked
101544 ** list in p->pVTab. It also decrements the VTable ref count. This is
101545 ** used when closing database connection db to free all of its VTable
101546 ** objects without disturbing the rest of the Schema object (which may
101547 ** be being used by other shared-cache connections).
101548 */
101549 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
101550   VTable **ppVTab;
101551
101552   assert( IsVirtual(p) );
101553   assert( sqlite3BtreeHoldsAllMutexes(db) );
101554   assert( sqlite3_mutex_held(db->mutex) );
101555
101556   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
101557     if( (*ppVTab)->db==db  ){
101558       VTable *pVTab = *ppVTab;
101559       *ppVTab = pVTab->pNext;
101560       sqlite3VtabUnlock(pVTab);
101561       break;
101562     }
101563   }
101564 }
101565
101566
101567 /*
101568 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
101569 **
101570 ** This function may only be called when the mutexes associated with all
101571 ** shared b-tree databases opened using connection db are held by the 
101572 ** caller. This is done to protect the sqlite3.pDisconnect list. The
101573 ** sqlite3.pDisconnect list is accessed only as follows:
101574 **
101575 **   1) By this function. In this case, all BtShared mutexes and the mutex
101576 **      associated with the database handle itself must be held.
101577 **
101578 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
101579 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
101580 **      associated with the database the virtual table is stored in is held
101581 **      or, if the virtual table is stored in a non-sharable database, then
101582 **      the database handle mutex is held.
101583 **
101584 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
101585 ** by multiple threads. It is thread-safe.
101586 */
101587 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
101588   VTable *p = db->pDisconnect;
101589   db->pDisconnect = 0;
101590
101591   assert( sqlite3BtreeHoldsAllMutexes(db) );
101592   assert( sqlite3_mutex_held(db->mutex) );
101593
101594   if( p ){
101595     sqlite3ExpirePreparedStatements(db);
101596     do {
101597       VTable *pNext = p->pNext;
101598       sqlite3VtabUnlock(p);
101599       p = pNext;
101600     }while( p );
101601   }
101602 }
101603
101604 /*
101605 ** Clear any and all virtual-table information from the Table record.
101606 ** This routine is called, for example, just before deleting the Table
101607 ** record.
101608 **
101609 ** Since it is a virtual-table, the Table structure contains a pointer
101610 ** to the head of a linked list of VTable structures. Each VTable 
101611 ** structure is associated with a single sqlite3* user of the schema.
101612 ** The reference count of the VTable structure associated with database 
101613 ** connection db is decremented immediately (which may lead to the 
101614 ** structure being xDisconnected and free). Any other VTable structures
101615 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
101616 ** database connection.
101617 */
101618 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
101619   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
101620   if( p->azModuleArg ){
101621     int i;
101622     for(i=0; i<p->nModuleArg; i++){
101623       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
101624     }
101625     sqlite3DbFree(db, p->azModuleArg);
101626   }
101627 }
101628
101629 /*
101630 ** Add a new module argument to pTable->azModuleArg[].
101631 ** The string is not copied - the pointer is stored.  The
101632 ** string will be freed automatically when the table is
101633 ** deleted.
101634 */
101635 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
101636   int i = pTable->nModuleArg++;
101637   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
101638   char **azModuleArg;
101639   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
101640   if( azModuleArg==0 ){
101641     int j;
101642     for(j=0; j<i; j++){
101643       sqlite3DbFree(db, pTable->azModuleArg[j]);
101644     }
101645     sqlite3DbFree(db, zArg);
101646     sqlite3DbFree(db, pTable->azModuleArg);
101647     pTable->nModuleArg = 0;
101648   }else{
101649     azModuleArg[i] = zArg;
101650     azModuleArg[i+1] = 0;
101651   }
101652   pTable->azModuleArg = azModuleArg;
101653 }
101654
101655 /*
101656 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
101657 ** statement.  The module name has been parsed, but the optional list
101658 ** of parameters that follow the module name are still pending.
101659 */
101660 SQLITE_PRIVATE void sqlite3VtabBeginParse(
101661   Parse *pParse,        /* Parsing context */
101662   Token *pName1,        /* Name of new table, or database name */
101663   Token *pName2,        /* Name of new table or NULL */
101664   Token *pModuleName,   /* Name of the module for the virtual table */
101665   int ifNotExists       /* No error if the table already exists */
101666 ){
101667   int iDb;              /* The database the table is being created in */
101668   Table *pTable;        /* The new virtual table */
101669   sqlite3 *db;          /* Database connection */
101670
101671   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
101672   pTable = pParse->pNewTable;
101673   if( pTable==0 ) return;
101674   assert( 0==pTable->pIndex );
101675
101676   db = pParse->db;
101677   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
101678   assert( iDb>=0 );
101679
101680   pTable->tabFlags |= TF_Virtual;
101681   pTable->nModuleArg = 0;
101682   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
101683   addModuleArgument(db, pTable, 0);
101684   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
101685   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
101686
101687 #ifndef SQLITE_OMIT_AUTHORIZATION
101688   /* Creating a virtual table invokes the authorization callback twice.
101689   ** The first invocation, to obtain permission to INSERT a row into the
101690   ** sqlite_master table, has already been made by sqlite3StartTable().
101691   ** The second call, to obtain permission to create the table, is made now.
101692   */
101693   if( pTable->azModuleArg ){
101694     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
101695             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
101696   }
101697 #endif
101698 }
101699
101700 /*
101701 ** This routine takes the module argument that has been accumulating
101702 ** in pParse->zArg[] and appends it to the list of arguments on the
101703 ** virtual table currently under construction in pParse->pTable.
101704 */
101705 static void addArgumentToVtab(Parse *pParse){
101706   if( pParse->sArg.z && pParse->pNewTable ){
101707     const char *z = (const char*)pParse->sArg.z;
101708     int n = pParse->sArg.n;
101709     sqlite3 *db = pParse->db;
101710     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
101711   }
101712 }
101713
101714 /*
101715 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
101716 ** has been completely parsed.
101717 */
101718 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
101719   Table *pTab = pParse->pNewTable;  /* The table being constructed */
101720   sqlite3 *db = pParse->db;         /* The database connection */
101721
101722   if( pTab==0 ) return;
101723   addArgumentToVtab(pParse);
101724   pParse->sArg.z = 0;
101725   if( pTab->nModuleArg<1 ) return;
101726   
101727   /* If the CREATE VIRTUAL TABLE statement is being entered for the
101728   ** first time (in other words if the virtual table is actually being
101729   ** created now instead of just being read out of sqlite_master) then
101730   ** do additional initialization work and store the statement text
101731   ** in the sqlite_master table.
101732   */
101733   if( !db->init.busy ){
101734     char *zStmt;
101735     char *zWhere;
101736     int iDb;
101737     Vdbe *v;
101738
101739     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
101740     if( pEnd ){
101741       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
101742     }
101743     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
101744
101745     /* A slot for the record has already been allocated in the 
101746     ** SQLITE_MASTER table.  We just need to update that slot with all
101747     ** the information we've collected.  
101748     **
101749     ** The VM register number pParse->regRowid holds the rowid of an
101750     ** entry in the sqlite_master table tht was created for this vtab
101751     ** by sqlite3StartTable().
101752     */
101753     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101754     sqlite3NestedParse(pParse,
101755       "UPDATE %Q.%s "
101756          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
101757        "WHERE rowid=#%d",
101758       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
101759       pTab->zName,
101760       pTab->zName,
101761       zStmt,
101762       pParse->regRowid
101763     );
101764     sqlite3DbFree(db, zStmt);
101765     v = sqlite3GetVdbe(pParse);
101766     sqlite3ChangeCookie(pParse, iDb);
101767
101768     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
101769     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
101770     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
101771     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
101772                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
101773   }
101774
101775   /* If we are rereading the sqlite_master table create the in-memory
101776   ** record of the table. The xConnect() method is not called until
101777   ** the first time the virtual table is used in an SQL statement. This
101778   ** allows a schema that contains virtual tables to be loaded before
101779   ** the required virtual table implementations are registered.  */
101780   else {
101781     Table *pOld;
101782     Schema *pSchema = pTab->pSchema;
101783     const char *zName = pTab->zName;
101784     int nName = sqlite3Strlen30(zName);
101785     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
101786     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
101787     if( pOld ){
101788       db->mallocFailed = 1;
101789       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
101790       return;
101791     }
101792     pParse->pNewTable = 0;
101793   }
101794 }
101795
101796 /*
101797 ** The parser calls this routine when it sees the first token
101798 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
101799 */
101800 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
101801   addArgumentToVtab(pParse);
101802   pParse->sArg.z = 0;
101803   pParse->sArg.n = 0;
101804 }
101805
101806 /*
101807 ** The parser calls this routine for each token after the first token
101808 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101809 */
101810 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
101811   Token *pArg = &pParse->sArg;
101812   if( pArg->z==0 ){
101813     pArg->z = p->z;
101814     pArg->n = p->n;
101815   }else{
101816     assert(pArg->z < p->z);
101817     pArg->n = (int)(&p->z[p->n] - pArg->z);
101818   }
101819 }
101820
101821 /*
101822 ** Invoke a virtual table constructor (either xCreate or xConnect). The
101823 ** pointer to the function to invoke is passed as the fourth parameter
101824 ** to this procedure.
101825 */
101826 static int vtabCallConstructor(
101827   sqlite3 *db, 
101828   Table *pTab,
101829   Module *pMod,
101830   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
101831   char **pzErr
101832 ){
101833   VtabCtx sCtx, *pPriorCtx;
101834   VTable *pVTable;
101835   int rc;
101836   const char *const*azArg = (const char *const*)pTab->azModuleArg;
101837   int nArg = pTab->nModuleArg;
101838   char *zErr = 0;
101839   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
101840   int iDb;
101841
101842   if( !zModuleName ){
101843     return SQLITE_NOMEM;
101844   }
101845
101846   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
101847   if( !pVTable ){
101848     sqlite3DbFree(db, zModuleName);
101849     return SQLITE_NOMEM;
101850   }
101851   pVTable->db = db;
101852   pVTable->pMod = pMod;
101853
101854   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101855   pTab->azModuleArg[1] = db->aDb[iDb].zName;
101856
101857   /* Invoke the virtual table constructor */
101858   assert( &db->pVtabCtx );
101859   assert( xConstruct );
101860   sCtx.pTab = pTab;
101861   sCtx.pVTable = pVTable;
101862   pPriorCtx = db->pVtabCtx;
101863   db->pVtabCtx = &sCtx;
101864   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101865   db->pVtabCtx = pPriorCtx;
101866   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
101867
101868   if( SQLITE_OK!=rc ){
101869     if( zErr==0 ){
101870       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101871     }else {
101872       *pzErr = sqlite3MPrintf(db, "%s", zErr);
101873       sqlite3_free(zErr);
101874     }
101875     sqlite3DbFree(db, pVTable);
101876   }else if( ALWAYS(pVTable->pVtab) ){
101877     /* Justification of ALWAYS():  A correct vtab constructor must allocate
101878     ** the sqlite3_vtab object if successful.  */
101879     pVTable->pVtab->pModule = pMod->pModule;
101880     pVTable->nRef = 1;
101881     if( sCtx.pTab ){
101882       const char *zFormat = "vtable constructor did not declare schema: %s";
101883       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
101884       sqlite3VtabUnlock(pVTable);
101885       rc = SQLITE_ERROR;
101886     }else{
101887       int iCol;
101888       /* If everything went according to plan, link the new VTable structure
101889       ** into the linked list headed by pTab->pVTable. Then loop through the 
101890       ** columns of the table to see if any of them contain the token "hidden".
101891       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
101892       ** the type string.  */
101893       pVTable->pNext = pTab->pVTable;
101894       pTab->pVTable = pVTable;
101895
101896       for(iCol=0; iCol<pTab->nCol; iCol++){
101897         char *zType = pTab->aCol[iCol].zType;
101898         int nType;
101899         int i = 0;
101900         if( !zType ) continue;
101901         nType = sqlite3Strlen30(zType);
101902         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101903           for(i=0; i<nType; i++){
101904             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
101905              && (zType[i+7]=='\0' || zType[i+7]==' ')
101906             ){
101907               i++;
101908               break;
101909             }
101910           }
101911         }
101912         if( i<nType ){
101913           int j;
101914           int nDel = 6 + (zType[i+6] ? 1 : 0);
101915           for(j=i; (j+nDel)<=nType; j++){
101916             zType[j] = zType[j+nDel];
101917           }
101918           if( zType[i]=='\0' && i>0 ){
101919             assert(zType[i-1]==' ');
101920             zType[i-1] = '\0';
101921           }
101922           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
101923         }
101924       }
101925     }
101926   }
101927
101928   sqlite3DbFree(db, zModuleName);
101929   return rc;
101930 }
101931
101932 /*
101933 ** This function is invoked by the parser to call the xConnect() method
101934 ** of the virtual table pTab. If an error occurs, an error code is returned 
101935 ** and an error left in pParse.
101936 **
101937 ** This call is a no-op if table pTab is not a virtual table.
101938 */
101939 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
101940   sqlite3 *db = pParse->db;
101941   const char *zMod;
101942   Module *pMod;
101943   int rc;
101944
101945   assert( pTab );
101946   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
101947     return SQLITE_OK;
101948   }
101949
101950   /* Locate the required virtual table module */
101951   zMod = pTab->azModuleArg[0];
101952   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
101953
101954   if( !pMod ){
101955     const char *zModule = pTab->azModuleArg[0];
101956     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
101957     rc = SQLITE_ERROR;
101958   }else{
101959     char *zErr = 0;
101960     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
101961     if( rc!=SQLITE_OK ){
101962       sqlite3ErrorMsg(pParse, "%s", zErr);
101963     }
101964     sqlite3DbFree(db, zErr);
101965   }
101966
101967   return rc;
101968 }
101969 /*
101970 ** Grow the db->aVTrans[] array so that there is room for at least one
101971 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
101972 */
101973 static int growVTrans(sqlite3 *db){
101974   const int ARRAY_INCR = 5;
101975
101976   /* Grow the sqlite3.aVTrans array if required */
101977   if( (db->nVTrans%ARRAY_INCR)==0 ){
101978     VTable **aVTrans;
101979     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
101980     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
101981     if( !aVTrans ){
101982       return SQLITE_NOMEM;
101983     }
101984     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
101985     db->aVTrans = aVTrans;
101986   }
101987
101988   return SQLITE_OK;
101989 }
101990
101991 /*
101992 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
101993 ** have already been reserved using growVTrans().
101994 */
101995 static void addToVTrans(sqlite3 *db, VTable *pVTab){
101996   /* Add pVtab to the end of sqlite3.aVTrans */
101997   db->aVTrans[db->nVTrans++] = pVTab;
101998   sqlite3VtabLock(pVTab);
101999 }
102000
102001 /*
102002 ** This function is invoked by the vdbe to call the xCreate method
102003 ** of the virtual table named zTab in database iDb. 
102004 **
102005 ** If an error occurs, *pzErr is set to point an an English language
102006 ** description of the error and an SQLITE_XXX error code is returned.
102007 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
102008 */
102009 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
102010   int rc = SQLITE_OK;
102011   Table *pTab;
102012   Module *pMod;
102013   const char *zMod;
102014
102015   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102016   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
102017
102018   /* Locate the required virtual table module */
102019   zMod = pTab->azModuleArg[0];
102020   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102021
102022   /* If the module has been registered and includes a Create method, 
102023   ** invoke it now. If the module has not been registered, return an 
102024   ** error. Otherwise, do nothing.
102025   */
102026   if( !pMod ){
102027     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
102028     rc = SQLITE_ERROR;
102029   }else{
102030     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
102031   }
102032
102033   /* Justification of ALWAYS():  The xConstructor method is required to
102034   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
102035   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
102036     rc = growVTrans(db);
102037     if( rc==SQLITE_OK ){
102038       addToVTrans(db, sqlite3GetVTable(db, pTab));
102039     }
102040   }
102041
102042   return rc;
102043 }
102044
102045 /*
102046 ** This function is used to set the schema of a virtual table.  It is only
102047 ** valid to call this function from within the xCreate() or xConnect() of a
102048 ** virtual table module.
102049 */
102050 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
102051   Parse *pParse;
102052
102053   int rc = SQLITE_OK;
102054   Table *pTab;
102055   char *zErr = 0;
102056
102057   sqlite3_mutex_enter(db->mutex);
102058   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
102059     sqlite3Error(db, SQLITE_MISUSE, 0);
102060     sqlite3_mutex_leave(db->mutex);
102061     return SQLITE_MISUSE_BKPT;
102062   }
102063   assert( (pTab->tabFlags & TF_Virtual)!=0 );
102064
102065   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
102066   if( pParse==0 ){
102067     rc = SQLITE_NOMEM;
102068   }else{
102069     pParse->declareVtab = 1;
102070     pParse->db = db;
102071     pParse->nQueryLoop = 1;
102072   
102073     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
102074      && pParse->pNewTable
102075      && !db->mallocFailed
102076      && !pParse->pNewTable->pSelect
102077      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
102078     ){
102079       if( !pTab->aCol ){
102080         pTab->aCol = pParse->pNewTable->aCol;
102081         pTab->nCol = pParse->pNewTable->nCol;
102082         pParse->pNewTable->nCol = 0;
102083         pParse->pNewTable->aCol = 0;
102084       }
102085       db->pVtabCtx->pTab = 0;
102086     }else{
102087       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
102088       sqlite3DbFree(db, zErr);
102089       rc = SQLITE_ERROR;
102090     }
102091     pParse->declareVtab = 0;
102092   
102093     if( pParse->pVdbe ){
102094       sqlite3VdbeFinalize(pParse->pVdbe);
102095     }
102096     sqlite3DeleteTable(db, pParse->pNewTable);
102097     sqlite3StackFree(db, pParse);
102098   }
102099
102100   assert( (rc&0xff)==rc );
102101   rc = sqlite3ApiExit(db, rc);
102102   sqlite3_mutex_leave(db->mutex);
102103   return rc;
102104 }
102105
102106 /*
102107 ** This function is invoked by the vdbe to call the xDestroy method
102108 ** of the virtual table named zTab in database iDb. This occurs
102109 ** when a DROP TABLE is mentioned.
102110 **
102111 ** This call is a no-op if zTab is not a virtual table.
102112 */
102113 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
102114   int rc = SQLITE_OK;
102115   Table *pTab;
102116
102117   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102118   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
102119     VTable *p = vtabDisconnectAll(db, pTab);
102120
102121     assert( rc==SQLITE_OK );
102122     rc = p->pMod->pModule->xDestroy(p->pVtab);
102123
102124     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
102125     if( rc==SQLITE_OK ){
102126       assert( pTab->pVTable==p && p->pNext==0 );
102127       p->pVtab = 0;
102128       pTab->pVTable = 0;
102129       sqlite3VtabUnlock(p);
102130     }
102131   }
102132
102133   return rc;
102134 }
102135
102136 /*
102137 ** This function invokes either the xRollback or xCommit method
102138 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
102139 ** called is identified by the second argument, "offset", which is
102140 ** the offset of the method to call in the sqlite3_module structure.
102141 **
102142 ** The array is cleared after invoking the callbacks. 
102143 */
102144 static void callFinaliser(sqlite3 *db, int offset){
102145   int i;
102146   if( db->aVTrans ){
102147     for(i=0; i<db->nVTrans; i++){
102148       VTable *pVTab = db->aVTrans[i];
102149       sqlite3_vtab *p = pVTab->pVtab;
102150       if( p ){
102151         int (*x)(sqlite3_vtab *);
102152         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
102153         if( x ) x(p);
102154       }
102155       pVTab->iSavepoint = 0;
102156       sqlite3VtabUnlock(pVTab);
102157     }
102158     sqlite3DbFree(db, db->aVTrans);
102159     db->nVTrans = 0;
102160     db->aVTrans = 0;
102161   }
102162 }
102163
102164 /*
102165 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
102166 ** array. Return the error code for the first error that occurs, or
102167 ** SQLITE_OK if all xSync operations are successful.
102168 **
102169 ** Set *pzErrmsg to point to a buffer that should be released using 
102170 ** sqlite3DbFree() containing an error message, if one is available.
102171 */
102172 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
102173   int i;
102174   int rc = SQLITE_OK;
102175   VTable **aVTrans = db->aVTrans;
102176
102177   db->aVTrans = 0;
102178   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102179     int (*x)(sqlite3_vtab *);
102180     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
102181     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
102182       rc = x(pVtab);
102183       sqlite3DbFree(db, *pzErrmsg);
102184       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
102185       sqlite3_free(pVtab->zErrMsg);
102186     }
102187   }
102188   db->aVTrans = aVTrans;
102189   return rc;
102190 }
102191
102192 /*
102193 ** Invoke the xRollback method of all virtual tables in the 
102194 ** sqlite3.aVTrans array. Then clear the array itself.
102195 */
102196 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
102197   callFinaliser(db, offsetof(sqlite3_module,xRollback));
102198   return SQLITE_OK;
102199 }
102200
102201 /*
102202 ** Invoke the xCommit method of all virtual tables in the 
102203 ** sqlite3.aVTrans array. Then clear the array itself.
102204 */
102205 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
102206   callFinaliser(db, offsetof(sqlite3_module,xCommit));
102207   return SQLITE_OK;
102208 }
102209
102210 /*
102211 ** If the virtual table pVtab supports the transaction interface
102212 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
102213 ** not currently open, invoke the xBegin method now.
102214 **
102215 ** If the xBegin call is successful, place the sqlite3_vtab pointer
102216 ** in the sqlite3.aVTrans array.
102217 */
102218 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
102219   int rc = SQLITE_OK;
102220   const sqlite3_module *pModule;
102221
102222   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
102223   ** than zero, then this function is being called from within a
102224   ** virtual module xSync() callback. It is illegal to write to 
102225   ** virtual module tables in this case, so return SQLITE_LOCKED.
102226   */
102227   if( sqlite3VtabInSync(db) ){
102228     return SQLITE_LOCKED;
102229   }
102230   if( !pVTab ){
102231     return SQLITE_OK;
102232   } 
102233   pModule = pVTab->pVtab->pModule;
102234
102235   if( pModule->xBegin ){
102236     int i;
102237
102238     /* If pVtab is already in the aVTrans array, return early */
102239     for(i=0; i<db->nVTrans; i++){
102240       if( db->aVTrans[i]==pVTab ){
102241         return SQLITE_OK;
102242       }
102243     }
102244
102245     /* Invoke the xBegin method. If successful, add the vtab to the 
102246     ** sqlite3.aVTrans[] array. */
102247     rc = growVTrans(db);
102248     if( rc==SQLITE_OK ){
102249       rc = pModule->xBegin(pVTab->pVtab);
102250       if( rc==SQLITE_OK ){
102251         addToVTrans(db, pVTab);
102252       }
102253     }
102254   }
102255   return rc;
102256 }
102257
102258 /*
102259 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
102260 ** virtual tables that currently have an open transaction. Pass iSavepoint
102261 ** as the second argument to the virtual table method invoked.
102262 **
102263 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
102264 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
102265 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
102266 ** an open transaction is invoked.
102267 **
102268 ** If any virtual table method returns an error code other than SQLITE_OK, 
102269 ** processing is abandoned and the error returned to the caller of this
102270 ** function immediately. If all calls to virtual table methods are successful,
102271 ** SQLITE_OK is returned.
102272 */
102273 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
102274   int rc = SQLITE_OK;
102275
102276   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
102277   assert( iSavepoint>=0 );
102278   if( db->aVTrans ){
102279     int i;
102280     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102281       VTable *pVTab = db->aVTrans[i];
102282       const sqlite3_module *pMod = pVTab->pMod->pModule;
102283       if( pVTab->pVtab && pMod->iVersion>=2 ){
102284         int (*xMethod)(sqlite3_vtab *, int);
102285         switch( op ){
102286           case SAVEPOINT_BEGIN:
102287             xMethod = pMod->xSavepoint;
102288             pVTab->iSavepoint = iSavepoint+1;
102289             break;
102290           case SAVEPOINT_ROLLBACK:
102291             xMethod = pMod->xRollbackTo;
102292             break;
102293           default:
102294             xMethod = pMod->xRelease;
102295             break;
102296         }
102297         if( xMethod && pVTab->iSavepoint>iSavepoint ){
102298           rc = xMethod(pVTab->pVtab, iSavepoint);
102299         }
102300       }
102301     }
102302   }
102303   return rc;
102304 }
102305
102306 /*
102307 ** The first parameter (pDef) is a function implementation.  The
102308 ** second parameter (pExpr) is the first argument to this function.
102309 ** If pExpr is a column in a virtual table, then let the virtual
102310 ** table implementation have an opportunity to overload the function.
102311 **
102312 ** This routine is used to allow virtual table implementations to
102313 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
102314 **
102315 ** Return either the pDef argument (indicating no change) or a 
102316 ** new FuncDef structure that is marked as ephemeral using the
102317 ** SQLITE_FUNC_EPHEM flag.
102318 */
102319 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
102320   sqlite3 *db,    /* Database connection for reporting malloc problems */
102321   FuncDef *pDef,  /* Function to possibly overload */
102322   int nArg,       /* Number of arguments to the function */
102323   Expr *pExpr     /* First argument to the function */
102324 ){
102325   Table *pTab;
102326   sqlite3_vtab *pVtab;
102327   sqlite3_module *pMod;
102328   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
102329   void *pArg = 0;
102330   FuncDef *pNew;
102331   int rc = 0;
102332   char *zLowerName;
102333   unsigned char *z;
102334
102335
102336   /* Check to see the left operand is a column in a virtual table */
102337   if( NEVER(pExpr==0) ) return pDef;
102338   if( pExpr->op!=TK_COLUMN ) return pDef;
102339   pTab = pExpr->pTab;
102340   if( NEVER(pTab==0) ) return pDef;
102341   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102342   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
102343   assert( pVtab!=0 );
102344   assert( pVtab->pModule!=0 );
102345   pMod = (sqlite3_module *)pVtab->pModule;
102346   if( pMod->xFindFunction==0 ) return pDef;
102347  
102348   /* Call the xFindFunction method on the virtual table implementation
102349   ** to see if the implementation wants to overload this function 
102350   */
102351   zLowerName = sqlite3DbStrDup(db, pDef->zName);
102352   if( zLowerName ){
102353     for(z=(unsigned char*)zLowerName; *z; z++){
102354       *z = sqlite3UpperToLower[*z];
102355     }
102356     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102357     sqlite3DbFree(db, zLowerName);
102358   }
102359   if( rc==0 ){
102360     return pDef;
102361   }
102362
102363   /* Create a new ephemeral function definition for the overloaded
102364   ** function */
102365   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
102366                              + sqlite3Strlen30(pDef->zName) + 1);
102367   if( pNew==0 ){
102368     return pDef;
102369   }
102370   *pNew = *pDef;
102371   pNew->zName = (char *)&pNew[1];
102372   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
102373   pNew->xFunc = xFunc;
102374   pNew->pUserData = pArg;
102375   pNew->flags |= SQLITE_FUNC_EPHEM;
102376   return pNew;
102377 }
102378
102379 /*
102380 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102381 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
102382 ** array if it is missing.  If pTab is already in the array, this routine
102383 ** is a no-op.
102384 */
102385 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
102386   Parse *pToplevel = sqlite3ParseToplevel(pParse);
102387   int i, n;
102388   Table **apVtabLock;
102389
102390   assert( IsVirtual(pTab) );
102391   for(i=0; i<pToplevel->nVtabLock; i++){
102392     if( pTab==pToplevel->apVtabLock[i] ) return;
102393   }
102394   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102395   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
102396   if( apVtabLock ){
102397     pToplevel->apVtabLock = apVtabLock;
102398     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102399   }else{
102400     pToplevel->db->mallocFailed = 1;
102401   }
102402 }
102403
102404 /*
102405 ** Return the ON CONFLICT resolution mode in effect for the virtual
102406 ** table update operation currently in progress.
102407 **
102408 ** The results of this routine are undefined unless it is called from
102409 ** within an xUpdate method.
102410 */
102411 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
102412   static const unsigned char aMap[] = { 
102413     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
102414   };
102415   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102416   assert( OE_Ignore==4 && OE_Replace==5 );
102417   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102418   return (int)aMap[db->vtabOnConflict-1];
102419 }
102420
102421 /*
102422 ** Call from within the xCreate() or xConnect() methods to provide 
102423 ** the SQLite core with additional information about the behavior
102424 ** of the virtual table being implemented.
102425 */
102426 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
102427   va_list ap;
102428   int rc = SQLITE_OK;
102429
102430   sqlite3_mutex_enter(db->mutex);
102431
102432   va_start(ap, op);
102433   switch( op ){
102434     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
102435       VtabCtx *p = db->pVtabCtx;
102436       if( !p ){
102437         rc = SQLITE_MISUSE_BKPT;
102438       }else{
102439         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102440         p->pVTable->bConstraint = (u8)va_arg(ap, int);
102441       }
102442       break;
102443     }
102444     default:
102445       rc = SQLITE_MISUSE_BKPT;
102446       break;
102447   }
102448   va_end(ap);
102449
102450   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
102451   sqlite3_mutex_leave(db->mutex);
102452   return rc;
102453 }
102454
102455 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102456
102457 /************** End of vtab.c ************************************************/
102458 /************** Begin file where.c *******************************************/
102459 /*
102460 ** 2001 September 15
102461 **
102462 ** The author disclaims copyright to this source code.  In place of
102463 ** a legal notice, here is a blessing:
102464 **
102465 **    May you do good and not evil.
102466 **    May you find forgiveness for yourself and forgive others.
102467 **    May you share freely, never taking more than you give.
102468 **
102469 *************************************************************************
102470 ** This module contains C code that generates VDBE code used to process
102471 ** the WHERE clause of SQL statements.  This module is responsible for
102472 ** generating the code that loops through a table looking for applicable
102473 ** rows.  Indices are selected and used to speed the search when doing
102474 ** so is applicable.  Because this module is responsible for selecting
102475 ** indices, you might also think of this module as the "query optimizer".
102476 */
102477
102478
102479 /*
102480 ** Trace output macros
102481 */
102482 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
102483 /***/ int sqlite3WhereTrace = 0;
102484 #endif
102485 #if defined(SQLITE_DEBUG) \
102486     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
102487 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
102488 #else
102489 # define WHERETRACE(X)
102490 #endif
102491
102492 /* Forward reference
102493 */
102494 typedef struct WhereClause WhereClause;
102495 typedef struct WhereMaskSet WhereMaskSet;
102496 typedef struct WhereOrInfo WhereOrInfo;
102497 typedef struct WhereAndInfo WhereAndInfo;
102498 typedef struct WhereCost WhereCost;
102499
102500 /*
102501 ** The query generator uses an array of instances of this structure to
102502 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102503 ** clause subexpression is separated from the others by AND operators,
102504 ** usually, or sometimes subexpressions separated by OR.
102505 **
102506 ** All WhereTerms are collected into a single WhereClause structure.  
102507 ** The following identity holds:
102508 **
102509 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102510 **
102511 ** When a term is of the form:
102512 **
102513 **              X <op> <expr>
102514 **
102515 ** where X is a column name and <op> is one of certain operators,
102516 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
102517 ** cursor number and column number for X.  WhereTerm.eOperator records
102518 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
102519 ** use of a bitmask encoding for the operator allows us to search
102520 ** quickly for terms that match any of several different operators.
102521 **
102522 ** A WhereTerm might also be two or more subterms connected by OR:
102523 **
102524 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
102525 **
102526 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
102527 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
102528 ** is collected about the
102529 **
102530 ** If a term in the WHERE clause does not match either of the two previous
102531 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
102532 ** to the original subexpression content and wtFlags is set up appropriately
102533 ** but no other fields in the WhereTerm object are meaningful.
102534 **
102535 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
102536 ** but they do so indirectly.  A single WhereMaskSet structure translates
102537 ** cursor number into bits and the translated bit is stored in the prereq
102538 ** fields.  The translation is used in order to maximize the number of
102539 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
102540 ** spread out over the non-negative integers.  For example, the cursor
102541 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
102542 ** translates these sparse cursor numbers into consecutive integers
102543 ** beginning with 0 in order to make the best possible use of the available
102544 ** bits in the Bitmask.  So, in the example above, the cursor numbers
102545 ** would be mapped into integers 0 through 7.
102546 **
102547 ** The number of terms in a join is limited by the number of bits
102548 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
102549 ** is only able to process joins with 64 or fewer tables.
102550 */
102551 typedef struct WhereTerm WhereTerm;
102552 struct WhereTerm {
102553   Expr *pExpr;            /* Pointer to the subexpression that is this term */
102554   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
102555   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
102556   union {
102557     int leftColumn;         /* Column number of X in "X <op> <expr>" */
102558     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102559     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
102560   } u;
102561   u16 eOperator;          /* A WO_xx value describing <op> */
102562   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
102563   u8 nChild;              /* Number of children that must disable us */
102564   WhereClause *pWC;       /* The clause this term is part of */
102565   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
102566   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
102567 };
102568
102569 /*
102570 ** Allowed values of WhereTerm.wtFlags
102571 */
102572 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
102573 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
102574 #define TERM_CODED      0x04   /* This term is already coded */
102575 #define TERM_COPIED     0x08   /* Has a child */
102576 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
102577 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
102578 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
102579 #ifdef SQLITE_ENABLE_STAT3
102580 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
102581 #else
102582 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
102583 #endif
102584
102585 /*
102586 ** An instance of the following structure holds all information about a
102587 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102588 **
102589 ** Explanation of pOuter:  For a WHERE clause of the form
102590 **
102591 **           a AND ((b AND c) OR (d AND e)) AND f
102592 **
102593 ** There are separate WhereClause objects for the whole clause and for
102594 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
102595 ** subclauses points to the WhereClause object for the whole clause.
102596 */
102597 struct WhereClause {
102598   Parse *pParse;           /* The parser context */
102599   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
102600   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
102601   WhereClause *pOuter;     /* Outer conjunction */
102602   u8 op;                   /* Split operator.  TK_AND or TK_OR */
102603   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
102604   int nTerm;               /* Number of terms */
102605   int nSlot;               /* Number of entries in a[] */
102606   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
102607 #if defined(SQLITE_SMALL_STACK)
102608   WhereTerm aStatic[1];    /* Initial static space for a[] */
102609 #else
102610   WhereTerm aStatic[8];    /* Initial static space for a[] */
102611 #endif
102612 };
102613
102614 /*
102615 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
102616 ** a dynamically allocated instance of the following structure.
102617 */
102618 struct WhereOrInfo {
102619   WhereClause wc;          /* Decomposition into subterms */
102620   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
102621 };
102622
102623 /*
102624 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
102625 ** a dynamically allocated instance of the following structure.
102626 */
102627 struct WhereAndInfo {
102628   WhereClause wc;          /* The subexpression broken out */
102629 };
102630
102631 /*
102632 ** An instance of the following structure keeps track of a mapping
102633 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
102634 **
102635 ** The VDBE cursor numbers are small integers contained in 
102636 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
102637 ** clause, the cursor numbers might not begin with 0 and they might
102638 ** contain gaps in the numbering sequence.  But we want to make maximum
102639 ** use of the bits in our bitmasks.  This structure provides a mapping
102640 ** from the sparse cursor numbers into consecutive integers beginning
102641 ** with 0.
102642 **
102643 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
102644 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
102645 **
102646 ** For example, if the WHERE clause expression used these VDBE
102647 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
102648 ** would map those cursor numbers into bits 0 through 5.
102649 **
102650 ** Note that the mapping is not necessarily ordered.  In the example
102651 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
102652 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
102653 ** does not really matter.  What is important is that sparse cursor
102654 ** numbers all get mapped into bit numbers that begin with 0 and contain
102655 ** no gaps.
102656 */
102657 struct WhereMaskSet {
102658   int n;                        /* Number of assigned cursor values */
102659   int ix[BMS];                  /* Cursor assigned to each bit */
102660 };
102661
102662 /*
102663 ** A WhereCost object records a lookup strategy and the estimated
102664 ** cost of pursuing that strategy.
102665 */
102666 struct WhereCost {
102667   WherePlan plan;    /* The lookup strategy */
102668   double rCost;      /* Overall cost of pursuing this search strategy */
102669   Bitmask used;      /* Bitmask of cursors used by this plan */
102670 };
102671
102672 /*
102673 ** Bitmasks for the operators that indices are able to exploit.  An
102674 ** OR-ed combination of these values can be used when searching for
102675 ** terms in the where clause.
102676 */
102677 #define WO_IN     0x001
102678 #define WO_EQ     0x002
102679 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
102680 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
102681 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
102682 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
102683 #define WO_MATCH  0x040
102684 #define WO_ISNULL 0x080
102685 #define WO_OR     0x100       /* Two or more OR-connected terms */
102686 #define WO_AND    0x200       /* Two or more AND-connected terms */
102687 #define WO_NOOP   0x800       /* This term does not restrict search space */
102688
102689 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
102690 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
102691
102692 /*
102693 ** Value for wsFlags returned by bestIndex() and stored in
102694 ** WhereLevel.wsFlags.  These flags determine which search
102695 ** strategies are appropriate.
102696 **
102697 ** The least significant 12 bits is reserved as a mask for WO_ values above.
102698 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
102699 ** But if the table is the right table of a left join, WhereLevel.wsFlags
102700 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
102701 ** the "op" parameter to findTerm when we are resolving equality constraints.
102702 ** ISNULL constraints will then not be used on the right table of a left
102703 ** join.  Tickets #2177 and #2189.
102704 */
102705 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
102706 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
102707 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
102708 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
102709 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
102710 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
102711 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
102712 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
102713 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
102714 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
102715 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
102716 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
102717 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
102718 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
102719 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
102720 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
102721 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
102722 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
102723 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
102724 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
102725 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
102726 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
102727
102728 /*
102729 ** This module contains many separate subroutines that work together to
102730 ** find the best indices to use for accessing a particular table in a query.
102731 ** An instance of the following structure holds context information about the
102732 ** index search so that it can be more easily passed between the various
102733 ** routines.
102734 */
102735 typedef struct WhereBestIdx WhereBestIdx;
102736 struct WhereBestIdx {
102737   Parse *pParse;                  /* Parser context */
102738   WhereClause *pWC;               /* The WHERE clause */
102739   struct SrcList_item *pSrc;      /* The FROM clause term to search */
102740   Bitmask notReady;               /* Mask of cursors not available */
102741   Bitmask notValid;               /* Cursors not available for any purpose */
102742   ExprList *pOrderBy;             /* The ORDER BY clause */
102743   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
102744   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
102745   int i, n;                       /* Which loop is being coded; # of loops */
102746   WhereLevel *aLevel;             /* Info about outer loops */
102747   WhereCost cost;                 /* Lowest cost query plan */
102748 };
102749
102750 /*
102751 ** Return TRUE if the probe cost is less than the baseline cost
102752 */
102753 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
102754   if( pProbe->rCost<pBaseline->rCost ) return 1;
102755   if( pProbe->rCost>pBaseline->rCost ) return 0;
102756   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
102757   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
102758   return 0;
102759 }
102760
102761 /*
102762 ** Initialize a preallocated WhereClause structure.
102763 */
102764 static void whereClauseInit(
102765   WhereClause *pWC,        /* The WhereClause to be initialized */
102766   Parse *pParse,           /* The parsing context */
102767   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
102768   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
102769 ){
102770   pWC->pParse = pParse;
102771   pWC->pMaskSet = pMaskSet;
102772   pWC->pOuter = 0;
102773   pWC->nTerm = 0;
102774   pWC->nSlot = ArraySize(pWC->aStatic);
102775   pWC->a = pWC->aStatic;
102776   pWC->vmask = 0;
102777   pWC->wctrlFlags = wctrlFlags;
102778 }
102779
102780 /* Forward reference */
102781 static void whereClauseClear(WhereClause*);
102782
102783 /*
102784 ** Deallocate all memory associated with a WhereOrInfo object.
102785 */
102786 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
102787   whereClauseClear(&p->wc);
102788   sqlite3DbFree(db, p);
102789 }
102790
102791 /*
102792 ** Deallocate all memory associated with a WhereAndInfo object.
102793 */
102794 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
102795   whereClauseClear(&p->wc);
102796   sqlite3DbFree(db, p);
102797 }
102798
102799 /*
102800 ** Deallocate a WhereClause structure.  The WhereClause structure
102801 ** itself is not freed.  This routine is the inverse of whereClauseInit().
102802 */
102803 static void whereClauseClear(WhereClause *pWC){
102804   int i;
102805   WhereTerm *a;
102806   sqlite3 *db = pWC->pParse->db;
102807   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
102808     if( a->wtFlags & TERM_DYNAMIC ){
102809       sqlite3ExprDelete(db, a->pExpr);
102810     }
102811     if( a->wtFlags & TERM_ORINFO ){
102812       whereOrInfoDelete(db, a->u.pOrInfo);
102813     }else if( a->wtFlags & TERM_ANDINFO ){
102814       whereAndInfoDelete(db, a->u.pAndInfo);
102815     }
102816   }
102817   if( pWC->a!=pWC->aStatic ){
102818     sqlite3DbFree(db, pWC->a);
102819   }
102820 }
102821
102822 /*
102823 ** Add a single new WhereTerm entry to the WhereClause object pWC.
102824 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
102825 ** The index in pWC->a[] of the new WhereTerm is returned on success.
102826 ** 0 is returned if the new WhereTerm could not be added due to a memory
102827 ** allocation error.  The memory allocation failure will be recorded in
102828 ** the db->mallocFailed flag so that higher-level functions can detect it.
102829 **
102830 ** This routine will increase the size of the pWC->a[] array as necessary.
102831 **
102832 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
102833 ** for freeing the expression p is assumed by the WhereClause object pWC.
102834 ** This is true even if this routine fails to allocate a new WhereTerm.
102835 **
102836 ** WARNING:  This routine might reallocate the space used to store
102837 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
102838 ** calling this routine.  Such pointers may be reinitialized by referencing
102839 ** the pWC->a[] array.
102840 */
102841 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
102842   WhereTerm *pTerm;
102843   int idx;
102844   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
102845   if( pWC->nTerm>=pWC->nSlot ){
102846     WhereTerm *pOld = pWC->a;
102847     sqlite3 *db = pWC->pParse->db;
102848     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102849     if( pWC->a==0 ){
102850       if( wtFlags & TERM_DYNAMIC ){
102851         sqlite3ExprDelete(db, p);
102852       }
102853       pWC->a = pOld;
102854       return 0;
102855     }
102856     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102857     if( pOld!=pWC->aStatic ){
102858       sqlite3DbFree(db, pOld);
102859     }
102860     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102861   }
102862   pTerm = &pWC->a[idx = pWC->nTerm++];
102863   pTerm->pExpr = p;
102864   pTerm->wtFlags = wtFlags;
102865   pTerm->pWC = pWC;
102866   pTerm->iParent = -1;
102867   return idx;
102868 }
102869
102870 /*
102871 ** This routine identifies subexpressions in the WHERE clause where
102872 ** each subexpression is separated by the AND operator or some other
102873 ** operator specified in the op parameter.  The WhereClause structure
102874 ** is filled with pointers to subexpressions.  For example:
102875 **
102876 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102877 **           \________/     \_______________/     \________________/
102878 **            slot[0]            slot[1]               slot[2]
102879 **
102880 ** The original WHERE clause in pExpr is unaltered.  All this routine
102881 ** does is make slot[] entries point to substructure within pExpr.
102882 **
102883 ** In the previous sentence and in the diagram, "slot[]" refers to
102884 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102885 ** all terms of the WHERE clause.
102886 */
102887 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102888   pWC->op = (u8)op;
102889   if( pExpr==0 ) return;
102890   if( pExpr->op!=op ){
102891     whereClauseInsert(pWC, pExpr, 0);
102892   }else{
102893     whereSplit(pWC, pExpr->pLeft, op);
102894     whereSplit(pWC, pExpr->pRight, op);
102895   }
102896 }
102897
102898 /*
102899 ** Initialize an expression mask set (a WhereMaskSet object)
102900 */
102901 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
102902
102903 /*
102904 ** Return the bitmask for the given cursor number.  Return 0 if
102905 ** iCursor is not in the set.
102906 */
102907 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102908   int i;
102909   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102910   for(i=0; i<pMaskSet->n; i++){
102911     if( pMaskSet->ix[i]==iCursor ){
102912       return ((Bitmask)1)<<i;
102913     }
102914   }
102915   return 0;
102916 }
102917
102918 /*
102919 ** Create a new mask for cursor iCursor.
102920 **
102921 ** There is one cursor per table in the FROM clause.  The number of
102922 ** tables in the FROM clause is limited by a test early in the
102923 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102924 ** array will never overflow.
102925 */
102926 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102927   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102928   pMaskSet->ix[pMaskSet->n++] = iCursor;
102929 }
102930
102931 /*
102932 ** This routine walks (recursively) an expression tree and generates
102933 ** a bitmask indicating which tables are used in that expression
102934 ** tree.
102935 **
102936 ** In order for this routine to work, the calling function must have
102937 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
102938 ** the header comment on that routine for additional information.
102939 ** The sqlite3ResolveExprNames() routines looks for column names and
102940 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102941 ** the VDBE cursor number of the table.  This routine just has to
102942 ** translate the cursor numbers into bitmask values and OR all
102943 ** the bitmasks together.
102944 */
102945 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102946 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102947 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
102948   Bitmask mask = 0;
102949   if( p==0 ) return 0;
102950   if( p->op==TK_COLUMN ){
102951     mask = getMask(pMaskSet, p->iTable);
102952     return mask;
102953   }
102954   mask = exprTableUsage(pMaskSet, p->pRight);
102955   mask |= exprTableUsage(pMaskSet, p->pLeft);
102956   if( ExprHasProperty(p, EP_xIsSelect) ){
102957     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
102958   }else{
102959     mask |= exprListTableUsage(pMaskSet, p->x.pList);
102960   }
102961   return mask;
102962 }
102963 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
102964   int i;
102965   Bitmask mask = 0;
102966   if( pList ){
102967     for(i=0; i<pList->nExpr; i++){
102968       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
102969     }
102970   }
102971   return mask;
102972 }
102973 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
102974   Bitmask mask = 0;
102975   while( pS ){
102976     SrcList *pSrc = pS->pSrc;
102977     mask |= exprListTableUsage(pMaskSet, pS->pEList);
102978     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
102979     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
102980     mask |= exprTableUsage(pMaskSet, pS->pWhere);
102981     mask |= exprTableUsage(pMaskSet, pS->pHaving);
102982     if( ALWAYS(pSrc!=0) ){
102983       int i;
102984       for(i=0; i<pSrc->nSrc; i++){
102985         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
102986         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
102987       }
102988     }
102989     pS = pS->pPrior;
102990   }
102991   return mask;
102992 }
102993
102994 /*
102995 ** Return TRUE if the given operator is one of the operators that is
102996 ** allowed for an indexable WHERE clause term.  The allowed operators are
102997 ** "=", "<", ">", "<=", ">=", and "IN".
102998 **
102999 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
103000 ** of one of the following forms: column = expression column > expression
103001 ** column >= expression column < expression column <= expression
103002 ** expression = column expression > column expression >= column
103003 ** expression < column expression <= column column IN
103004 ** (expression-list) column IN (subquery) column IS NULL
103005 */
103006 static int allowedOp(int op){
103007   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103008   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
103009   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103010   assert( TK_GE==TK_EQ+4 );
103011   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
103012 }
103013
103014 /*
103015 ** Swap two objects of type TYPE.
103016 */
103017 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
103018
103019 /*
103020 ** Commute a comparison operator.  Expressions of the form "X op Y"
103021 ** are converted into "Y op X".
103022 **
103023 ** If left/right precendence rules come into play when determining the
103024 ** collating
103025 ** side of the comparison, it remains associated with the same side after
103026 ** the commutation. So "Y collate NOCASE op X" becomes 
103027 ** "X op Y". This is because any collation sequence on
103028 ** the left hand side of a comparison overrides any collation sequence 
103029 ** attached to the right. For the same reason the EP_Collate flag
103030 ** is not commuted.
103031 */
103032 static void exprCommute(Parse *pParse, Expr *pExpr){
103033   u16 expRight = (pExpr->pRight->flags & EP_Collate);
103034   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
103035   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
103036   if( expRight==expLeft ){
103037     /* Either X and Y both have COLLATE operator or neither do */
103038     if( expRight ){
103039       /* Both X and Y have COLLATE operators.  Make sure X is always
103040       ** used by clearing the EP_Collate flag from Y. */
103041       pExpr->pRight->flags &= ~EP_Collate;
103042     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
103043       /* Neither X nor Y have COLLATE operators, but X has a non-default
103044       ** collating sequence.  So add the EP_Collate marker on X to cause
103045       ** it to be searched first. */
103046       pExpr->pLeft->flags |= EP_Collate;
103047     }
103048   }
103049   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
103050   if( pExpr->op>=TK_GT ){
103051     assert( TK_LT==TK_GT+2 );
103052     assert( TK_GE==TK_LE+2 );
103053     assert( TK_GT>TK_EQ );
103054     assert( TK_GT<TK_LE );
103055     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
103056     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
103057   }
103058 }
103059
103060 /*
103061 ** Translate from TK_xx operator to WO_xx bitmask.
103062 */
103063 static u16 operatorMask(int op){
103064   u16 c;
103065   assert( allowedOp(op) );
103066   if( op==TK_IN ){
103067     c = WO_IN;
103068   }else if( op==TK_ISNULL ){
103069     c = WO_ISNULL;
103070   }else{
103071     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
103072     c = (u16)(WO_EQ<<(op-TK_EQ));
103073   }
103074   assert( op!=TK_ISNULL || c==WO_ISNULL );
103075   assert( op!=TK_IN || c==WO_IN );
103076   assert( op!=TK_EQ || c==WO_EQ );
103077   assert( op!=TK_LT || c==WO_LT );
103078   assert( op!=TK_LE || c==WO_LE );
103079   assert( op!=TK_GT || c==WO_GT );
103080   assert( op!=TK_GE || c==WO_GE );
103081   return c;
103082 }
103083
103084 /*
103085 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
103086 ** where X is a reference to the iColumn of table iCur and <op> is one of
103087 ** the WO_xx operator codes specified by the op parameter.
103088 ** Return a pointer to the term.  Return 0 if not found.
103089 */
103090 static WhereTerm *findTerm(
103091   WhereClause *pWC,     /* The WHERE clause to be searched */
103092   int iCur,             /* Cursor number of LHS */
103093   int iColumn,          /* Column number of LHS */
103094   Bitmask notReady,     /* RHS must not overlap with this mask */
103095   u32 op,               /* Mask of WO_xx values describing operator */
103096   Index *pIdx           /* Must be compatible with this index, if not NULL */
103097 ){
103098   WhereTerm *pTerm;
103099   int k;
103100   assert( iCur>=0 );
103101   op &= WO_ALL;
103102   for(; pWC; pWC=pWC->pOuter){
103103     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
103104       if( pTerm->leftCursor==iCur
103105          && (pTerm->prereqRight & notReady)==0
103106          && pTerm->u.leftColumn==iColumn
103107          && (pTerm->eOperator & op)!=0
103108       ){
103109         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
103110           Expr *pX = pTerm->pExpr;
103111           CollSeq *pColl;
103112           char idxaff;
103113           int j;
103114           Parse *pParse = pWC->pParse;
103115   
103116           idxaff = pIdx->pTable->aCol[iColumn].affinity;
103117           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
103118   
103119           /* Figure out the collation sequence required from an index for
103120           ** it to be useful for optimising expression pX. Store this
103121           ** value in variable pColl.
103122           */
103123           assert(pX->pLeft);
103124           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103125           if( pColl==0 ) pColl = pParse->db->pDfltColl;
103126   
103127           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
103128             if( NEVER(j>=pIdx->nColumn) ) return 0;
103129           }
103130           if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
103131         }
103132         return pTerm;
103133       }
103134     }
103135   }
103136   return 0;
103137 }
103138
103139 /* Forward reference */
103140 static void exprAnalyze(SrcList*, WhereClause*, int);
103141
103142 /*
103143 ** Call exprAnalyze on all terms in a WHERE clause.  
103144 **
103145 **
103146 */
103147 static void exprAnalyzeAll(
103148   SrcList *pTabList,       /* the FROM clause */
103149   WhereClause *pWC         /* the WHERE clause to be analyzed */
103150 ){
103151   int i;
103152   for(i=pWC->nTerm-1; i>=0; i--){
103153     exprAnalyze(pTabList, pWC, i);
103154   }
103155 }
103156
103157 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103158 /*
103159 ** Check to see if the given expression is a LIKE or GLOB operator that
103160 ** can be optimized using inequality constraints.  Return TRUE if it is
103161 ** so and false if not.
103162 **
103163 ** In order for the operator to be optimizible, the RHS must be a string
103164 ** literal that does not begin with a wildcard.  
103165 */
103166 static int isLikeOrGlob(
103167   Parse *pParse,    /* Parsing and code generating context */
103168   Expr *pExpr,      /* Test this expression */
103169   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
103170   int *pisComplete, /* True if the only wildcard is % in the last character */
103171   int *pnoCase      /* True if uppercase is equivalent to lowercase */
103172 ){
103173   const char *z = 0;         /* String on RHS of LIKE operator */
103174   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
103175   ExprList *pList;           /* List of operands to the LIKE operator */
103176   int c;                     /* One character in z[] */
103177   int cnt;                   /* Number of non-wildcard prefix characters */
103178   char wc[3];                /* Wildcard characters */
103179   sqlite3 *db = pParse->db;  /* Database connection */
103180   sqlite3_value *pVal = 0;
103181   int op;                    /* Opcode of pRight */
103182
103183   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
103184     return 0;
103185   }
103186 #ifdef SQLITE_EBCDIC
103187   if( *pnoCase ) return 0;
103188 #endif
103189   pList = pExpr->x.pList;
103190   pLeft = pList->a[1].pExpr;
103191   if( pLeft->op!=TK_COLUMN 
103192    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
103193    || IsVirtual(pLeft->pTab)
103194   ){
103195     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
103196     ** be the name of an indexed column with TEXT affinity. */
103197     return 0;
103198   }
103199   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
103200
103201   pRight = pList->a[0].pExpr;
103202   op = pRight->op;
103203   if( op==TK_REGISTER ){
103204     op = pRight->op2;
103205   }
103206   if( op==TK_VARIABLE ){
103207     Vdbe *pReprepare = pParse->pReprepare;
103208     int iCol = pRight->iColumn;
103209     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
103210     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
103211       z = (char *)sqlite3_value_text(pVal);
103212     }
103213     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
103214     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
103215   }else if( op==TK_STRING ){
103216     z = pRight->u.zToken;
103217   }
103218   if( z ){
103219     cnt = 0;
103220     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
103221       cnt++;
103222     }
103223     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
103224       Expr *pPrefix;
103225       *pisComplete = c==wc[0] && z[cnt+1]==0;
103226       pPrefix = sqlite3Expr(db, TK_STRING, z);
103227       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
103228       *ppPrefix = pPrefix;
103229       if( op==TK_VARIABLE ){
103230         Vdbe *v = pParse->pVdbe;
103231         sqlite3VdbeSetVarmask(v, pRight->iColumn);
103232         if( *pisComplete && pRight->u.zToken[1] ){
103233           /* If the rhs of the LIKE expression is a variable, and the current
103234           ** value of the variable means there is no need to invoke the LIKE
103235           ** function, then no OP_Variable will be added to the program.
103236           ** This causes problems for the sqlite3_bind_parameter_name()
103237           ** API. To workaround them, add a dummy OP_Variable here.
103238           */ 
103239           int r1 = sqlite3GetTempReg(pParse);
103240           sqlite3ExprCodeTarget(pParse, pRight, r1);
103241           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
103242           sqlite3ReleaseTempReg(pParse, r1);
103243         }
103244       }
103245     }else{
103246       z = 0;
103247     }
103248   }
103249
103250   sqlite3ValueFree(pVal);
103251   return (z!=0);
103252 }
103253 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103254
103255
103256 #ifndef SQLITE_OMIT_VIRTUALTABLE
103257 /*
103258 ** Check to see if the given expression is of the form
103259 **
103260 **         column MATCH expr
103261 **
103262 ** If it is then return TRUE.  If not, return FALSE.
103263 */
103264 static int isMatchOfColumn(
103265   Expr *pExpr      /* Test this expression */
103266 ){
103267   ExprList *pList;
103268
103269   if( pExpr->op!=TK_FUNCTION ){
103270     return 0;
103271   }
103272   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
103273     return 0;
103274   }
103275   pList = pExpr->x.pList;
103276   if( pList->nExpr!=2 ){
103277     return 0;
103278   }
103279   if( pList->a[1].pExpr->op != TK_COLUMN ){
103280     return 0;
103281   }
103282   return 1;
103283 }
103284 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103285
103286 /*
103287 ** If the pBase expression originated in the ON or USING clause of
103288 ** a join, then transfer the appropriate markings over to derived.
103289 */
103290 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
103291   pDerived->flags |= pBase->flags & EP_FromJoin;
103292   pDerived->iRightJoinTable = pBase->iRightJoinTable;
103293 }
103294
103295 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103296 /*
103297 ** Analyze a term that consists of two or more OR-connected
103298 ** subterms.  So in:
103299 **
103300 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
103301 **                          ^^^^^^^^^^^^^^^^^^^^
103302 **
103303 ** This routine analyzes terms such as the middle term in the above example.
103304 ** A WhereOrTerm object is computed and attached to the term under
103305 ** analysis, regardless of the outcome of the analysis.  Hence:
103306 **
103307 **     WhereTerm.wtFlags   |=  TERM_ORINFO
103308 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
103309 **
103310 ** The term being analyzed must have two or more of OR-connected subterms.
103311 ** A single subterm might be a set of AND-connected sub-subterms.
103312 ** Examples of terms under analysis:
103313 **
103314 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
103315 **     (B)     x=expr1 OR expr2=x OR x=expr3
103316 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
103317 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
103318 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
103319 **
103320 ** CASE 1:
103321 **
103322 ** If all subterms are of the form T.C=expr for some single column of C
103323 ** a single table T (as shown in example B above) then create a new virtual
103324 ** term that is an equivalent IN expression.  In other words, if the term
103325 ** being analyzed is:
103326 **
103327 **      x = expr1  OR  expr2 = x  OR  x = expr3
103328 **
103329 ** then create a new virtual term like this:
103330 **
103331 **      x IN (expr1,expr2,expr3)
103332 **
103333 ** CASE 2:
103334 **
103335 ** If all subterms are indexable by a single table T, then set
103336 **
103337 **     WhereTerm.eOperator              =  WO_OR
103338 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103339 **
103340 ** A subterm is "indexable" if it is of the form
103341 ** "T.C <op> <expr>" where C is any column of table T and 
103342 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103343 ** A subterm is also indexable if it is an AND of two or more
103344 ** subsubterms at least one of which is indexable.  Indexable AND 
103345 ** subterms have their eOperator set to WO_AND and they have
103346 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103347 **
103348 ** From another point of view, "indexable" means that the subterm could
103349 ** potentially be used with an index if an appropriate index exists.
103350 ** This analysis does not consider whether or not the index exists; that
103351 ** is something the bestIndex() routine will determine.  This analysis
103352 ** only looks at whether subterms appropriate for indexing exist.
103353 **
103354 ** All examples A through E above all satisfy case 2.  But if a term
103355 ** also statisfies case 1 (such as B) we know that the optimizer will
103356 ** always prefer case 1, so in that case we pretend that case 2 is not
103357 ** satisfied.
103358 **
103359 ** It might be the case that multiple tables are indexable.  For example,
103360 ** (E) above is indexable on tables P, Q, and R.
103361 **
103362 ** Terms that satisfy case 2 are candidates for lookup by using
103363 ** separate indices to find rowids for each subterm and composing
103364 ** the union of all rowids using a RowSet object.  This is similar
103365 ** to "bitmap indices" in other database engines.
103366 **
103367 ** OTHERWISE:
103368 **
103369 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
103370 ** zero.  This term is not useful for search.
103371 */
103372 static void exprAnalyzeOrTerm(
103373   SrcList *pSrc,            /* the FROM clause */
103374   WhereClause *pWC,         /* the complete WHERE clause */
103375   int idxTerm               /* Index of the OR-term to be analyzed */
103376 ){
103377   Parse *pParse = pWC->pParse;            /* Parser context */
103378   sqlite3 *db = pParse->db;               /* Database connection */
103379   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103380   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103381   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103382   int i;                                  /* Loop counters */
103383   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103384   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103385   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103386   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103387   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103388
103389   /*
103390   ** Break the OR clause into its separate subterms.  The subterms are
103391   ** stored in a WhereClause structure containing within the WhereOrInfo
103392   ** object that is attached to the original OR clause term.
103393   */
103394   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103395   assert( pExpr->op==TK_OR );
103396   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
103397   if( pOrInfo==0 ) return;
103398   pTerm->wtFlags |= TERM_ORINFO;
103399   pOrWc = &pOrInfo->wc;
103400   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103401   whereSplit(pOrWc, pExpr, TK_OR);
103402   exprAnalyzeAll(pSrc, pOrWc);
103403   if( db->mallocFailed ) return;
103404   assert( pOrWc->nTerm>=2 );
103405
103406   /*
103407   ** Compute the set of tables that might satisfy cases 1 or 2.
103408   */
103409   indexable = ~(Bitmask)0;
103410   chngToIN = ~(pWC->vmask);
103411   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103412     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103413       WhereAndInfo *pAndInfo;
103414       assert( pOrTerm->eOperator==0 );
103415       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103416       chngToIN = 0;
103417       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
103418       if( pAndInfo ){
103419         WhereClause *pAndWC;
103420         WhereTerm *pAndTerm;
103421         int j;
103422         Bitmask b = 0;
103423         pOrTerm->u.pAndInfo = pAndInfo;
103424         pOrTerm->wtFlags |= TERM_ANDINFO;
103425         pOrTerm->eOperator = WO_AND;
103426         pAndWC = &pAndInfo->wc;
103427         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103428         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103429         exprAnalyzeAll(pSrc, pAndWC);
103430         pAndWC->pOuter = pWC;
103431         testcase( db->mallocFailed );
103432         if( !db->mallocFailed ){
103433           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103434             assert( pAndTerm->pExpr );
103435             if( allowedOp(pAndTerm->pExpr->op) ){
103436               b |= getMask(pMaskSet, pAndTerm->leftCursor);
103437             }
103438           }
103439         }
103440         indexable &= b;
103441       }
103442     }else if( pOrTerm->wtFlags & TERM_COPIED ){
103443       /* Skip this term for now.  We revisit it when we process the
103444       ** corresponding TERM_VIRTUAL term */
103445     }else{
103446       Bitmask b;
103447       b = getMask(pMaskSet, pOrTerm->leftCursor);
103448       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103449         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103450         b |= getMask(pMaskSet, pOther->leftCursor);
103451       }
103452       indexable &= b;
103453       if( pOrTerm->eOperator!=WO_EQ ){
103454         chngToIN = 0;
103455       }else{
103456         chngToIN &= b;
103457       }
103458     }
103459   }
103460
103461   /*
103462   ** Record the set of tables that satisfy case 2.  The set might be
103463   ** empty.
103464   */
103465   pOrInfo->indexable = indexable;
103466   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
103467
103468   /*
103469   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
103470   ** we have to do some additional checking to see if case 1 really
103471   ** is satisfied.
103472   **
103473   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
103474   ** that there is no possibility of transforming the OR clause into an
103475   ** IN operator because one or more terms in the OR clause contain
103476   ** something other than == on a column in the single table.  The 1-bit
103477   ** case means that every term of the OR clause is of the form
103478   ** "table.column=expr" for some single table.  The one bit that is set
103479   ** will correspond to the common table.  We still need to check to make
103480   ** sure the same column is used on all terms.  The 2-bit case is when
103481   ** the all terms are of the form "table1.column=table2.column".  It
103482   ** might be possible to form an IN operator with either table1.column
103483   ** or table2.column as the LHS if either is common to every term of
103484   ** the OR clause.
103485   **
103486   ** Note that terms of the form "table.column1=table.column2" (the
103487   ** same table on both sizes of the ==) cannot be optimized.
103488   */
103489   if( chngToIN ){
103490     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
103491     int iColumn = -1;         /* Column index on lhs of IN operator */
103492     int iCursor = -1;         /* Table cursor common to all terms */
103493     int j = 0;                /* Loop counter */
103494
103495     /* Search for a table and column that appears on one side or the
103496     ** other of the == operator in every subterm.  That table and column
103497     ** will be recorded in iCursor and iColumn.  There might not be any
103498     ** such table and column.  Set okToChngToIN if an appropriate table
103499     ** and column is found but leave okToChngToIN false if not found.
103500     */
103501     for(j=0; j<2 && !okToChngToIN; j++){
103502       pOrTerm = pOrWc->a;
103503       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
103504         assert( pOrTerm->eOperator==WO_EQ );
103505         pOrTerm->wtFlags &= ~TERM_OR_OK;
103506         if( pOrTerm->leftCursor==iCursor ){
103507           /* This is the 2-bit case and we are on the second iteration and
103508           ** current term is from the first iteration.  So skip this term. */
103509           assert( j==1 );
103510           continue;
103511         }
103512         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
103513           /* This term must be of the form t1.a==t2.b where t2 is in the
103514           ** chngToIN set but t1 is not.  This term will be either preceeded
103515           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
103516           ** and use its inversion. */
103517           testcase( pOrTerm->wtFlags & TERM_COPIED );
103518           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
103519           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
103520           continue;
103521         }
103522         iColumn = pOrTerm->u.leftColumn;
103523         iCursor = pOrTerm->leftCursor;
103524         break;
103525       }
103526       if( i<0 ){
103527         /* No candidate table+column was found.  This can only occur
103528         ** on the second iteration */
103529         assert( j==1 );
103530         assert( (chngToIN&(chngToIN-1))==0 );
103531         assert( chngToIN==getMask(pMaskSet, iCursor) );
103532         break;
103533       }
103534       testcase( j==1 );
103535
103536       /* We have found a candidate table and column.  Check to see if that
103537       ** table and column is common to every term in the OR clause */
103538       okToChngToIN = 1;
103539       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
103540         assert( pOrTerm->eOperator==WO_EQ );
103541         if( pOrTerm->leftCursor!=iCursor ){
103542           pOrTerm->wtFlags &= ~TERM_OR_OK;
103543         }else if( pOrTerm->u.leftColumn!=iColumn ){
103544           okToChngToIN = 0;
103545         }else{
103546           int affLeft, affRight;
103547           /* If the right-hand side is also a column, then the affinities
103548           ** of both right and left sides must be such that no type
103549           ** conversions are required on the right.  (Ticket #2249)
103550           */
103551           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
103552           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
103553           if( affRight!=0 && affRight!=affLeft ){
103554             okToChngToIN = 0;
103555           }else{
103556             pOrTerm->wtFlags |= TERM_OR_OK;
103557           }
103558         }
103559       }
103560     }
103561
103562     /* At this point, okToChngToIN is true if original pTerm satisfies
103563     ** case 1.  In that case, construct a new virtual term that is 
103564     ** pTerm converted into an IN operator.
103565     **
103566     ** EV: R-00211-15100
103567     */
103568     if( okToChngToIN ){
103569       Expr *pDup;            /* A transient duplicate expression */
103570       ExprList *pList = 0;   /* The RHS of the IN operator */
103571       Expr *pLeft = 0;       /* The LHS of the IN operator */
103572       Expr *pNew;            /* The complete IN operator */
103573
103574       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
103575         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
103576         assert( pOrTerm->eOperator==WO_EQ );
103577         assert( pOrTerm->leftCursor==iCursor );
103578         assert( pOrTerm->u.leftColumn==iColumn );
103579         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
103580         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
103581         pLeft = pOrTerm->pExpr->pLeft;
103582       }
103583       assert( pLeft!=0 );
103584       pDup = sqlite3ExprDup(db, pLeft, 0);
103585       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
103586       if( pNew ){
103587         int idxNew;
103588         transferJoinMarkings(pNew, pExpr);
103589         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
103590         pNew->x.pList = pList;
103591         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
103592         testcase( idxNew==0 );
103593         exprAnalyze(pSrc, pWC, idxNew);
103594         pTerm = &pWC->a[idxTerm];
103595         pWC->a[idxNew].iParent = idxTerm;
103596         pTerm->nChild = 1;
103597       }else{
103598         sqlite3ExprListDelete(db, pList);
103599       }
103600       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
103601     }
103602   }
103603 }
103604 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
103605
103606
103607 /*
103608 ** The input to this routine is an WhereTerm structure with only the
103609 ** "pExpr" field filled in.  The job of this routine is to analyze the
103610 ** subexpression and populate all the other fields of the WhereTerm
103611 ** structure.
103612 **
103613 ** If the expression is of the form "<expr> <op> X" it gets commuted
103614 ** to the standard form of "X <op> <expr>".
103615 **
103616 ** If the expression is of the form "X <op> Y" where both X and Y are
103617 ** columns, then the original expression is unchanged and a new virtual
103618 ** term of the form "Y <op> X" is added to the WHERE clause and
103619 ** analyzed separately.  The original term is marked with TERM_COPIED
103620 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
103621 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
103622 ** is a commuted copy of a prior term.)  The original term has nChild=1
103623 ** and the copy has idxParent set to the index of the original term.
103624 */
103625 static void exprAnalyze(
103626   SrcList *pSrc,            /* the FROM clause */
103627   WhereClause *pWC,         /* the WHERE clause */
103628   int idxTerm               /* Index of the term to be analyzed */
103629 ){
103630   WhereTerm *pTerm;                /* The term to be analyzed */
103631   WhereMaskSet *pMaskSet;          /* Set of table index masks */
103632   Expr *pExpr;                     /* The expression to be analyzed */
103633   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
103634   Bitmask prereqAll;               /* Prerequesites of pExpr */
103635   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
103636   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
103637   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
103638   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
103639   int op;                          /* Top-level operator.  pExpr->op */
103640   Parse *pParse = pWC->pParse;     /* Parsing context */
103641   sqlite3 *db = pParse->db;        /* Database connection */
103642
103643   if( db->mallocFailed ){
103644     return;
103645   }
103646   pTerm = &pWC->a[idxTerm];
103647   pMaskSet = pWC->pMaskSet;
103648   pExpr = sqlite3ExprSkipCollate(pTerm->pExpr);
103649   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
103650   op = pExpr->op;
103651   if( op==TK_IN ){
103652     assert( pExpr->pRight==0 );
103653     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103654       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
103655     }else{
103656       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
103657     }
103658   }else if( op==TK_ISNULL ){
103659     pTerm->prereqRight = 0;
103660   }else{
103661     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
103662   }
103663   prereqAll = exprTableUsage(pMaskSet, pExpr);
103664   if( ExprHasProperty(pExpr, EP_FromJoin) ){
103665     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
103666     prereqAll |= x;
103667     extraRight = x-1;  /* ON clause terms may not be used with an index
103668                        ** on left table of a LEFT JOIN.  Ticket #3015 */
103669   }
103670   pTerm->prereqAll = prereqAll;
103671   pTerm->leftCursor = -1;
103672   pTerm->iParent = -1;
103673   pTerm->eOperator = 0;
103674   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
103675     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
103676     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
103677     if( pLeft->op==TK_COLUMN ){
103678       pTerm->leftCursor = pLeft->iTable;
103679       pTerm->u.leftColumn = pLeft->iColumn;
103680       pTerm->eOperator = operatorMask(op);
103681     }
103682     if( pRight && pRight->op==TK_COLUMN ){
103683       WhereTerm *pNew;
103684       Expr *pDup;
103685       if( pTerm->leftCursor>=0 ){
103686         int idxNew;
103687         pDup = sqlite3ExprDup(db, pExpr, 0);
103688         if( db->mallocFailed ){
103689           sqlite3ExprDelete(db, pDup);
103690           return;
103691         }
103692         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
103693         if( idxNew==0 ) return;
103694         pNew = &pWC->a[idxNew];
103695         pNew->iParent = idxTerm;
103696         pTerm = &pWC->a[idxTerm];
103697         pTerm->nChild = 1;
103698         pTerm->wtFlags |= TERM_COPIED;
103699       }else{
103700         pDup = pExpr;
103701         pNew = pTerm;
103702       }
103703       exprCommute(pParse, pDup);
103704       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
103705       pNew->leftCursor = pLeft->iTable;
103706       pNew->u.leftColumn = pLeft->iColumn;
103707       testcase( (prereqLeft | extraRight) != prereqLeft );
103708       pNew->prereqRight = prereqLeft | extraRight;
103709       pNew->prereqAll = prereqAll;
103710       pNew->eOperator = operatorMask(pDup->op);
103711     }
103712   }
103713
103714 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
103715   /* If a term is the BETWEEN operator, create two new virtual terms
103716   ** that define the range that the BETWEEN implements.  For example:
103717   **
103718   **      a BETWEEN b AND c
103719   **
103720   ** is converted into:
103721   **
103722   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
103723   **
103724   ** The two new terms are added onto the end of the WhereClause object.
103725   ** The new terms are "dynamic" and are children of the original BETWEEN
103726   ** term.  That means that if the BETWEEN term is coded, the children are
103727   ** skipped.  Or, if the children are satisfied by an index, the original
103728   ** BETWEEN term is skipped.
103729   */
103730   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
103731     ExprList *pList = pExpr->x.pList;
103732     int i;
103733     static const u8 ops[] = {TK_GE, TK_LE};
103734     assert( pList!=0 );
103735     assert( pList->nExpr==2 );
103736     for(i=0; i<2; i++){
103737       Expr *pNewExpr;
103738       int idxNew;
103739       pNewExpr = sqlite3PExpr(pParse, ops[i], 
103740                              sqlite3ExprDup(db, pExpr->pLeft, 0),
103741                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
103742       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103743       testcase( idxNew==0 );
103744       exprAnalyze(pSrc, pWC, idxNew);
103745       pTerm = &pWC->a[idxTerm];
103746       pWC->a[idxNew].iParent = idxTerm;
103747     }
103748     pTerm->nChild = 2;
103749   }
103750 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
103751
103752 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103753   /* Analyze a term that is composed of two or more subterms connected by
103754   ** an OR operator.
103755   */
103756   else if( pExpr->op==TK_OR ){
103757     assert( pWC->op==TK_AND );
103758     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
103759     pTerm = &pWC->a[idxTerm];
103760   }
103761 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
103762
103763 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103764   /* Add constraints to reduce the search space on a LIKE or GLOB
103765   ** operator.
103766   **
103767   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
103768   **
103769   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
103770   **
103771   ** The last character of the prefix "abc" is incremented to form the
103772   ** termination condition "abd".
103773   */
103774   if( pWC->op==TK_AND 
103775    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
103776   ){
103777     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
103778     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
103779     Expr *pNewExpr1;
103780     Expr *pNewExpr2;
103781     int idxNew1;
103782     int idxNew2;
103783     Token sCollSeqName;  /* Name of collating sequence */
103784
103785     pLeft = pExpr->x.pList->a[1].pExpr;
103786     pStr2 = sqlite3ExprDup(db, pStr1, 0);
103787     if( !db->mallocFailed ){
103788       u8 c, *pC;       /* Last character before the first wildcard */
103789       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
103790       c = *pC;
103791       if( noCase ){
103792         /* The point is to increment the last character before the first
103793         ** wildcard.  But if we increment '@', that will push it into the
103794         ** alphabetic range where case conversions will mess up the 
103795         ** inequality.  To avoid this, make sure to also run the full
103796         ** LIKE on all candidate expressions by clearing the isComplete flag
103797         */
103798         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
103799
103800
103801         c = sqlite3UpperToLower[c];
103802       }
103803       *pC = c + 1;
103804     }
103805     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
103806     sCollSeqName.n = 6;
103807     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
103808     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
103809            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
103810            pStr1, 0);
103811     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
103812     testcase( idxNew1==0 );
103813     exprAnalyze(pSrc, pWC, idxNew1);
103814     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
103815     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
103816            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
103817            pStr2, 0);
103818     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
103819     testcase( idxNew2==0 );
103820     exprAnalyze(pSrc, pWC, idxNew2);
103821     pTerm = &pWC->a[idxTerm];
103822     if( isComplete ){
103823       pWC->a[idxNew1].iParent = idxTerm;
103824       pWC->a[idxNew2].iParent = idxTerm;
103825       pTerm->nChild = 2;
103826     }
103827   }
103828 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103829
103830 #ifndef SQLITE_OMIT_VIRTUALTABLE
103831   /* Add a WO_MATCH auxiliary term to the constraint set if the
103832   ** current expression is of the form:  column MATCH expr.
103833   ** This information is used by the xBestIndex methods of
103834   ** virtual tables.  The native query optimizer does not attempt
103835   ** to do anything with MATCH functions.
103836   */
103837   if( isMatchOfColumn(pExpr) ){
103838     int idxNew;
103839     Expr *pRight, *pLeft;
103840     WhereTerm *pNewTerm;
103841     Bitmask prereqColumn, prereqExpr;
103842
103843     pRight = pExpr->x.pList->a[0].pExpr;
103844     pLeft = pExpr->x.pList->a[1].pExpr;
103845     prereqExpr = exprTableUsage(pMaskSet, pRight);
103846     prereqColumn = exprTableUsage(pMaskSet, pLeft);
103847     if( (prereqExpr & prereqColumn)==0 ){
103848       Expr *pNewExpr;
103849       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
103850                               0, sqlite3ExprDup(db, pRight, 0), 0);
103851       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103852       testcase( idxNew==0 );
103853       pNewTerm = &pWC->a[idxNew];
103854       pNewTerm->prereqRight = prereqExpr;
103855       pNewTerm->leftCursor = pLeft->iTable;
103856       pNewTerm->u.leftColumn = pLeft->iColumn;
103857       pNewTerm->eOperator = WO_MATCH;
103858       pNewTerm->iParent = idxTerm;
103859       pTerm = &pWC->a[idxTerm];
103860       pTerm->nChild = 1;
103861       pTerm->wtFlags |= TERM_COPIED;
103862       pNewTerm->prereqAll = pTerm->prereqAll;
103863     }
103864   }
103865 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103866
103867 #ifdef SQLITE_ENABLE_STAT3
103868   /* When sqlite_stat3 histogram data is available an operator of the
103869   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103870   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103871   ** virtual term of that form.
103872   **
103873   ** Note that the virtual term must be tagged with TERM_VNULL.  This
103874   ** TERM_VNULL tag will suppress the not-null check at the beginning
103875   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103876   ** the start of the loop will prevent any results from being returned.
103877   */
103878   if( pExpr->op==TK_NOTNULL
103879    && pExpr->pLeft->op==TK_COLUMN
103880    && pExpr->pLeft->iColumn>=0
103881   ){
103882     Expr *pNewExpr;
103883     Expr *pLeft = pExpr->pLeft;
103884     int idxNew;
103885     WhereTerm *pNewTerm;
103886
103887     pNewExpr = sqlite3PExpr(pParse, TK_GT,
103888                             sqlite3ExprDup(db, pLeft, 0),
103889                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103890
103891     idxNew = whereClauseInsert(pWC, pNewExpr,
103892                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103893     if( idxNew ){
103894       pNewTerm = &pWC->a[idxNew];
103895       pNewTerm->prereqRight = 0;
103896       pNewTerm->leftCursor = pLeft->iTable;
103897       pNewTerm->u.leftColumn = pLeft->iColumn;
103898       pNewTerm->eOperator = WO_GT;
103899       pNewTerm->iParent = idxTerm;
103900       pTerm = &pWC->a[idxTerm];
103901       pTerm->nChild = 1;
103902       pTerm->wtFlags |= TERM_COPIED;
103903       pNewTerm->prereqAll = pTerm->prereqAll;
103904     }
103905   }
103906 #endif /* SQLITE_ENABLE_STAT */
103907
103908   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103909   ** an index for tables to the left of the join.
103910   */
103911   pTerm->prereqRight |= extraRight;
103912 }
103913
103914 /*
103915 ** This function searches the expression list passed as the second argument
103916 ** for an expression of type TK_COLUMN that refers to the same column and
103917 ** uses the same collation sequence as the iCol'th column of index pIdx.
103918 ** Argument iBase is the cursor number used for the table that pIdx refers
103919 ** to.
103920 **
103921 ** If such an expression is found, its index in pList->a[] is returned. If
103922 ** no expression is found, -1 is returned.
103923 */
103924 static int findIndexCol(
103925   Parse *pParse,                  /* Parse context */
103926   ExprList *pList,                /* Expression list to search */
103927   int iBase,                      /* Cursor for table associated with pIdx */
103928   Index *pIdx,                    /* Index to match column of */
103929   int iCol                        /* Column of index to match */
103930 ){
103931   int i;
103932   const char *zColl = pIdx->azColl[iCol];
103933
103934   for(i=0; i<pList->nExpr; i++){
103935     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
103936     if( p->op==TK_COLUMN
103937      && p->iColumn==pIdx->aiColumn[iCol]
103938      && p->iTable==iBase
103939     ){
103940       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
103941       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
103942         return i;
103943       }
103944     }
103945   }
103946
103947   return -1;
103948 }
103949
103950 /*
103951 ** This routine determines if pIdx can be used to assist in processing a
103952 ** DISTINCT qualifier. In other words, it tests whether or not using this
103953 ** index for the outer loop guarantees that rows with equal values for
103954 ** all expressions in the pDistinct list are delivered grouped together.
103955 **
103956 ** For example, the query 
103957 **
103958 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
103959 **
103960 ** can benefit from any index on columns "b" and "c".
103961 */
103962 static int isDistinctIndex(
103963   Parse *pParse,                  /* Parsing context */
103964   WhereClause *pWC,               /* The WHERE clause */
103965   Index *pIdx,                    /* The index being considered */
103966   int base,                       /* Cursor number for the table pIdx is on */
103967   ExprList *pDistinct,            /* The DISTINCT expressions */
103968   int nEqCol                      /* Number of index columns with == */
103969 ){
103970   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
103971   int i;                          /* Iterator variable */
103972
103973   assert( pDistinct!=0 );
103974   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
103975   testcase( pDistinct->nExpr==BMS-1 );
103976
103977   /* Loop through all the expressions in the distinct list. If any of them
103978   ** are not simple column references, return early. Otherwise, test if the
103979   ** WHERE clause contains a "col=X" clause. If it does, the expression
103980   ** can be ignored. If it does not, and the column does not belong to the
103981   ** same table as index pIdx, return early. Finally, if there is no
103982   ** matching "col=X" expression and the column is on the same table as pIdx,
103983   ** set the corresponding bit in variable mask.
103984   */
103985   for(i=0; i<pDistinct->nExpr; i++){
103986     WhereTerm *pTerm;
103987     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
103988     if( p->op!=TK_COLUMN ) return 0;
103989     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
103990     if( pTerm ){
103991       Expr *pX = pTerm->pExpr;
103992       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103993       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
103994       if( p1==p2 ) continue;
103995     }
103996     if( p->iTable!=base ) return 0;
103997     mask |= (((Bitmask)1) << i);
103998   }
103999
104000   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
104001     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
104002     if( iExpr<0 ) break;
104003     mask &= ~(((Bitmask)1) << iExpr);
104004   }
104005
104006   return (mask==0);
104007 }
104008
104009
104010 /*
104011 ** Return true if the DISTINCT expression-list passed as the third argument
104012 ** is redundant. A DISTINCT list is redundant if the database contains a
104013 ** UNIQUE index that guarantees that the result of the query will be distinct
104014 ** anyway.
104015 */
104016 static int isDistinctRedundant(
104017   Parse *pParse,
104018   SrcList *pTabList,
104019   WhereClause *pWC,
104020   ExprList *pDistinct
104021 ){
104022   Table *pTab;
104023   Index *pIdx;
104024   int i;                          
104025   int iBase;
104026
104027   /* If there is more than one table or sub-select in the FROM clause of
104028   ** this query, then it will not be possible to show that the DISTINCT 
104029   ** clause is redundant. */
104030   if( pTabList->nSrc!=1 ) return 0;
104031   iBase = pTabList->a[0].iCursor;
104032   pTab = pTabList->a[0].pTab;
104033
104034   /* If any of the expressions is an IPK column on table iBase, then return 
104035   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
104036   ** current SELECT is a correlated sub-query.
104037   */
104038   for(i=0; i<pDistinct->nExpr; i++){
104039     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
104040     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
104041   }
104042
104043   /* Loop through all indices on the table, checking each to see if it makes
104044   ** the DISTINCT qualifier redundant. It does so if:
104045   **
104046   **   1. The index is itself UNIQUE, and
104047   **
104048   **   2. All of the columns in the index are either part of the pDistinct
104049   **      list, or else the WHERE clause contains a term of the form "col=X",
104050   **      where X is a constant value. The collation sequences of the
104051   **      comparison and select-list expressions must match those of the index.
104052   **
104053   **   3. All of those index columns for which the WHERE clause does not
104054   **      contain a "col=X" term are subject to a NOT NULL constraint.
104055   */
104056   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104057     if( pIdx->onError==OE_None ) continue;
104058     for(i=0; i<pIdx->nColumn; i++){
104059       int iCol = pIdx->aiColumn[i];
104060       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
104061         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
104062         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
104063           break;
104064         }
104065       }
104066     }
104067     if( i==pIdx->nColumn ){
104068       /* This index implies that the DISTINCT qualifier is redundant. */
104069       return 1;
104070     }
104071   }
104072
104073   return 0;
104074 }
104075
104076 /*
104077 ** Prepare a crude estimate of the logarithm of the input value.
104078 ** The results need not be exact.  This is only used for estimating
104079 ** the total cost of performing operations with O(logN) or O(NlogN)
104080 ** complexity.  Because N is just a guess, it is no great tragedy if
104081 ** logN is a little off.
104082 */
104083 static double estLog(double N){
104084   double logN = 1;
104085   double x = 10;
104086   while( N>x ){
104087     logN += 1;
104088     x *= 10;
104089   }
104090   return logN;
104091 }
104092
104093 /*
104094 ** Two routines for printing the content of an sqlite3_index_info
104095 ** structure.  Used for testing and debugging only.  If neither
104096 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
104097 ** are no-ops.
104098 */
104099 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
104100 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
104101   int i;
104102   if( !sqlite3WhereTrace ) return;
104103   for(i=0; i<p->nConstraint; i++){
104104     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
104105        i,
104106        p->aConstraint[i].iColumn,
104107        p->aConstraint[i].iTermOffset,
104108        p->aConstraint[i].op,
104109        p->aConstraint[i].usable);
104110   }
104111   for(i=0; i<p->nOrderBy; i++){
104112     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
104113        i,
104114        p->aOrderBy[i].iColumn,
104115        p->aOrderBy[i].desc);
104116   }
104117 }
104118 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
104119   int i;
104120   if( !sqlite3WhereTrace ) return;
104121   for(i=0; i<p->nConstraint; i++){
104122     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
104123        i,
104124        p->aConstraintUsage[i].argvIndex,
104125        p->aConstraintUsage[i].omit);
104126   }
104127   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
104128   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
104129   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
104130   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
104131 }
104132 #else
104133 #define TRACE_IDX_INPUTS(A)
104134 #define TRACE_IDX_OUTPUTS(A)
104135 #endif
104136
104137 /* 
104138 ** Required because bestIndex() is called by bestOrClauseIndex() 
104139 */
104140 static void bestIndex(WhereBestIdx*);
104141
104142 /*
104143 ** This routine attempts to find an scanning strategy that can be used 
104144 ** to optimize an 'OR' expression that is part of a WHERE clause. 
104145 **
104146 ** The table associated with FROM clause term pSrc may be either a
104147 ** regular B-Tree table or a virtual table.
104148 */
104149 static void bestOrClauseIndex(WhereBestIdx *p){
104150 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
104151   WhereClause *pWC = p->pWC;           /* The WHERE clause */
104152   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
104153   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
104154   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
104155   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
104156   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
104157
104158   /* The OR-clause optimization is disallowed if the INDEXED BY or
104159   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
104160   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
104161     return;
104162   }
104163   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104164     return;
104165   }
104166
104167   /* Search the WHERE clause terms for a usable WO_OR term. */
104168   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104169     if( pTerm->eOperator==WO_OR 
104170      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
104171      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
104172     ){
104173       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104174       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104175       WhereTerm *pOrTerm;
104176       int flags = WHERE_MULTI_OR;
104177       double rTotal = 0;
104178       double nRow = 0;
104179       Bitmask used = 0;
104180       WhereBestIdx sBOI;
104181
104182       sBOI = *p;
104183       sBOI.pOrderBy = 0;
104184       sBOI.pDistinct = 0;
104185       sBOI.ppIdxInfo = 0;
104186       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104187         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
104188           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104189         ));
104190         if( pOrTerm->eOperator==WO_AND ){
104191           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
104192           bestIndex(&sBOI);
104193         }else if( pOrTerm->leftCursor==iCur ){
104194           WhereClause tempWC;
104195           tempWC.pParse = pWC->pParse;
104196           tempWC.pMaskSet = pWC->pMaskSet;
104197           tempWC.pOuter = pWC;
104198           tempWC.op = TK_AND;
104199           tempWC.a = pOrTerm;
104200           tempWC.wctrlFlags = 0;
104201           tempWC.nTerm = 1;
104202           sBOI.pWC = &tempWC;
104203           bestIndex(&sBOI);
104204         }else{
104205           continue;
104206         }
104207         rTotal += sBOI.cost.rCost;
104208         nRow += sBOI.cost.plan.nRow;
104209         used |= sBOI.cost.used;
104210         if( rTotal>=p->cost.rCost ) break;
104211       }
104212
104213       /* If there is an ORDER BY clause, increase the scan cost to account 
104214       ** for the cost of the sort. */
104215       if( p->pOrderBy!=0 ){
104216         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104217                     rTotal, rTotal+nRow*estLog(nRow)));
104218         rTotal += nRow*estLog(nRow);
104219       }
104220
104221       /* If the cost of scanning using this OR term for optimization is
104222       ** less than the current cost stored in pCost, replace the contents
104223       ** of pCost. */
104224       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104225       if( rTotal<p->cost.rCost ){
104226         p->cost.rCost = rTotal;
104227         p->cost.used = used;
104228         p->cost.plan.nRow = nRow;
104229         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
104230         p->cost.plan.wsFlags = flags;
104231         p->cost.plan.u.pTerm = pTerm;
104232       }
104233     }
104234   }
104235 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104236 }
104237
104238 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104239 /*
104240 ** Return TRUE if the WHERE clause term pTerm is of a form where it
104241 ** could be used with an index to access pSrc, assuming an appropriate
104242 ** index existed.
104243 */
104244 static int termCanDriveIndex(
104245   WhereTerm *pTerm,              /* WHERE clause term to check */
104246   struct SrcList_item *pSrc,     /* Table we are trying to access */
104247   Bitmask notReady               /* Tables in outer loops of the join */
104248 ){
104249   char aff;
104250   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104251   if( pTerm->eOperator!=WO_EQ ) return 0;
104252   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104253   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104254   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104255   return 1;
104256 }
104257 #endif
104258
104259 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104260 /*
104261 ** If the query plan for pSrc specified in pCost is a full table scan
104262 ** and indexing is allows (if there is no NOT INDEXED clause) and it
104263 ** possible to construct a transient index that would perform better
104264 ** than a full table scan even when the cost of constructing the index
104265 ** is taken into account, then alter the query plan to use the
104266 ** transient index.
104267 */
104268 static void bestAutomaticIndex(WhereBestIdx *p){
104269   Parse *pParse = p->pParse;            /* The parsing context */
104270   WhereClause *pWC = p->pWC;            /* The WHERE clause */
104271   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
104272   double nTableRow;                     /* Rows in the input table */
104273   double logN;                          /* log(nTableRow) */
104274   double costTempIdx;         /* per-query cost of the transient index */
104275   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104276   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104277   Table *pTable;              /* Table tht might be indexed */
104278
104279   if( pParse->nQueryLoop<=(double)1 ){
104280     /* There is no point in building an automatic index for a single scan */
104281     return;
104282   }
104283   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
104284     /* Automatic indices are disabled at run-time */
104285     return;
104286   }
104287   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
104288    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
104289   ){
104290     /* We already have some kind of index in use for this query. */
104291     return;
104292   }
104293   if( pSrc->viaCoroutine ){
104294     /* Cannot index a co-routine */
104295     return;
104296   }
104297   if( pSrc->notIndexed ){
104298     /* The NOT INDEXED clause appears in the SQL. */
104299     return;
104300   }
104301   if( pSrc->isCorrelated ){
104302     /* The source is a correlated sub-query. No point in indexing it. */
104303     return;
104304   }
104305
104306   assert( pParse->nQueryLoop >= (double)1 );
104307   pTable = pSrc->pTab;
104308   nTableRow = pTable->nRowEst;
104309   logN = estLog(nTableRow);
104310   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104311   if( costTempIdx>=p->cost.rCost ){
104312     /* The cost of creating the transient table would be greater than
104313     ** doing the full table scan */
104314     return;
104315   }
104316
104317   /* Search for any equality comparison term */
104318   pWCEnd = &pWC->a[pWC->nTerm];
104319   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104320     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
104321       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104322                     p->cost.rCost, costTempIdx));
104323       p->cost.rCost = costTempIdx;
104324       p->cost.plan.nRow = logN + 1;
104325       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
104326       p->cost.used = pTerm->prereqRight;
104327       break;
104328     }
104329   }
104330 }
104331 #else
104332 # define bestAutomaticIndex(A)  /* no-op */
104333 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104334
104335
104336 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104337 /*
104338 ** Generate code to construct the Index object for an automatic index
104339 ** and to set up the WhereLevel object pLevel so that the code generator
104340 ** makes use of the automatic index.
104341 */
104342 static void constructAutomaticIndex(
104343   Parse *pParse,              /* The parsing context */
104344   WhereClause *pWC,           /* The WHERE clause */
104345   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104346   Bitmask notReady,           /* Mask of cursors that are not available */
104347   WhereLevel *pLevel          /* Write new index here */
104348 ){
104349   int nColumn;                /* Number of columns in the constructed index */
104350   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104351   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104352   int nByte;                  /* Byte of memory needed for pIdx */
104353   Index *pIdx;                /* Object describing the transient index */
104354   Vdbe *v;                    /* Prepared statement under construction */
104355   int addrInit;               /* Address of the initialization bypass jump */
104356   Table *pTable;              /* The table being indexed */
104357   KeyInfo *pKeyinfo;          /* Key information for the index */   
104358   int addrTop;                /* Top of the index fill loop */
104359   int regRecord;              /* Register holding an index record */
104360   int n;                      /* Column counter */
104361   int i;                      /* Loop counter */
104362   int mxBitCol;               /* Maximum column in pSrc->colUsed */
104363   CollSeq *pColl;             /* Collating sequence to on a column */
104364   Bitmask idxCols;            /* Bitmap of columns used for indexing */
104365   Bitmask extraCols;          /* Bitmap of additional columns */
104366
104367   /* Generate code to skip over the creation and initialization of the
104368   ** transient index on 2nd and subsequent iterations of the loop. */
104369   v = pParse->pVdbe;
104370   assert( v!=0 );
104371   addrInit = sqlite3CodeOnce(pParse);
104372
104373   /* Count the number of columns that will be added to the index
104374   ** and used to match WHERE clause constraints */
104375   nColumn = 0;
104376   pTable = pSrc->pTab;
104377   pWCEnd = &pWC->a[pWC->nTerm];
104378   idxCols = 0;
104379   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104380     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104381       int iCol = pTerm->u.leftColumn;
104382       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104383       testcase( iCol==BMS );
104384       testcase( iCol==BMS-1 );
104385       if( (idxCols & cMask)==0 ){
104386         nColumn++;
104387         idxCols |= cMask;
104388       }
104389     }
104390   }
104391   assert( nColumn>0 );
104392   pLevel->plan.nEq = nColumn;
104393
104394   /* Count the number of additional columns needed to create a
104395   ** covering index.  A "covering index" is an index that contains all
104396   ** columns that are needed by the query.  With a covering index, the
104397   ** original table never needs to be accessed.  Automatic indices must
104398   ** be a covering index because the index will not be updated if the
104399   ** original table changes and the index and table cannot both be used
104400   ** if they go out of sync.
104401   */
104402   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104403   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104404   testcase( pTable->nCol==BMS-1 );
104405   testcase( pTable->nCol==BMS-2 );
104406   for(i=0; i<mxBitCol; i++){
104407     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104408   }
104409   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104410     nColumn += pTable->nCol - BMS + 1;
104411   }
104412   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104413
104414   /* Construct the Index object to describe this index */
104415   nByte = sizeof(Index);
104416   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104417   nByte += nColumn*sizeof(char*);   /* Index.azColl */
104418   nByte += nColumn;                 /* Index.aSortOrder */
104419   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
104420   if( pIdx==0 ) return;
104421   pLevel->plan.u.pIdx = pIdx;
104422   pIdx->azColl = (char**)&pIdx[1];
104423   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104424   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104425   pIdx->zName = "auto-index";
104426   pIdx->nColumn = nColumn;
104427   pIdx->pTable = pTable;
104428   n = 0;
104429   idxCols = 0;
104430   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104431     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104432       int iCol = pTerm->u.leftColumn;
104433       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104434       if( (idxCols & cMask)==0 ){
104435         Expr *pX = pTerm->pExpr;
104436         idxCols |= cMask;
104437         pIdx->aiColumn[n] = pTerm->u.leftColumn;
104438         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104439         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104440         n++;
104441       }
104442     }
104443   }
104444   assert( (u32)n==pLevel->plan.nEq );
104445
104446   /* Add additional columns needed to make the automatic index into
104447   ** a covering index */
104448   for(i=0; i<mxBitCol; i++){
104449     if( extraCols & (((Bitmask)1)<<i) ){
104450       pIdx->aiColumn[n] = i;
104451       pIdx->azColl[n] = "BINARY";
104452       n++;
104453     }
104454   }
104455   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104456     for(i=BMS-1; i<pTable->nCol; i++){
104457       pIdx->aiColumn[n] = i;
104458       pIdx->azColl[n] = "BINARY";
104459       n++;
104460     }
104461   }
104462   assert( n==nColumn );
104463
104464   /* Create the automatic index */
104465   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
104466   assert( pLevel->iIdxCur>=0 );
104467   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
104468                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
104469   VdbeComment((v, "for %s", pTable->zName));
104470
104471   /* Fill the automatic index with content */
104472   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
104473   regRecord = sqlite3GetTempReg(pParse);
104474   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
104475   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
104476   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104477   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
104478   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
104479   sqlite3VdbeJumpHere(v, addrTop);
104480   sqlite3ReleaseTempReg(pParse, regRecord);
104481   
104482   /* Jump here when skipping the initialization */
104483   sqlite3VdbeJumpHere(v, addrInit);
104484 }
104485 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104486
104487 #ifndef SQLITE_OMIT_VIRTUALTABLE
104488 /*
104489 ** Allocate and populate an sqlite3_index_info structure. It is the 
104490 ** responsibility of the caller to eventually release the structure
104491 ** by passing the pointer returned by this function to sqlite3_free().
104492 */
104493 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
104494   Parse *pParse = p->pParse; 
104495   WhereClause *pWC = p->pWC;
104496   struct SrcList_item *pSrc = p->pSrc;
104497   ExprList *pOrderBy = p->pOrderBy;
104498   int i, j;
104499   int nTerm;
104500   struct sqlite3_index_constraint *pIdxCons;
104501   struct sqlite3_index_orderby *pIdxOrderBy;
104502   struct sqlite3_index_constraint_usage *pUsage;
104503   WhereTerm *pTerm;
104504   int nOrderBy;
104505   sqlite3_index_info *pIdxInfo;
104506
104507   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
104508
104509   /* Count the number of possible WHERE clause constraints referring
104510   ** to this virtual table */
104511   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104512     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104513     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104514     testcase( pTerm->eOperator==WO_IN );
104515     testcase( pTerm->eOperator==WO_ISNULL );
104516     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104517     if( pTerm->wtFlags & TERM_VNULL ) continue;
104518     nTerm++;
104519   }
104520
104521   /* If the ORDER BY clause contains only columns in the current 
104522   ** virtual table then allocate space for the aOrderBy part of
104523   ** the sqlite3_index_info structure.
104524   */
104525   nOrderBy = 0;
104526   if( pOrderBy ){
104527     int n = pOrderBy->nExpr;
104528     for(i=0; i<n; i++){
104529       Expr *pExpr = pOrderBy->a[i].pExpr;
104530       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
104531     }
104532     if( i==n){
104533       nOrderBy = n;
104534     }
104535   }
104536
104537   /* Allocate the sqlite3_index_info structure
104538   */
104539   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
104540                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
104541                            + sizeof(*pIdxOrderBy)*nOrderBy );
104542   if( pIdxInfo==0 ){
104543     sqlite3ErrorMsg(pParse, "out of memory");
104544     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104545     return 0;
104546   }
104547
104548   /* Initialize the structure.  The sqlite3_index_info structure contains
104549   ** many fields that are declared "const" to prevent xBestIndex from
104550   ** changing them.  We have to do some funky casting in order to
104551   ** initialize those fields.
104552   */
104553   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
104554   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
104555   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
104556   *(int*)&pIdxInfo->nConstraint = nTerm;
104557   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
104558   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
104559   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
104560   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
104561                                                                    pUsage;
104562
104563   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104564     if( pTerm->leftCursor != pSrc->iCursor ) continue;
104565     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104566     testcase( pTerm->eOperator==WO_IN );
104567     testcase( pTerm->eOperator==WO_ISNULL );
104568     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104569     if( pTerm->wtFlags & TERM_VNULL ) continue;
104570     pIdxCons[j].iColumn = pTerm->u.leftColumn;
104571     pIdxCons[j].iTermOffset = i;
104572     pIdxCons[j].op = (u8)pTerm->eOperator;
104573     /* The direct assignment in the previous line is possible only because
104574     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
104575     ** following asserts verify this fact. */
104576     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
104577     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
104578     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
104579     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
104580     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
104581     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
104582     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
104583     j++;
104584   }
104585   for(i=0; i<nOrderBy; i++){
104586     Expr *pExpr = pOrderBy->a[i].pExpr;
104587     pIdxOrderBy[i].iColumn = pExpr->iColumn;
104588     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
104589   }
104590
104591   return pIdxInfo;
104592 }
104593
104594 /*
104595 ** The table object reference passed as the second argument to this function
104596 ** must represent a virtual table. This function invokes the xBestIndex()
104597 ** method of the virtual table with the sqlite3_index_info pointer passed
104598 ** as the argument.
104599 **
104600 ** If an error occurs, pParse is populated with an error message and a
104601 ** non-zero value is returned. Otherwise, 0 is returned and the output
104602 ** part of the sqlite3_index_info structure is left populated.
104603 **
104604 ** Whether or not an error is returned, it is the responsibility of the
104605 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
104606 ** that this is required.
104607 */
104608 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
104609   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
104610   int i;
104611   int rc;
104612
104613   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
104614   TRACE_IDX_INPUTS(p);
104615   rc = pVtab->pModule->xBestIndex(pVtab, p);
104616   TRACE_IDX_OUTPUTS(p);
104617
104618   if( rc!=SQLITE_OK ){
104619     if( rc==SQLITE_NOMEM ){
104620       pParse->db->mallocFailed = 1;
104621     }else if( !pVtab->zErrMsg ){
104622       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
104623     }else{
104624       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
104625     }
104626   }
104627   sqlite3_free(pVtab->zErrMsg);
104628   pVtab->zErrMsg = 0;
104629
104630   for(i=0; i<p->nConstraint; i++){
104631     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
104632       sqlite3ErrorMsg(pParse, 
104633           "table %s: xBestIndex returned an invalid plan", pTab->zName);
104634     }
104635   }
104636
104637   return pParse->nErr;
104638 }
104639
104640
104641 /*
104642 ** Compute the best index for a virtual table.
104643 **
104644 ** The best index is computed by the xBestIndex method of the virtual
104645 ** table module.  This routine is really just a wrapper that sets up
104646 ** the sqlite3_index_info structure that is used to communicate with
104647 ** xBestIndex.
104648 **
104649 ** In a join, this routine might be called multiple times for the
104650 ** same virtual table.  The sqlite3_index_info structure is created
104651 ** and initialized on the first invocation and reused on all subsequent
104652 ** invocations.  The sqlite3_index_info structure is also used when
104653 ** code is generated to access the virtual table.  The whereInfoDelete() 
104654 ** routine takes care of freeing the sqlite3_index_info structure after
104655 ** everybody has finished with it.
104656 */
104657 static void bestVirtualIndex(WhereBestIdx *p){
104658   Parse *pParse = p->pParse;      /* The parsing context */
104659   WhereClause *pWC = p->pWC;      /* The WHERE clause */
104660   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
104661   Table *pTab = pSrc->pTab;
104662   sqlite3_index_info *pIdxInfo;
104663   struct sqlite3_index_constraint *pIdxCons;
104664   struct sqlite3_index_constraint_usage *pUsage;
104665   WhereTerm *pTerm;
104666   int i, j;
104667   int nOrderBy;
104668   double rCost;
104669
104670   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
104671   ** malloc in allocateIndexInfo() fails and this function returns leaving
104672   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
104673   */
104674   memset(&p->cost, 0, sizeof(p->cost));
104675   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
104676
104677   /* If the sqlite3_index_info structure has not been previously
104678   ** allocated and initialized, then allocate and initialize it now.
104679   */
104680   pIdxInfo = *p->ppIdxInfo;
104681   if( pIdxInfo==0 ){
104682     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
104683   }
104684   if( pIdxInfo==0 ){
104685     return;
104686   }
104687
104688   /* At this point, the sqlite3_index_info structure that pIdxInfo points
104689   ** to will have been initialized, either during the current invocation or
104690   ** during some prior invocation.  Now we just have to customize the
104691   ** details of pIdxInfo for the current invocation and pass it to
104692   ** xBestIndex.
104693   */
104694
104695   /* The module name must be defined. Also, by this point there must
104696   ** be a pointer to an sqlite3_vtab structure. Otherwise
104697   ** sqlite3ViewGetColumnNames() would have picked up the error. 
104698   */
104699   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104700   assert( sqlite3GetVTable(pParse->db, pTab) );
104701
104702   /* Set the aConstraint[].usable fields and initialize all 
104703   ** output variables to zero.
104704   **
104705   ** aConstraint[].usable is true for constraints where the right-hand
104706   ** side contains only references to tables to the left of the current
104707   ** table.  In other words, if the constraint is of the form:
104708   **
104709   **           column = expr
104710   **
104711   ** and we are evaluating a join, then the constraint on column is 
104712   ** only valid if all tables referenced in expr occur to the left
104713   ** of the table containing column.
104714   **
104715   ** The aConstraints[] array contains entries for all constraints
104716   ** on the current table.  That way we only have to compute it once
104717   ** even though we might try to pick the best index multiple times.
104718   ** For each attempt at picking an index, the order of tables in the
104719   ** join might be different so we have to recompute the usable flag
104720   ** each time.
104721   */
104722   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104723   pUsage = pIdxInfo->aConstraintUsage;
104724   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104725     j = pIdxCons->iTermOffset;
104726     pTerm = &pWC->a[j];
104727     pIdxCons->usable = (pTerm->prereqRight&p->notReady) ? 0 : 1;
104728   }
104729   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104730   if( pIdxInfo->needToFreeIdxStr ){
104731     sqlite3_free(pIdxInfo->idxStr);
104732   }
104733   pIdxInfo->idxStr = 0;
104734   pIdxInfo->idxNum = 0;
104735   pIdxInfo->needToFreeIdxStr = 0;
104736   pIdxInfo->orderByConsumed = 0;
104737   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
104738   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
104739   nOrderBy = pIdxInfo->nOrderBy;
104740   if( !p->pOrderBy ){
104741     pIdxInfo->nOrderBy = 0;
104742   }
104743
104744   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104745     return;
104746   }
104747
104748   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104749   for(i=0; i<pIdxInfo->nConstraint; i++){
104750     if( pUsage[i].argvIndex>0 ){
104751       p->cost.used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104752     }
104753   }
104754
104755   /* If there is an ORDER BY clause, and the selected virtual table index
104756   ** does not satisfy it, increase the cost of the scan accordingly. This
104757   ** matches the processing for non-virtual tables in bestBtreeIndex().
104758   */
104759   rCost = pIdxInfo->estimatedCost;
104760   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
104761     rCost += estLog(rCost)*rCost;
104762   }
104763
104764   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
104765   ** inital value of lowestCost in this loop. If it is, then the
104766   ** (cost<lowestCost) test below will never be true.
104767   ** 
104768   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
104769   ** is defined.
104770   */
104771   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
104772     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
104773   }else{
104774     p->cost.rCost = rCost;
104775   }
104776   p->cost.plan.u.pVtabIdx = pIdxInfo;
104777   if( pIdxInfo->orderByConsumed ){
104778     p->cost.plan.wsFlags |= WHERE_ORDERED;
104779     p->cost.plan.nOBSat = nOrderBy;
104780   }else{
104781     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
104782   }
104783   p->cost.plan.nEq = 0;
104784   pIdxInfo->nOrderBy = nOrderBy;
104785
104786   /* Try to find a more efficient access pattern by using multiple indexes
104787   ** to optimize an OR expression within the WHERE clause. 
104788   */
104789   bestOrClauseIndex(p);
104790 }
104791 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104792
104793 #ifdef SQLITE_ENABLE_STAT3
104794 /*
104795 ** Estimate the location of a particular key among all keys in an
104796 ** index.  Store the results in aStat as follows:
104797 **
104798 **    aStat[0]      Est. number of rows less than pVal
104799 **    aStat[1]      Est. number of rows equal to pVal
104800 **
104801 ** Return SQLITE_OK on success.
104802 */
104803 static int whereKeyStats(
104804   Parse *pParse,              /* Database connection */
104805   Index *pIdx,                /* Index to consider domain of */
104806   sqlite3_value *pVal,        /* Value to consider */
104807   int roundUp,                /* Round up if true.  Round down if false */
104808   tRowcnt *aStat              /* OUT: stats written here */
104809 ){
104810   tRowcnt n;
104811   IndexSample *aSample;
104812   int i, eType;
104813   int isEq = 0;
104814   i64 v;
104815   double r, rS;
104816
104817   assert( roundUp==0 || roundUp==1 );
104818   assert( pIdx->nSample>0 );
104819   if( pVal==0 ) return SQLITE_ERROR;
104820   n = pIdx->aiRowEst[0];
104821   aSample = pIdx->aSample;
104822   eType = sqlite3_value_type(pVal);
104823
104824   if( eType==SQLITE_INTEGER ){
104825     v = sqlite3_value_int64(pVal);
104826     r = (i64)v;
104827     for(i=0; i<pIdx->nSample; i++){
104828       if( aSample[i].eType==SQLITE_NULL ) continue;
104829       if( aSample[i].eType>=SQLITE_TEXT ) break;
104830       if( aSample[i].eType==SQLITE_INTEGER ){
104831         if( aSample[i].u.i>=v ){
104832           isEq = aSample[i].u.i==v;
104833           break;
104834         }
104835       }else{
104836         assert( aSample[i].eType==SQLITE_FLOAT );
104837         if( aSample[i].u.r>=r ){
104838           isEq = aSample[i].u.r==r;
104839           break;
104840         }
104841       }
104842     }
104843   }else if( eType==SQLITE_FLOAT ){
104844     r = sqlite3_value_double(pVal);
104845     for(i=0; i<pIdx->nSample; i++){
104846       if( aSample[i].eType==SQLITE_NULL ) continue;
104847       if( aSample[i].eType>=SQLITE_TEXT ) break;
104848       if( aSample[i].eType==SQLITE_FLOAT ){
104849         rS = aSample[i].u.r;
104850       }else{
104851         rS = aSample[i].u.i;
104852       }
104853       if( rS>=r ){
104854         isEq = rS==r;
104855         break;
104856       }
104857     }
104858   }else if( eType==SQLITE_NULL ){
104859     i = 0;
104860     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
104861   }else{
104862     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
104863     for(i=0; i<pIdx->nSample; i++){
104864       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
104865         break;
104866       }
104867     }
104868     if( i<pIdx->nSample ){      
104869       sqlite3 *db = pParse->db;
104870       CollSeq *pColl;
104871       const u8 *z;
104872       if( eType==SQLITE_BLOB ){
104873         z = (const u8 *)sqlite3_value_blob(pVal);
104874         pColl = db->pDfltColl;
104875         assert( pColl->enc==SQLITE_UTF8 );
104876       }else{
104877         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
104878         if( pColl==0 ){
104879           return SQLITE_ERROR;
104880         }
104881         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
104882         if( !z ){
104883           return SQLITE_NOMEM;
104884         }
104885         assert( z && pColl && pColl->xCmp );
104886       }
104887       n = sqlite3ValueBytes(pVal, pColl->enc);
104888   
104889       for(; i<pIdx->nSample; i++){
104890         int c;
104891         int eSampletype = aSample[i].eType;
104892         if( eSampletype<eType ) continue;
104893         if( eSampletype!=eType ) break;
104894 #ifndef SQLITE_OMIT_UTF16
104895         if( pColl->enc!=SQLITE_UTF8 ){
104896           int nSample;
104897           char *zSample = sqlite3Utf8to16(
104898               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
104899           );
104900           if( !zSample ){
104901             assert( db->mallocFailed );
104902             return SQLITE_NOMEM;
104903           }
104904           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
104905           sqlite3DbFree(db, zSample);
104906         }else
104907 #endif
104908         {
104909           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
104910         }
104911         if( c>=0 ){
104912           if( c==0 ) isEq = 1;
104913           break;
104914         }
104915       }
104916     }
104917   }
104918
104919   /* At this point, aSample[i] is the first sample that is greater than
104920   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
104921   ** than pVal.  If aSample[i]==pVal, then isEq==1.
104922   */
104923   if( isEq ){
104924     assert( i<pIdx->nSample );
104925     aStat[0] = aSample[i].nLt;
104926     aStat[1] = aSample[i].nEq;
104927   }else{
104928     tRowcnt iLower, iUpper, iGap;
104929     if( i==0 ){
104930       iLower = 0;
104931       iUpper = aSample[0].nLt;
104932     }else{
104933       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
104934       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
104935     }
104936     aStat[1] = pIdx->avgEq;
104937     if( iLower>=iUpper ){
104938       iGap = 0;
104939     }else{
104940       iGap = iUpper - iLower;
104941     }
104942     if( roundUp ){
104943       iGap = (iGap*2)/3;
104944     }else{
104945       iGap = iGap/3;
104946     }
104947     aStat[0] = iLower + iGap;
104948   }
104949   return SQLITE_OK;
104950 }
104951 #endif /* SQLITE_ENABLE_STAT3 */
104952
104953 /*
104954 ** If expression pExpr represents a literal value, set *pp to point to
104955 ** an sqlite3_value structure containing the same value, with affinity
104956 ** aff applied to it, before returning. It is the responsibility of the 
104957 ** caller to eventually release this structure by passing it to 
104958 ** sqlite3ValueFree().
104959 **
104960 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
104961 ** is an SQL variable that currently has a non-NULL value bound to it,
104962 ** create an sqlite3_value structure containing this value, again with
104963 ** affinity aff applied to it, instead.
104964 **
104965 ** If neither of the above apply, set *pp to NULL.
104966 **
104967 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
104968 */
104969 #ifdef SQLITE_ENABLE_STAT3
104970 static int valueFromExpr(
104971   Parse *pParse, 
104972   Expr *pExpr, 
104973   u8 aff, 
104974   sqlite3_value **pp
104975 ){
104976   if( pExpr->op==TK_VARIABLE
104977    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
104978   ){
104979     int iVar = pExpr->iColumn;
104980     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
104981     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
104982     return SQLITE_OK;
104983   }
104984   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
104985 }
104986 #endif
104987
104988 /*
104989 ** This function is used to estimate the number of rows that will be visited
104990 ** by scanning an index for a range of values. The range may have an upper
104991 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
104992 ** and lower bounds are represented by pLower and pUpper respectively. For
104993 ** example, assuming that index p is on t1(a):
104994 **
104995 **   ... FROM t1 WHERE a > ? AND a < ? ...
104996 **                    |_____|   |_____|
104997 **                       |         |
104998 **                     pLower    pUpper
104999 **
105000 ** If either of the upper or lower bound is not present, then NULL is passed in
105001 ** place of the corresponding WhereTerm.
105002 **
105003 ** The nEq parameter is passed the index of the index column subject to the
105004 ** range constraint. Or, equivalently, the number of equality constraints
105005 ** optimized by the proposed index scan. For example, assuming index p is
105006 ** on t1(a, b), and the SQL query is:
105007 **
105008 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
105009 **
105010 ** then nEq should be passed the value 1 (as the range restricted column,
105011 ** b, is the second left-most column of the index). Or, if the query is:
105012 **
105013 **   ... FROM t1 WHERE a > ? AND a < ? ...
105014 **
105015 ** then nEq should be passed 0.
105016 **
105017 ** The returned value is an integer divisor to reduce the estimated
105018 ** search space.  A return value of 1 means that range constraints are
105019 ** no help at all.  A return value of 2 means range constraints are
105020 ** expected to reduce the search space by half.  And so forth...
105021 **
105022 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
105023 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
105024 ** results in a return of 4 and a range constraint (x>? AND x<?) results
105025 ** in a return of 16.
105026 */
105027 static int whereRangeScanEst(
105028   Parse *pParse,       /* Parsing & code generating context */
105029   Index *p,            /* The index containing the range-compared column; "x" */
105030   int nEq,             /* index into p->aCol[] of the range-compared column */
105031   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
105032   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
105033   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
105034 ){
105035   int rc = SQLITE_OK;
105036
105037 #ifdef SQLITE_ENABLE_STAT3
105038
105039   if( nEq==0 && p->nSample ){
105040     sqlite3_value *pRangeVal;
105041     tRowcnt iLower = 0;
105042     tRowcnt iUpper = p->aiRowEst[0];
105043     tRowcnt a[2];
105044     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105045
105046     if( pLower ){
105047       Expr *pExpr = pLower->pExpr->pRight;
105048       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105049       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
105050       if( rc==SQLITE_OK
105051        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
105052       ){
105053         iLower = a[0];
105054         if( pLower->eOperator==WO_GT ) iLower += a[1];
105055       }
105056       sqlite3ValueFree(pRangeVal);
105057     }
105058     if( rc==SQLITE_OK && pUpper ){
105059       Expr *pExpr = pUpper->pExpr->pRight;
105060       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105061       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
105062       if( rc==SQLITE_OK
105063        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
105064       ){
105065         iUpper = a[0];
105066         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
105067       }
105068       sqlite3ValueFree(pRangeVal);
105069     }
105070     if( rc==SQLITE_OK ){
105071       if( iUpper<=iLower ){
105072         *pRangeDiv = (double)p->aiRowEst[0];
105073       }else{
105074         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
105075       }
105076       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
105077                   (u32)iLower, (u32)iUpper, *pRangeDiv));
105078       return SQLITE_OK;
105079     }
105080   }
105081 #else
105082   UNUSED_PARAMETER(pParse);
105083   UNUSED_PARAMETER(p);
105084   UNUSED_PARAMETER(nEq);
105085 #endif
105086   assert( pLower || pUpper );
105087   *pRangeDiv = (double)1;
105088   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
105089   if( pUpper ) *pRangeDiv *= (double)4;
105090   return rc;
105091 }
105092
105093 #ifdef SQLITE_ENABLE_STAT3
105094 /*
105095 ** Estimate the number of rows that will be returned based on
105096 ** an equality constraint x=VALUE and where that VALUE occurs in
105097 ** the histogram data.  This only works when x is the left-most
105098 ** column of an index and sqlite_stat3 histogram data is available
105099 ** for that index.  When pExpr==NULL that means the constraint is
105100 ** "x IS NULL" instead of "x=VALUE".
105101 **
105102 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
105103 ** If unable to make an estimate, leave *pnRow unchanged and return
105104 ** non-zero.
105105 **
105106 ** This routine can fail if it is unable to load a collating sequence
105107 ** required for string comparison, or if unable to allocate memory
105108 ** for a UTF conversion required for comparison.  The error is stored
105109 ** in the pParse structure.
105110 */
105111 static int whereEqualScanEst(
105112   Parse *pParse,       /* Parsing & code generating context */
105113   Index *p,            /* The index whose left-most column is pTerm */
105114   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
105115   double *pnRow        /* Write the revised row estimate here */
105116 ){
105117   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
105118   u8 aff;                   /* Column affinity */
105119   int rc;                   /* Subfunction return code */
105120   tRowcnt a[2];             /* Statistics */
105121
105122   assert( p->aSample!=0 );
105123   assert( p->nSample>0 );
105124   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105125   if( pExpr ){
105126     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
105127     if( rc ) goto whereEqualScanEst_cancel;
105128   }else{
105129     pRhs = sqlite3ValueNew(pParse->db);
105130   }
105131   if( pRhs==0 ) return SQLITE_NOTFOUND;
105132   rc = whereKeyStats(pParse, p, pRhs, 0, a);
105133   if( rc==SQLITE_OK ){
105134     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
105135     *pnRow = a[1];
105136   }
105137 whereEqualScanEst_cancel:
105138   sqlite3ValueFree(pRhs);
105139   return rc;
105140 }
105141 #endif /* defined(SQLITE_ENABLE_STAT3) */
105142
105143 #ifdef SQLITE_ENABLE_STAT3
105144 /*
105145 ** Estimate the number of rows that will be returned based on
105146 ** an IN constraint where the right-hand side of the IN operator
105147 ** is a list of values.  Example:
105148 **
105149 **        WHERE x IN (1,2,3,4)
105150 **
105151 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
105152 ** If unable to make an estimate, leave *pnRow unchanged and return
105153 ** non-zero.
105154 **
105155 ** This routine can fail if it is unable to load a collating sequence
105156 ** required for string comparison, or if unable to allocate memory
105157 ** for a UTF conversion required for comparison.  The error is stored
105158 ** in the pParse structure.
105159 */
105160 static int whereInScanEst(
105161   Parse *pParse,       /* Parsing & code generating context */
105162   Index *p,            /* The index whose left-most column is pTerm */
105163   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
105164   double *pnRow        /* Write the revised row estimate here */
105165 ){
105166   int rc = SQLITE_OK;         /* Subfunction return code */
105167   double nEst;                /* Number of rows for a single term */
105168   double nRowEst = (double)0; /* New estimate of the number of rows */
105169   int i;                      /* Loop counter */
105170
105171   assert( p->aSample!=0 );
105172   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
105173     nEst = p->aiRowEst[0];
105174     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105175     nRowEst += nEst;
105176   }
105177   if( rc==SQLITE_OK ){
105178     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105179     *pnRow = nRowEst;
105180     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105181   }
105182   return rc;
105183 }
105184 #endif /* defined(SQLITE_ENABLE_STAT3) */
105185
105186 /*
105187 ** Check to see if column iCol of the table with cursor iTab will appear
105188 ** in sorted order according to the current query plan.
105189 **
105190 ** Return values:
105191 **
105192 **    0   iCol is not ordered
105193 **    1   iCol has only a single value
105194 **    2   iCol is in ASC order
105195 **    3   iCol is in DESC order
105196 */
105197 static int isOrderedColumn(
105198   WhereBestIdx *p,
105199   int iTab,
105200   int iCol
105201 ){
105202   int i, j;
105203   WhereLevel *pLevel = &p->aLevel[p->i-1];
105204   Index *pIdx;
105205   u8 sortOrder;
105206   for(i=p->i-1; i>=0; i--, pLevel--){
105207     if( pLevel->iTabCur!=iTab ) continue;
105208     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
105209       return 1;
105210     }
105211     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
105212     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
105213       if( iCol<0 ){
105214         sortOrder = 0;
105215         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105216       }else{
105217         int n = pIdx->nColumn;
105218         for(j=0; j<n; j++){
105219           if( iCol==pIdx->aiColumn[j] ) break;
105220         }
105221         if( j>=n ) return 0;
105222         sortOrder = pIdx->aSortOrder[j];
105223         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105224       }
105225     }else{
105226       if( iCol!=(-1) ) return 0;
105227       sortOrder = 0;
105228       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105229     }
105230     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
105231       assert( sortOrder==0 || sortOrder==1 );
105232       testcase( sortOrder==1 );
105233       sortOrder = 1 - sortOrder;
105234     }
105235     return sortOrder+2;
105236   }
105237   return 0;
105238 }
105239
105240 /*
105241 ** This routine decides if pIdx can be used to satisfy the ORDER BY
105242 ** clause, either in whole or in part.  The return value is the 
105243 ** cumulative number of terms in the ORDER BY clause that are satisfied
105244 ** by the index pIdx and other indices in outer loops.
105245 **
105246 ** The table being queried has a cursor number of "base".  pIdx is the
105247 ** index that is postulated for use to access the table.
105248 **
105249 ** The *pbRev value is set to 0 order 1 depending on whether or not
105250 ** pIdx should be run in the forward order or in reverse order.
105251 */
105252 static int isSortingIndex(
105253   WhereBestIdx *p,    /* Best index search context */
105254   Index *pIdx,        /* The index we are testing */
105255   int base,           /* Cursor number for the table to be sorted */
105256   int *pbRev          /* Set to 1 for reverse-order scan of pIdx */
105257 ){
105258   int i;                        /* Number of pIdx terms used */
105259   int j;                        /* Number of ORDER BY terms satisfied */
105260   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
105261   int nTerm;                    /* Number of ORDER BY terms */
105262   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
105263   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
105264   ExprList *pOrderBy;           /* The ORDER BY clause */
105265   Parse *pParse = p->pParse;    /* Parser context */
105266   sqlite3 *db = pParse->db;     /* Database connection */
105267   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
105268   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
105269   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
105270
105271   if( p->i==0 ){
105272     nPriorSat = 0;
105273   }else{
105274     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
105275     if( (p->aLevel[p->i-1].plan.wsFlags & WHERE_ORDERED)==0 ){
105276       /* This loop cannot be ordered unless the next outer loop is
105277       ** also ordered */
105278       return nPriorSat;
105279     }
105280     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
105281       /* Only look at the outer-most loop if the OrderByIdxJoin
105282       ** optimization is disabled */
105283       return nPriorSat;
105284     }
105285   }
105286   pOrderBy = p->pOrderBy;
105287   assert( pOrderBy!=0 );
105288   if( pIdx->bUnordered ){
105289     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
105290     ** be used for sorting */
105291     return nPriorSat;
105292   }
105293   nTerm = pOrderBy->nExpr;
105294   uniqueNotNull = pIdx->onError!=OE_None;
105295   assert( nTerm>0 );
105296
105297   /* Argument pIdx must either point to a 'real' named index structure, 
105298   ** or an index structure allocated on the stack by bestBtreeIndex() to
105299   ** represent the rowid index that is part of every table.  */
105300   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
105301
105302   /* Match terms of the ORDER BY clause against columns of
105303   ** the index.
105304   **
105305   ** Note that indices have pIdx->nColumn regular columns plus
105306   ** one additional column containing the rowid.  The rowid column
105307   ** of the index is also allowed to match against the ORDER BY
105308   ** clause.
105309   */
105310   j = nPriorSat;
105311   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
105312     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
105313     CollSeq *pColl;         /* The collating sequence of pOBExpr */
105314     int termSortOrder;      /* Sort order for this term */
105315     int iColumn;            /* The i-th column of the index.  -1 for rowid */
105316     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
105317     int isEq;               /* Subject to an == or IS NULL constraint */
105318     int isMatch;            /* ORDER BY term matches the index term */
105319     const char *zColl;      /* Name of collating sequence for i-th index term */
105320     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
105321
105322     /* If the next term of the ORDER BY clause refers to anything other than
105323     ** a column in the "base" table, then this index will not be of any
105324     ** further use in handling the ORDER BY. */
105325     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
105326     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
105327       break;
105328     }
105329
105330     /* Find column number and collating sequence for the next entry
105331     ** in the index */
105332     if( pIdx->zName && i<pIdx->nColumn ){
105333       iColumn = pIdx->aiColumn[i];
105334       if( iColumn==pIdx->pTable->iPKey ){
105335         iColumn = -1;
105336       }
105337       iSortOrder = pIdx->aSortOrder[i];
105338       zColl = pIdx->azColl[i];
105339       assert( zColl!=0 );
105340     }else{
105341       iColumn = -1;
105342       iSortOrder = 0;
105343       zColl = 0;
105344     }
105345
105346     /* Check to see if the column number and collating sequence of the
105347     ** index match the column number and collating sequence of the ORDER BY
105348     ** clause entry.  Set isMatch to 1 if they both match. */
105349     if( pOBExpr->iColumn==iColumn ){
105350       if( zColl ){
105351         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
105352         if( !pColl ) pColl = db->pDfltColl;
105353         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
105354       }else{
105355         isMatch = 1;
105356       }
105357     }else{
105358       isMatch = 0;
105359     }
105360
105361     /* termSortOrder is 0 or 1 for whether or not the access loop should
105362     ** run forward or backwards (respectively) in order to satisfy this 
105363     ** term of the ORDER BY clause. */
105364     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
105365     assert( iSortOrder==0 || iSortOrder==1 );
105366     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
105367
105368     /* If X is the column in the index and ORDER BY clause, check to see
105369     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
105370     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
105371                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
105372     if( pConstraint==0 ){
105373       isEq = 0;
105374     }else if( pConstraint->eOperator==WO_IN ){
105375       /* Constraints of the form: "X IN ..." cannot be used with an ORDER BY
105376       ** because we do not know in what order the values on the RHS of the IN
105377       ** operator will occur. */
105378       break;
105379     }else if( pConstraint->eOperator==WO_ISNULL ){
105380       uniqueNotNull = 0;
105381       isEq = 1;  /* "X IS NULL" means X has only a single value */
105382     }else if( pConstraint->prereqRight==0 ){
105383       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
105384     }else{
105385       Expr *pRight = pConstraint->pExpr->pRight;
105386       if( pRight->op==TK_COLUMN ){
105387         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
105388                     pRight->iTable, pRight->iColumn));
105389         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
105390         WHERETRACE((" -> isEq=%d\n", isEq));
105391
105392         /* If the constraint is of the form X=Y where Y is an ordered value
105393         ** in an outer loop, then make sure the sort order of Y matches the
105394         ** sort order required for X. */
105395         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
105396           testcase( isEq==2 );
105397           testcase( isEq==3 );
105398           break;
105399         }
105400       }else{
105401         isEq = 0;  /* "X=expr" places no ordering constraints on X */
105402       }
105403     }
105404     if( !isMatch ){
105405       if( isEq==0 ){
105406         break;
105407       }else{
105408         continue;
105409       }
105410     }else if( isEq!=1 ){
105411       if( sortOrder==2 ){
105412         sortOrder = termSortOrder;
105413       }else if( termSortOrder!=sortOrder ){
105414         break;
105415       }
105416     }
105417     j++;
105418     pOBItem++;
105419     if( iColumn<0 ){
105420       seenRowid = 1;
105421       break;
105422     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
105423       testcase( isEq==0 );
105424       testcase( isEq==2 );
105425       testcase( isEq==3 );
105426       uniqueNotNull = 0;
105427     }
105428   }
105429
105430   /* If we have not found at least one ORDER BY term that matches the
105431   ** index, then show no progress. */
105432   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
105433
105434   /* Return the necessary scan order back to the caller */
105435   *pbRev = sortOrder & 1;
105436
105437   /* If there was an "ORDER BY rowid" term that matched, or it is only
105438   ** possible for a single row from this table to match, then skip over
105439   ** any additional ORDER BY terms dealing with this table.
105440   */
105441   if( seenRowid || (uniqueNotNull && i>=pIdx->nColumn) ){
105442     /* Advance j over additional ORDER BY terms associated with base */
105443     WhereMaskSet *pMS = p->pWC->pMaskSet;
105444     Bitmask m = ~getMask(pMS, base);
105445     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
105446       j++;
105447     }
105448   }
105449   return j;
105450 }
105451
105452 /*
105453 ** Find the best query plan for accessing a particular table.  Write the
105454 ** best query plan and its cost into the p->cost.
105455 **
105456 ** The lowest cost plan wins.  The cost is an estimate of the amount of
105457 ** CPU and disk I/O needed to process the requested result.
105458 ** Factors that influence cost include:
105459 **
105460 **    *  The estimated number of rows that will be retrieved.  (The
105461 **       fewer the better.)
105462 **
105463 **    *  Whether or not sorting must occur.
105464 **
105465 **    *  Whether or not there must be separate lookups in the
105466 **       index and in the main table.
105467 **
105468 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
105469 ** the SQL statement, then this function only considers plans using the 
105470 ** named index. If no such plan is found, then the returned cost is
105471 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
105472 ** then the cost is calculated in the usual way.
105473 **
105474 ** If a NOT INDEXED clause was attached to the table 
105475 ** in the SELECT statement, then no indexes are considered. However, the 
105476 ** selected plan may still take advantage of the built-in rowid primary key
105477 ** index.
105478 */
105479 static void bestBtreeIndex(WhereBestIdx *p){
105480   Parse *pParse = p->pParse;  /* The parsing context */
105481   WhereClause *pWC = p->pWC;  /* The WHERE clause */
105482   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
105483   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105484   Index *pProbe;              /* An index we are evaluating */
105485   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
105486   int eqTermMask;             /* Current mask of valid equality operators */
105487   int idxEqTermMask;          /* Index mask of valid equality operators */
105488   Index sPk;                  /* A fake index object for the primary key */
105489   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
105490   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
105491   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
105492   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
105493   int nOrderBy;               /* Number of ORDER BY terms */
105494   char bSortInit;             /* Initializer for bSort in inner loop */
105495   char bDistInit;             /* Initializer for bDist in inner loop */
105496
105497
105498   /* Initialize the cost to a worst-case value */
105499   memset(&p->cost, 0, sizeof(p->cost));
105500   p->cost.rCost = SQLITE_BIG_DBL;
105501
105502   /* If the pSrc table is the right table of a LEFT JOIN then we may not
105503   ** use an index to satisfy IS NULL constraints on that table.  This is
105504   ** because columns might end up being NULL if the table does not match -
105505   ** a circumstance which the index cannot help us discover.  Ticket #2177.
105506   */
105507   if( pSrc->jointype & JT_LEFT ){
105508     idxEqTermMask = WO_EQ|WO_IN;
105509   }else{
105510     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
105511   }
105512
105513   if( pSrc->pIndex ){
105514     /* An INDEXED BY clause specifies a particular index to use */
105515     pIdx = pProbe = pSrc->pIndex;
105516     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105517     eqTermMask = idxEqTermMask;
105518   }else{
105519     /* There is no INDEXED BY clause.  Create a fake Index object in local
105520     ** variable sPk to represent the rowid primary key index.  Make this
105521     ** fake index the first in a chain of Index objects with all of the real
105522     ** indices to follow */
105523     Index *pFirst;                  /* First of real indices on the table */
105524     memset(&sPk, 0, sizeof(Index));
105525     sPk.nColumn = 1;
105526     sPk.aiColumn = &aiColumnPk;
105527     sPk.aiRowEst = aiRowEstPk;
105528     sPk.onError = OE_Replace;
105529     sPk.pTable = pSrc->pTab;
105530     aiRowEstPk[0] = pSrc->pTab->nRowEst;
105531     aiRowEstPk[1] = 1;
105532     pFirst = pSrc->pTab->pIndex;
105533     if( pSrc->notIndexed==0 ){
105534       /* The real indices of the table are only considered if the
105535       ** NOT INDEXED qualifier is omitted from the FROM clause */
105536       sPk.pNext = pFirst;
105537     }
105538     pProbe = &sPk;
105539     wsFlagMask = ~(
105540         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
105541     );
105542     eqTermMask = WO_EQ|WO_IN;
105543     pIdx = 0;
105544   }
105545
105546   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
105547   if( p->i ){
105548     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
105549     bSortInit = nPriorSat<nOrderBy;
105550     bDistInit = 0;
105551   }else{
105552     nPriorSat = 0;
105553     bSortInit = nOrderBy>0;
105554     bDistInit = p->pDistinct!=0;
105555   }
105556
105557   /* Loop over all indices looking for the best one to use
105558   */
105559   for(; pProbe; pIdx=pProbe=pProbe->pNext){
105560     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
105561     WhereCost pc;               /* Cost of using pProbe */
105562     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
105563
105564     /* The following variables are populated based on the properties of
105565     ** index being evaluated. They are then used to determine the expected
105566     ** cost and number of rows returned.
105567     **
105568     **  pc.plan.nEq: 
105569     **    Number of equality terms that can be implemented using the index.
105570     **    In other words, the number of initial fields in the index that
105571     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
105572     **
105573     **  nInMul:  
105574     **    The "in-multiplier". This is an estimate of how many seek operations 
105575     **    SQLite must perform on the index in question. For example, if the 
105576     **    WHERE clause is:
105577     **
105578     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
105579     **
105580     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
105581     **    set to 9. Given the same schema and either of the following WHERE 
105582     **    clauses:
105583     **
105584     **      WHERE a =  1
105585     **      WHERE a >= 2
105586     **
105587     **    nInMul is set to 1.
105588     **
105589     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
105590     **    the sub-select is assumed to return 25 rows for the purposes of 
105591     **    determining nInMul.
105592     **
105593     **  bInEst:  
105594     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
105595     **    in determining the value of nInMul.  Note that the RHS of the
105596     **    IN operator must be a SELECT, not a value list, for this variable
105597     **    to be true.
105598     **
105599     **  rangeDiv:
105600     **    An estimate of a divisor by which to reduce the search space due
105601     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
105602     **    data, a single inequality reduces the search space to 1/4rd its
105603     **    original size (rangeDiv==4).  Two inequalities reduce the search
105604     **    space to 1/16th of its original size (rangeDiv==16).
105605     **
105606     **  bSort:   
105607     **    Boolean. True if there is an ORDER BY clause that will require an 
105608     **    external sort (i.e. scanning the index being evaluated will not 
105609     **    correctly order records).
105610     **
105611     **  bDist:
105612     **    Boolean. True if there is a DISTINCT clause that will require an 
105613     **    external btree.
105614     **
105615     **  bLookup: 
105616     **    Boolean. True if a table lookup is required for each index entry
105617     **    visited.  In other words, true if this is not a covering index.
105618     **    This is always false for the rowid primary key index of a table.
105619     **    For other indexes, it is true unless all the columns of the table
105620     **    used by the SELECT statement are present in the index (such an
105621     **    index is sometimes described as a covering index).
105622     **    For example, given the index on (a, b), the second of the following 
105623     **    two queries requires table b-tree lookups in order to find the value
105624     **    of column c, but the first does not because columns a and b are
105625     **    both available in the index.
105626     **
105627     **             SELECT a, b    FROM tbl WHERE a = 1;
105628     **             SELECT a, b, c FROM tbl WHERE a = 1;
105629     */
105630     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
105631     int nInMul = 1;               /* Number of distinct equalities to lookup */
105632     double rangeDiv = (double)1;  /* Estimated reduction in search space */
105633     int nBound = 0;               /* Number of range constraints seen */
105634     char bSort = bSortInit;       /* True if external sort required */
105635     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
105636     char bLookup = 0;             /* True if not a covering index */
105637     WhereTerm *pTerm;             /* A single term of the WHERE clause */
105638 #ifdef SQLITE_ENABLE_STAT3
105639     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
105640 #endif
105641
105642     WHERETRACE((
105643       "   %s(%s):\n",
105644       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
105645     ));
105646     memset(&pc, 0, sizeof(pc));
105647     pc.plan.nOBSat = nPriorSat;
105648
105649     /* Determine the values of pc.plan.nEq and nInMul */
105650     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
105651       int j = pProbe->aiColumn[pc.plan.nEq];
105652       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
105653       if( pTerm==0 ) break;
105654       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
105655       testcase( pTerm->pWC!=pWC );
105656       if( pTerm->eOperator & WO_IN ){
105657         Expr *pExpr = pTerm->pExpr;
105658         pc.plan.wsFlags |= WHERE_COLUMN_IN;
105659         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105660           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
105661           nInMul *= 25;
105662           bInEst = 1;
105663         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
105664           /* "x IN (value, value, ...)" */
105665           nInMul *= pExpr->x.pList->nExpr;
105666         }
105667       }else if( pTerm->eOperator & WO_ISNULL ){
105668         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
105669       }
105670 #ifdef SQLITE_ENABLE_STAT3
105671       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
105672 #endif
105673       pc.used |= pTerm->prereqRight;
105674     }
105675  
105676     /* If the index being considered is UNIQUE, and there is an equality 
105677     ** constraint for all columns in the index, then this search will find
105678     ** at most a single row. In this case set the WHERE_UNIQUE flag to 
105679     ** indicate this to the caller.
105680     **
105681     ** Otherwise, if the search may find more than one row, test to see if
105682     ** there is a range constraint on indexed column (pc.plan.nEq+1) that can be 
105683     ** optimized using the index. 
105684     */
105685     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
105686       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
105687       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
105688       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
105689         pc.plan.wsFlags |= WHERE_UNIQUE;
105690         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
105691           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
105692         }
105693       }
105694     }else if( pProbe->bUnordered==0 ){
105695       int j;
105696       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
105697       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
105698         WhereTerm *pTop, *pBtm;
105699         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
105700         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
105701         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
105702         if( pTop ){
105703           nBound = 1;
105704           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
105705           pc.used |= pTop->prereqRight;
105706           testcase( pTop->pWC!=pWC );
105707         }
105708         if( pBtm ){
105709           nBound++;
105710           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
105711           pc.used |= pBtm->prereqRight;
105712           testcase( pBtm->pWC!=pWC );
105713         }
105714         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
105715       }
105716     }
105717
105718     /* If there is an ORDER BY clause and the index being considered will
105719     ** naturally scan rows in the required order, set the appropriate flags
105720     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
105721     ** the index will scan rows in a different order, set the bSort
105722     ** variable.  */
105723     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
105724       int bRev = 2;
105725       WHERETRACE(("      --> before isSortingIndex: nPriorSat=%d\n",nPriorSat));
105726       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev);
105727       WHERETRACE(("      --> after  isSortingIndex: bRev=%d nOBSat=%d\n",
105728                   bRev, pc.plan.nOBSat));
105729       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_UNIQUE)!=0 ){
105730         pc.plan.wsFlags |= WHERE_ORDERED;
105731       }
105732       if( nOrderBy==pc.plan.nOBSat ){
105733         bSort = 0;
105734         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
105735       }
105736       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
105737     }
105738
105739     /* If there is a DISTINCT qualifier and this index will scan rows in
105740     ** order of the DISTINCT expressions, clear bDist and set the appropriate
105741     ** flags in pc.plan.wsFlags. */
105742     if( bDist
105743      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
105744      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
105745     ){
105746       bDist = 0;
105747       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
105748     }
105749
105750     /* If currently calculating the cost of using an index (not the IPK
105751     ** index), determine if all required column data may be obtained without 
105752     ** using the main table (i.e. if the index is a covering
105753     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
105754     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
105755     if( pIdx ){
105756       Bitmask m = pSrc->colUsed;
105757       int j;
105758       for(j=0; j<pIdx->nColumn; j++){
105759         int x = pIdx->aiColumn[j];
105760         if( x<BMS-1 ){
105761           m &= ~(((Bitmask)1)<<x);
105762         }
105763       }
105764       if( m==0 ){
105765         pc.plan.wsFlags |= WHERE_IDX_ONLY;
105766       }else{
105767         bLookup = 1;
105768       }
105769     }
105770
105771     /*
105772     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
105773     ** constraint, do not let the estimate exceed half the rows in the table.
105774     */
105775     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
105776     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
105777       pc.plan.nRow = aiRowEst[0]/2;
105778       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
105779     }
105780
105781 #ifdef SQLITE_ENABLE_STAT3
105782     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
105783     ** and we do not think that values of x are unique and if histogram
105784     ** data is available for column x, then it might be possible
105785     ** to get a better estimate on the number of rows based on
105786     ** VALUE and how common that value is according to the histogram.
105787     */
105788     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
105789      && pFirstTerm!=0 && aiRowEst[1]>1 ){
105790       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
105791       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
105792         testcase( pFirstTerm->eOperator==WO_EQ );
105793         testcase( pFirstTerm->eOperator==WO_ISNULL );
105794         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
105795                           &pc.plan.nRow);
105796       }else if( bInEst==0 ){
105797         assert( pFirstTerm->eOperator==WO_IN );
105798         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
105799                        &pc.plan.nRow);
105800       }
105801     }
105802 #endif /* SQLITE_ENABLE_STAT3 */
105803
105804     /* Adjust the number of output rows and downward to reflect rows
105805     ** that are excluded by range constraints.
105806     */
105807     pc.plan.nRow = pc.plan.nRow/rangeDiv;
105808     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
105809
105810     /* Experiments run on real SQLite databases show that the time needed
105811     ** to do a binary search to locate a row in a table or index is roughly
105812     ** log10(N) times the time to move from one row to the next row within
105813     ** a table or index.  The actual times can vary, with the size of
105814     ** records being an important factor.  Both moves and searches are
105815     ** slower with larger records, presumably because fewer records fit
105816     ** on one page and hence more pages have to be fetched.
105817     **
105818     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
105819     ** not give us data on the relative sizes of table and index records.
105820     ** So this computation assumes table records are about twice as big
105821     ** as index records
105822     */
105823     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED))==WHERE_IDX_ONLY
105824      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
105825      && sqlite3GlobalConfig.bUseCis
105826      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
105827     ){
105828       /* This index is not useful for indexing, but it is a covering index.
105829       ** A full-scan of the index might be a little faster than a full-scan
105830       ** of the table, so give this case a cost slightly less than a table
105831       ** scan. */
105832       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
105833       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
105834     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105835       /* The cost of a full table scan is a number of move operations equal
105836       ** to the number of rows in the table.
105837       **
105838       ** We add an additional 4x penalty to full table scans.  This causes
105839       ** the cost function to err on the side of choosing an index over
105840       ** choosing a full scan.  This 4x full-scan penalty is an arguable
105841       ** decision and one which we expect to revisit in the future.  But
105842       ** it seems to be working well enough at the moment.
105843       */
105844       pc.rCost = aiRowEst[0]*4;
105845       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
105846       if( pIdx ){
105847         pc.plan.wsFlags &= ~WHERE_ORDERED;
105848         pc.plan.nOBSat = nPriorSat;
105849       }
105850     }else{
105851       log10N = estLog(aiRowEst[0]);
105852       pc.rCost = pc.plan.nRow;
105853       if( pIdx ){
105854         if( bLookup ){
105855           /* For an index lookup followed by a table lookup:
105856           **    nInMul index searches to find the start of each index range
105857           **  + nRow steps through the index
105858           **  + nRow table searches to lookup the table entry using the rowid
105859           */
105860           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
105861         }else{
105862           /* For a covering index:
105863           **     nInMul index searches to find the initial entry 
105864           **   + nRow steps through the index
105865           */
105866           pc.rCost += nInMul*log10N;
105867         }
105868       }else{
105869         /* For a rowid primary key lookup:
105870         **    nInMult table searches to find the initial entry for each range
105871         **  + nRow steps through the table
105872         */
105873         pc.rCost += nInMul*log10N;
105874       }
105875     }
105876
105877     /* Add in the estimated cost of sorting the result.  Actual experimental
105878     ** measurements of sorting performance in SQLite show that sorting time
105879     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
105880     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
105881     ** difference and select C of 3.0.
105882     */
105883     if( bSort ){
105884       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
105885       m *= (double)(pc.plan.nOBSat ? 2 : 3);
105886       pc.rCost += pc.plan.nRow*m;
105887     }
105888     if( bDist ){
105889       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
105890     }
105891
105892     /**** Cost of using this index has now been computed ****/
105893
105894     /* If there are additional constraints on this table that cannot
105895     ** be used with the current index, but which might lower the number
105896     ** of output rows, adjust the nRow value accordingly.  This only 
105897     ** matters if the current index is the least costly, so do not bother
105898     ** with this step if we already know this index will not be chosen.
105899     ** Also, never reduce the output row count below 2 using this step.
105900     **
105901     ** It is critical that the notValid mask be used here instead of
105902     ** the notReady mask.  When computing an "optimal" index, the notReady
105903     ** mask will only have one bit set - the bit for the current table.
105904     ** The notValid mask, on the other hand, always has all bits set for
105905     ** tables that are not in outer loops.  If notReady is used here instead
105906     ** of notValid, then a optimal index that depends on inner joins loops
105907     ** might be selected even when there exists an optimal index that has
105908     ** no such dependency.
105909     */
105910     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
105911       int k;                       /* Loop counter */
105912       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
105913       int nSkipRange = nBound;     /* Number of < constraints to skip */
105914       Bitmask thisTab;             /* Bitmap for pSrc */
105915
105916       thisTab = getMask(pWC->pMaskSet, iCur);
105917       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
105918         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
105919         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
105920         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
105921           if( nSkipEq ){
105922             /* Ignore the first pc.plan.nEq equality matches since the index
105923             ** has already accounted for these */
105924             nSkipEq--;
105925           }else{
105926             /* Assume each additional equality match reduces the result
105927             ** set size by a factor of 10 */
105928             pc.plan.nRow /= 10;
105929           }
105930         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
105931           if( nSkipRange ){
105932             /* Ignore the first nSkipRange range constraints since the index
105933             ** has already accounted for these */
105934             nSkipRange--;
105935           }else{
105936             /* Assume each additional range constraint reduces the result
105937             ** set size by a factor of 3.  Indexed range constraints reduce
105938             ** the search space by a larger factor: 4.  We make indexed range
105939             ** more selective intentionally because of the subjective 
105940             ** observation that indexed range constraints really are more
105941             ** selective in practice, on average. */
105942             pc.plan.nRow /= 3;
105943           }
105944         }else if( pTerm->eOperator!=WO_NOOP ){
105945           /* Any other expression lowers the output row count by half */
105946           pc.plan.nRow /= 2;
105947         }
105948       }
105949       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
105950     }
105951
105952
105953     WHERETRACE((
105954       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
105955       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
105956       "      used=0x%llx nOBSat=%d\n",
105957       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
105958       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
105959       pc.plan.nOBSat
105960     ));
105961
105962     /* If this index is the best we have seen so far, then record this
105963     ** index and its cost in the p->cost structure.
105964     */
105965     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
105966       p->cost = pc;
105967       p->cost.plan.wsFlags &= wsFlagMask;
105968       p->cost.plan.u.pIdx = pIdx;
105969     }
105970
105971     /* If there was an INDEXED BY clause, then only that one index is
105972     ** considered. */
105973     if( pSrc->pIndex ) break;
105974
105975     /* Reset masks for the next index in the loop */
105976     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105977     eqTermMask = idxEqTermMask;
105978   }
105979
105980   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
105981   ** is set, then reverse the order that the index will be scanned
105982   ** in. This is used for application testing, to help find cases
105983   ** where application behaviour depends on the (undefined) order that
105984   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
105985   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
105986     p->cost.plan.wsFlags |= WHERE_REVERSE;
105987   }
105988
105989   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
105990   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
105991   assert( pSrc->pIndex==0 
105992        || p->cost.plan.u.pIdx==0 
105993        || p->cost.plan.u.pIdx==pSrc->pIndex 
105994   );
105995
105996   WHERETRACE(("   best index is: %s\n",
105997          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk"));
105998   
105999   bestOrClauseIndex(p);
106000   bestAutomaticIndex(p);
106001   p->cost.plan.wsFlags |= eqTermMask;
106002 }
106003
106004 /*
106005 ** Find the query plan for accessing table pSrc->pTab. Write the
106006 ** best query plan and its cost into the WhereCost object supplied 
106007 ** as the last parameter. This function may calculate the cost of
106008 ** both real and virtual table scans.
106009 **
106010 ** This function does not take ORDER BY or DISTINCT into account.  Nor
106011 ** does it remember the virtual table query plan.  All it does is compute
106012 ** the cost while determining if an OR optimization is applicable.  The
106013 ** details will be reconsidered later if the optimization is found to be
106014 ** applicable.
106015 */
106016 static void bestIndex(WhereBestIdx *p){
106017 #ifndef SQLITE_OMIT_VIRTUALTABLE
106018   if( IsVirtual(p->pSrc->pTab) ){
106019     sqlite3_index_info *pIdxInfo = 0;
106020     p->ppIdxInfo = &pIdxInfo;
106021     bestVirtualIndex(p);
106022     if( pIdxInfo->needToFreeIdxStr ){
106023       sqlite3_free(pIdxInfo->idxStr);
106024     }
106025     sqlite3DbFree(p->pParse->db, pIdxInfo);
106026   }else
106027 #endif
106028   {
106029     bestBtreeIndex(p);
106030   }
106031 }
106032
106033 /*
106034 ** Disable a term in the WHERE clause.  Except, do not disable the term
106035 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
106036 ** or USING clause of that join.
106037 **
106038 ** Consider the term t2.z='ok' in the following queries:
106039 **
106040 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
106041 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
106042 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
106043 **
106044 ** The t2.z='ok' is disabled in the in (2) because it originates
106045 ** in the ON clause.  The term is disabled in (3) because it is not part
106046 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
106047 **
106048 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
106049 ** completely satisfied by indices.
106050 **
106051 ** Disabling a term causes that term to not be tested in the inner loop
106052 ** of the join.  Disabling is an optimization.  When terms are satisfied
106053 ** by indices, we disable them to prevent redundant tests in the inner
106054 ** loop.  We would get the correct results if nothing were ever disabled,
106055 ** but joins might run a little slower.  The trick is to disable as much
106056 ** as we can without disabling too much.  If we disabled in (1), we'd get
106057 ** the wrong answer.  See ticket #813.
106058 */
106059 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
106060   if( pTerm
106061       && (pTerm->wtFlags & TERM_CODED)==0
106062       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
106063   ){
106064     pTerm->wtFlags |= TERM_CODED;
106065     if( pTerm->iParent>=0 ){
106066       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
106067       if( (--pOther->nChild)==0 ){
106068         disableTerm(pLevel, pOther);
106069       }
106070     }
106071   }
106072 }
106073
106074 /*
106075 ** Code an OP_Affinity opcode to apply the column affinity string zAff
106076 ** to the n registers starting at base. 
106077 **
106078 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
106079 ** beginning and end of zAff are ignored.  If all entries in zAff are
106080 ** SQLITE_AFF_NONE, then no code gets generated.
106081 **
106082 ** This routine makes its own copy of zAff so that the caller is free
106083 ** to modify zAff after this routine returns.
106084 */
106085 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
106086   Vdbe *v = pParse->pVdbe;
106087   if( zAff==0 ){
106088     assert( pParse->db->mallocFailed );
106089     return;
106090   }
106091   assert( v!=0 );
106092
106093   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
106094   ** and end of the affinity string.
106095   */
106096   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
106097     n--;
106098     base++;
106099     zAff++;
106100   }
106101   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
106102     n--;
106103   }
106104
106105   /* Code the OP_Affinity opcode if there is anything left to do. */
106106   if( n>0 ){
106107     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
106108     sqlite3VdbeChangeP4(v, -1, zAff, n);
106109     sqlite3ExprCacheAffinityChange(pParse, base, n);
106110   }
106111 }
106112
106113
106114 /*
106115 ** Generate code for a single equality term of the WHERE clause.  An equality
106116 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
106117 ** coded.
106118 **
106119 ** The current value for the constraint is left in register iReg.
106120 **
106121 ** For a constraint of the form X=expr, the expression is evaluated and its
106122 ** result is left on the stack.  For constraints of the form X IN (...)
106123 ** this routine sets up a loop that will iterate over all values of X.
106124 */
106125 static int codeEqualityTerm(
106126   Parse *pParse,      /* The parsing context */
106127   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
106128   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
106129   int iTarget         /* Attempt to leave results in this register */
106130 ){
106131   Expr *pX = pTerm->pExpr;
106132   Vdbe *v = pParse->pVdbe;
106133   int iReg;                  /* Register holding results */
106134
106135   assert( iTarget>0 );
106136   if( pX->op==TK_EQ ){
106137     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
106138   }else if( pX->op==TK_ISNULL ){
106139     iReg = iTarget;
106140     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
106141 #ifndef SQLITE_OMIT_SUBQUERY
106142   }else{
106143     int eType;
106144     int iTab;
106145     struct InLoop *pIn;
106146
106147     assert( pX->op==TK_IN );
106148     iReg = iTarget;
106149     eType = sqlite3FindInIndex(pParse, pX, 0);
106150     iTab = pX->iTable;
106151     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
106152     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
106153     if( pLevel->u.in.nIn==0 ){
106154       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106155     }
106156     pLevel->u.in.nIn++;
106157     pLevel->u.in.aInLoop =
106158        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
106159                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
106160     pIn = pLevel->u.in.aInLoop;
106161     if( pIn ){
106162       pIn += pLevel->u.in.nIn - 1;
106163       pIn->iCur = iTab;
106164       if( eType==IN_INDEX_ROWID ){
106165         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
106166       }else{
106167         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
106168       }
106169       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
106170     }else{
106171       pLevel->u.in.nIn = 0;
106172     }
106173 #endif
106174   }
106175   disableTerm(pLevel, pTerm);
106176   return iReg;
106177 }
106178
106179 /*
106180 ** Generate code that will evaluate all == and IN constraints for an
106181 ** index.
106182 **
106183 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
106184 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
106185 ** The index has as many as three equality constraints, but in this
106186 ** example, the third "c" value is an inequality.  So only two 
106187 ** constraints are coded.  This routine will generate code to evaluate
106188 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
106189 ** in consecutive registers and the index of the first register is returned.
106190 **
106191 ** In the example above nEq==2.  But this subroutine works for any value
106192 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
106193 ** The only thing it does is allocate the pLevel->iMem memory cell and
106194 ** compute the affinity string.
106195 **
106196 ** This routine always allocates at least one memory cell and returns
106197 ** the index of that memory cell. The code that
106198 ** calls this routine will use that memory cell to store the termination
106199 ** key value of the loop.  If one or more IN operators appear, then
106200 ** this routine allocates an additional nEq memory cells for internal
106201 ** use.
106202 **
106203 ** Before returning, *pzAff is set to point to a buffer containing a
106204 ** copy of the column affinity string of the index allocated using
106205 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
106206 ** with equality constraints that use NONE affinity are set to
106207 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
106208 **
106209 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
106210 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
106211 **
106212 ** In the example above, the index on t1(a) has TEXT affinity. But since
106213 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
106214 ** no conversion should be attempted before using a t2.b value as part of
106215 ** a key to search the index. Hence the first byte in the returned affinity
106216 ** string in this example would be set to SQLITE_AFF_NONE.
106217 */
106218 static int codeAllEqualityTerms(
106219   Parse *pParse,        /* Parsing context */
106220   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
106221   WhereClause *pWC,     /* The WHERE clause */
106222   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
106223   int nExtraReg,        /* Number of extra registers to allocate */
106224   char **pzAff          /* OUT: Set to point to affinity string */
106225 ){
106226   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
106227   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
106228   Index *pIdx;                  /* The index being used for this loop */
106229   int iCur = pLevel->iTabCur;   /* The cursor of the table */
106230   WhereTerm *pTerm;             /* A single constraint term */
106231   int j;                        /* Loop counter */
106232   int regBase;                  /* Base register */
106233   int nReg;                     /* Number of registers to allocate */
106234   char *zAff;                   /* Affinity string to return */
106235
106236   /* This module is only called on query plans that use an index. */
106237   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
106238   pIdx = pLevel->plan.u.pIdx;
106239
106240   /* Figure out how many memory cells we will need then allocate them.
106241   */
106242   regBase = pParse->nMem + 1;
106243   nReg = pLevel->plan.nEq + nExtraReg;
106244   pParse->nMem += nReg;
106245
106246   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
106247   if( !zAff ){
106248     pParse->db->mallocFailed = 1;
106249   }
106250
106251   /* Evaluate the equality constraints
106252   */
106253   assert( pIdx->nColumn>=nEq );
106254   for(j=0; j<nEq; j++){
106255     int r1;
106256     int k = pIdx->aiColumn[j];
106257     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
106258     if( pTerm==0 ) break;
106259     /* The following true for indices with redundant columns. 
106260     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
106261     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
106262     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106263     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
106264     if( r1!=regBase+j ){
106265       if( nReg==1 ){
106266         sqlite3ReleaseTempReg(pParse, regBase);
106267         regBase = r1;
106268       }else{
106269         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
106270       }
106271     }
106272     testcase( pTerm->eOperator & WO_ISNULL );
106273     testcase( pTerm->eOperator & WO_IN );
106274     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
106275       Expr *pRight = pTerm->pExpr->pRight;
106276       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
106277       if( zAff ){
106278         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
106279           zAff[j] = SQLITE_AFF_NONE;
106280         }
106281         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
106282           zAff[j] = SQLITE_AFF_NONE;
106283         }
106284       }
106285     }
106286   }
106287   *pzAff = zAff;
106288   return regBase;
106289 }
106290
106291 #ifndef SQLITE_OMIT_EXPLAIN
106292 /*
106293 ** This routine is a helper for explainIndexRange() below
106294 **
106295 ** pStr holds the text of an expression that we are building up one term
106296 ** at a time.  This routine adds a new term to the end of the expression.
106297 ** Terms are separated by AND so add the "AND" text for second and subsequent
106298 ** terms only.
106299 */
106300 static void explainAppendTerm(
106301   StrAccum *pStr,             /* The text expression being built */
106302   int iTerm,                  /* Index of this term.  First is zero */
106303   const char *zColumn,        /* Name of the column */
106304   const char *zOp             /* Name of the operator */
106305 ){
106306   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
106307   sqlite3StrAccumAppend(pStr, zColumn, -1);
106308   sqlite3StrAccumAppend(pStr, zOp, 1);
106309   sqlite3StrAccumAppend(pStr, "?", 1);
106310 }
106311
106312 /*
106313 ** Argument pLevel describes a strategy for scanning table pTab. This 
106314 ** function returns a pointer to a string buffer containing a description
106315 ** of the subset of table rows scanned by the strategy in the form of an
106316 ** SQL expression. Or, if all rows are scanned, NULL is returned.
106317 **
106318 ** For example, if the query:
106319 **
106320 **   SELECT * FROM t1 WHERE a=1 AND b>2;
106321 **
106322 ** is run and there is an index on (a, b), then this function returns a
106323 ** string similar to:
106324 **
106325 **   "a=? AND b>?"
106326 **
106327 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
106328 ** It is the responsibility of the caller to free the buffer when it is
106329 ** no longer required.
106330 */
106331 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
106332   WherePlan *pPlan = &pLevel->plan;
106333   Index *pIndex = pPlan->u.pIdx;
106334   int nEq = pPlan->nEq;
106335   int i, j;
106336   Column *aCol = pTab->aCol;
106337   int *aiColumn = pIndex->aiColumn;
106338   StrAccum txt;
106339
106340   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
106341     return 0;
106342   }
106343   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
106344   txt.db = db;
106345   sqlite3StrAccumAppend(&txt, " (", 2);
106346   for(i=0; i<nEq; i++){
106347     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
106348   }
106349
106350   j = i;
106351   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
106352     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106353     explainAppendTerm(&txt, i++, z, ">");
106354   }
106355   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
106356     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106357     explainAppendTerm(&txt, i, z, "<");
106358   }
106359   sqlite3StrAccumAppend(&txt, ")", 1);
106360   return sqlite3StrAccumFinish(&txt);
106361 }
106362
106363 /*
106364 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
106365 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
106366 ** record is added to the output to describe the table scan strategy in 
106367 ** pLevel.
106368 */
106369 static void explainOneScan(
106370   Parse *pParse,                  /* Parse context */
106371   SrcList *pTabList,              /* Table list this loop refers to */
106372   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
106373   int iLevel,                     /* Value for "level" column of output */
106374   int iFrom,                      /* Value for "from" column of output */
106375   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
106376 ){
106377   if( pParse->explain==2 ){
106378     u32 flags = pLevel->plan.wsFlags;
106379     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
106380     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
106381     sqlite3 *db = pParse->db;     /* Database handle */
106382     char *zMsg;                   /* Text to add to EQP output */
106383     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
106384     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
106385     int isSearch;                 /* True for a SEARCH. False for SCAN. */
106386
106387     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
106388
106389     isSearch = (pLevel->plan.nEq>0)
106390              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
106391              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
106392
106393     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
106394     if( pItem->pSelect ){
106395       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
106396     }else{
106397       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
106398     }
106399
106400     if( pItem->zAlias ){
106401       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
106402     }
106403     if( (flags & WHERE_INDEXED)!=0 ){
106404       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
106405       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
106406           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
106407           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
106408           ((flags & WHERE_TEMP_INDEX)?"":" "),
106409           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
106410           zWhere
106411       );
106412       sqlite3DbFree(db, zWhere);
106413     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
106414       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
106415
106416       if( flags&WHERE_ROWID_EQ ){
106417         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
106418       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
106419         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
106420       }else if( flags&WHERE_BTM_LIMIT ){
106421         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
106422       }else if( flags&WHERE_TOP_LIMIT ){
106423         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
106424       }
106425     }
106426 #ifndef SQLITE_OMIT_VIRTUALTABLE
106427     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
106428       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106429       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
106430                   pVtabIdx->idxNum, pVtabIdx->idxStr);
106431     }
106432 #endif
106433     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
106434       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
106435       nRow = 1;
106436     }else{
106437       nRow = (sqlite3_int64)pLevel->plan.nRow;
106438     }
106439     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
106440     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
106441   }
106442 }
106443 #else
106444 # define explainOneScan(u,v,w,x,y,z)
106445 #endif /* SQLITE_OMIT_EXPLAIN */
106446
106447
106448 /*
106449 ** Generate code for the start of the iLevel-th loop in the WHERE clause
106450 ** implementation described by pWInfo.
106451 */
106452 static Bitmask codeOneLoopStart(
106453   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
106454   int iLevel,          /* Which level of pWInfo->a[] should be coded */
106455   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
106456   Bitmask notReady     /* Which tables are currently available */
106457 ){
106458   int j, k;            /* Loop counters */
106459   int iCur;            /* The VDBE cursor for the table */
106460   int addrNxt;         /* Where to jump to continue with the next IN case */
106461   int omitTable;       /* True if we use the index only */
106462   int bRev;            /* True if we need to scan in reverse order */
106463   WhereLevel *pLevel;  /* The where level to be coded */
106464   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
106465   WhereTerm *pTerm;               /* A WHERE clause term */
106466   Parse *pParse;                  /* Parsing context */
106467   Vdbe *v;                        /* The prepared stmt under constructions */
106468   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
106469   int addrBrk;                    /* Jump here to break out of the loop */
106470   int addrCont;                   /* Jump here to continue with next cycle */
106471   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
106472   int iReleaseReg = 0;      /* Temp register to free before returning */
106473
106474   pParse = pWInfo->pParse;
106475   v = pParse->pVdbe;
106476   pWC = pWInfo->pWC;
106477   pLevel = &pWInfo->a[iLevel];
106478   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
106479   iCur = pTabItem->iCursor;
106480   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
106481   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
106482            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
106483
106484   /* Create labels for the "break" and "continue" instructions
106485   ** for the current loop.  Jump to addrBrk to break out of a loop.
106486   ** Jump to cont to go immediately to the next iteration of the
106487   ** loop.
106488   **
106489   ** When there is an IN operator, we also have a "addrNxt" label that
106490   ** means to continue with the next IN value combination.  When
106491   ** there are no IN operators in the constraints, the "addrNxt" label
106492   ** is the same as "addrBrk".
106493   */
106494   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106495   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
106496
106497   /* If this is the right table of a LEFT OUTER JOIN, allocate and
106498   ** initialize a memory cell that records if this table matches any
106499   ** row of the left table of the join.
106500   */
106501   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
106502     pLevel->iLeftJoin = ++pParse->nMem;
106503     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
106504     VdbeComment((v, "init LEFT JOIN no-match flag"));
106505   }
106506
106507   /* Special case of a FROM clause subquery implemented as a co-routine */
106508   if( pTabItem->viaCoroutine ){
106509     int regYield = pTabItem->regReturn;
106510     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
106511     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
106512     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
106513     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
106514     pLevel->op = OP_Goto;
106515   }else
106516
106517 #ifndef SQLITE_OMIT_VIRTUALTABLE
106518   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
106519     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
106520     **          to access the data.
106521     */
106522     int iReg;   /* P3 Value for OP_VFilter */
106523     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106524     int nConstraint = pVtabIdx->nConstraint;
106525     struct sqlite3_index_constraint_usage *aUsage =
106526                                                 pVtabIdx->aConstraintUsage;
106527     const struct sqlite3_index_constraint *aConstraint =
106528                                                 pVtabIdx->aConstraint;
106529
106530     sqlite3ExprCachePush(pParse);
106531     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
106532     for(j=1; j<=nConstraint; j++){
106533       for(k=0; k<nConstraint; k++){
106534         if( aUsage[k].argvIndex==j ){
106535           int iTerm = aConstraint[k].iTermOffset;
106536           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
106537           break;
106538         }
106539       }
106540       if( k==nConstraint ) break;
106541     }
106542     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
106543     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
106544     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
106545                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
106546     pVtabIdx->needToFreeIdxStr = 0;
106547     for(j=0; j<nConstraint; j++){
106548       if( aUsage[j].omit ){
106549         int iTerm = aConstraint[j].iTermOffset;
106550         disableTerm(pLevel, &pWC->a[iTerm]);
106551       }
106552     }
106553     pLevel->op = OP_VNext;
106554     pLevel->p1 = iCur;
106555     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106556     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
106557     sqlite3ExprCachePop(pParse, 1);
106558   }else
106559 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106560
106561   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
106562     /* Case 1:  We can directly reference a single row using an
106563     **          equality comparison against the ROWID field.  Or
106564     **          we reference multiple rows using a "rowid IN (...)"
106565     **          construct.
106566     */
106567     iReleaseReg = sqlite3GetTempReg(pParse);
106568     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
106569     assert( pTerm!=0 );
106570     assert( pTerm->pExpr!=0 );
106571     assert( pTerm->leftCursor==iCur );
106572     assert( omitTable==0 );
106573     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106574     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
106575     addrNxt = pLevel->addrNxt;
106576     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
106577     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
106578     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106579     VdbeComment((v, "pk"));
106580     pLevel->op = OP_Noop;
106581   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
106582     /* Case 2:  We have an inequality comparison against the ROWID field.
106583     */
106584     int testOp = OP_Noop;
106585     int start;
106586     int memEndValue = 0;
106587     WhereTerm *pStart, *pEnd;
106588
106589     assert( omitTable==0 );
106590     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
106591     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
106592     if( bRev ){
106593       pTerm = pStart;
106594       pStart = pEnd;
106595       pEnd = pTerm;
106596     }
106597     if( pStart ){
106598       Expr *pX;             /* The expression that defines the start bound */
106599       int r1, rTemp;        /* Registers for holding the start boundary */
106600
106601       /* The following constant maps TK_xx codes into corresponding 
106602       ** seek opcodes.  It depends on a particular ordering of TK_xx
106603       */
106604       const u8 aMoveOp[] = {
106605            /* TK_GT */  OP_SeekGt,
106606            /* TK_LE */  OP_SeekLe,
106607            /* TK_LT */  OP_SeekLt,
106608            /* TK_GE */  OP_SeekGe
106609       };
106610       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
106611       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
106612       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
106613
106614       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106615       pX = pStart->pExpr;
106616       assert( pX!=0 );
106617       assert( pStart->leftCursor==iCur );
106618       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
106619       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
106620       VdbeComment((v, "pk"));
106621       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
106622       sqlite3ReleaseTempReg(pParse, rTemp);
106623       disableTerm(pLevel, pStart);
106624     }else{
106625       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
106626     }
106627     if( pEnd ){
106628       Expr *pX;
106629       pX = pEnd->pExpr;
106630       assert( pX!=0 );
106631       assert( pEnd->leftCursor==iCur );
106632       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106633       memEndValue = ++pParse->nMem;
106634       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
106635       if( pX->op==TK_LT || pX->op==TK_GT ){
106636         testOp = bRev ? OP_Le : OP_Ge;
106637       }else{
106638         testOp = bRev ? OP_Lt : OP_Gt;
106639       }
106640       disableTerm(pLevel, pEnd);
106641     }
106642     start = sqlite3VdbeCurrentAddr(v);
106643     pLevel->op = bRev ? OP_Prev : OP_Next;
106644     pLevel->p1 = iCur;
106645     pLevel->p2 = start;
106646     if( pStart==0 && pEnd==0 ){
106647       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106648     }else{
106649       assert( pLevel->p5==0 );
106650     }
106651     if( testOp!=OP_Noop ){
106652       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106653       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
106654       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106655       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
106656       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
106657     }
106658   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
106659     /* Case 3: A scan using an index.
106660     **
106661     **         The WHERE clause may contain zero or more equality 
106662     **         terms ("==" or "IN" operators) that refer to the N
106663     **         left-most columns of the index. It may also contain
106664     **         inequality constraints (>, <, >= or <=) on the indexed
106665     **         column that immediately follows the N equalities. Only 
106666     **         the right-most column can be an inequality - the rest must
106667     **         use the "==" and "IN" operators. For example, if the 
106668     **         index is on (x,y,z), then the following clauses are all 
106669     **         optimized:
106670     **
106671     **            x=5
106672     **            x=5 AND y=10
106673     **            x=5 AND y<10
106674     **            x=5 AND y>5 AND y<10
106675     **            x=5 AND y=5 AND z<=10
106676     **
106677     **         The z<10 term of the following cannot be used, only
106678     **         the x=5 term:
106679     **
106680     **            x=5 AND z<10
106681     **
106682     **         N may be zero if there are inequality constraints.
106683     **         If there are no inequality constraints, then N is at
106684     **         least one.
106685     **
106686     **         This case is also used when there are no WHERE clause
106687     **         constraints but an index is selected anyway, in order
106688     **         to force the output order to conform to an ORDER BY.
106689     */  
106690     static const u8 aStartOp[] = {
106691       0,
106692       0,
106693       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
106694       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
106695       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
106696       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
106697       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
106698       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
106699     };
106700     static const u8 aEndOp[] = {
106701       OP_Noop,             /* 0: (!end_constraints) */
106702       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
106703       OP_IdxLT             /* 2: (end_constraints && bRev) */
106704     };
106705     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
106706     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
106707     int regBase;                 /* Base register holding constraint values */
106708     int r1;                      /* Temp register */
106709     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
106710     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
106711     int startEq;                 /* True if range start uses ==, >= or <= */
106712     int endEq;                   /* True if range end uses ==, >= or <= */
106713     int start_constraints;       /* Start of range is constrained */
106714     int nConstraint;             /* Number of constraint terms */
106715     Index *pIdx;                 /* The index we will be using */
106716     int iIdxCur;                 /* The VDBE cursor for the index */
106717     int nExtraReg = 0;           /* Number of extra registers needed */
106718     int op;                      /* Instruction opcode */
106719     char *zStartAff;             /* Affinity for start of range constraint */
106720     char *zEndAff;               /* Affinity for end of range constraint */
106721
106722     pIdx = pLevel->plan.u.pIdx;
106723     iIdxCur = pLevel->iIdxCur;
106724     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
106725
106726     /* If this loop satisfies a sort order (pOrderBy) request that 
106727     ** was passed to this function to implement a "SELECT min(x) ..." 
106728     ** query, then the caller will only allow the loop to run for
106729     ** a single iteration. This means that the first row returned
106730     ** should not have a NULL value stored in 'x'. If column 'x' is
106731     ** the first one after the nEq equality constraints in the index,
106732     ** this requires some special handling.
106733     */
106734     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
106735      && (pLevel->plan.wsFlags&WHERE_ORDERED)
106736      && (pIdx->nColumn>nEq)
106737     ){
106738       /* assert( pOrderBy->nExpr==1 ); */
106739       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
106740       isMinQuery = 1;
106741       nExtraReg = 1;
106742     }
106743
106744     /* Find any inequality constraint terms for the start and end 
106745     ** of the range. 
106746     */
106747     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
106748       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
106749       nExtraReg = 1;
106750     }
106751     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
106752       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
106753       nExtraReg = 1;
106754     }
106755
106756     /* Generate code to evaluate all constraint terms using == or IN
106757     ** and store the values of those terms in an array of registers
106758     ** starting at regBase.
106759     */
106760     regBase = codeAllEqualityTerms(
106761         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
106762     );
106763     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
106764     addrNxt = pLevel->addrNxt;
106765
106766     /* If we are doing a reverse order scan on an ascending index, or
106767     ** a forward order scan on a descending index, interchange the 
106768     ** start and end terms (pRangeStart and pRangeEnd).
106769     */
106770     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
106771      || (bRev && pIdx->nColumn==nEq)
106772     ){
106773       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
106774     }
106775
106776     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
106777     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
106778     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
106779     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
106780     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
106781     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
106782     start_constraints = pRangeStart || nEq>0;
106783
106784     /* Seek the index cursor to the start of the range. */
106785     nConstraint = nEq;
106786     if( pRangeStart ){
106787       Expr *pRight = pRangeStart->pExpr->pRight;
106788       sqlite3ExprCode(pParse, pRight, regBase+nEq);
106789       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
106790         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106791       }
106792       if( zStartAff ){
106793         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
106794           /* Since the comparison is to be performed with no conversions
106795           ** applied to the operands, set the affinity to apply to pRight to 
106796           ** SQLITE_AFF_NONE.  */
106797           zStartAff[nEq] = SQLITE_AFF_NONE;
106798         }
106799         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
106800           zStartAff[nEq] = SQLITE_AFF_NONE;
106801         }
106802       }  
106803       nConstraint++;
106804       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106805     }else if( isMinQuery ){
106806       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
106807       nConstraint++;
106808       startEq = 0;
106809       start_constraints = 1;
106810     }
106811     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
106812     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
106813     assert( op!=0 );
106814     testcase( op==OP_Rewind );
106815     testcase( op==OP_Last );
106816     testcase( op==OP_SeekGt );
106817     testcase( op==OP_SeekGe );
106818     testcase( op==OP_SeekLe );
106819     testcase( op==OP_SeekLt );
106820     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106821
106822     /* Load the value for the inequality constraint at the end of the
106823     ** range (if any).
106824     */
106825     nConstraint = nEq;
106826     if( pRangeEnd ){
106827       Expr *pRight = pRangeEnd->pExpr->pRight;
106828       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
106829       sqlite3ExprCode(pParse, pRight, regBase+nEq);
106830       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
106831         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106832       }
106833       if( zEndAff ){
106834         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
106835           /* Since the comparison is to be performed with no conversions
106836           ** applied to the operands, set the affinity to apply to pRight to 
106837           ** SQLITE_AFF_NONE.  */
106838           zEndAff[nEq] = SQLITE_AFF_NONE;
106839         }
106840         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
106841           zEndAff[nEq] = SQLITE_AFF_NONE;
106842         }
106843       }  
106844       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
106845       nConstraint++;
106846       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106847     }
106848     sqlite3DbFree(pParse->db, zStartAff);
106849     sqlite3DbFree(pParse->db, zEndAff);
106850
106851     /* Top of the loop body */
106852     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106853
106854     /* Check if the index cursor is past the end of the range. */
106855     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
106856     testcase( op==OP_Noop );
106857     testcase( op==OP_IdxGE );
106858     testcase( op==OP_IdxLT );
106859     if( op!=OP_Noop ){
106860       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106861       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
106862     }
106863
106864     /* If there are inequality constraints, check that the value
106865     ** of the table column that the inequality contrains is not NULL.
106866     ** If it is, jump to the next iteration of the loop.
106867     */
106868     r1 = sqlite3GetTempReg(pParse);
106869     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
106870     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
106871     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
106872       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
106873       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
106874     }
106875     sqlite3ReleaseTempReg(pParse, r1);
106876
106877     /* Seek the table cursor, if required */
106878     disableTerm(pLevel, pRangeStart);
106879     disableTerm(pLevel, pRangeEnd);
106880     if( !omitTable ){
106881       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106882       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
106883       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106884       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
106885     }
106886
106887     /* Record the instruction used to terminate the loop. Disable 
106888     ** WHERE clause terms made redundant by the index range scan.
106889     */
106890     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
106891       pLevel->op = OP_Noop;
106892     }else if( bRev ){
106893       pLevel->op = OP_Prev;
106894     }else{
106895       pLevel->op = OP_Next;
106896     }
106897     pLevel->p1 = iIdxCur;
106898     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
106899       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106900     }else{
106901       assert( pLevel->p5==0 );
106902     }
106903   }else
106904
106905 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
106906   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106907     /* Case 4:  Two or more separately indexed terms connected by OR
106908     **
106909     ** Example:
106910     **
106911     **   CREATE TABLE t1(a,b,c,d);
106912     **   CREATE INDEX i1 ON t1(a);
106913     **   CREATE INDEX i2 ON t1(b);
106914     **   CREATE INDEX i3 ON t1(c);
106915     **
106916     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
106917     **
106918     ** In the example, there are three indexed terms connected by OR.
106919     ** The top of the loop looks like this:
106920     **
106921     **          Null       1                # Zero the rowset in reg 1
106922     **
106923     ** Then, for each indexed term, the following. The arguments to
106924     ** RowSetTest are such that the rowid of the current row is inserted
106925     ** into the RowSet. If it is already present, control skips the
106926     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
106927     **
106928     **        sqlite3WhereBegin(<term>)
106929     **          RowSetTest                  # Insert rowid into rowset
106930     **          Gosub      2 A
106931     **        sqlite3WhereEnd()
106932     **
106933     ** Following the above, code to terminate the loop. Label A, the target
106934     ** of the Gosub above, jumps to the instruction right after the Goto.
106935     **
106936     **          Null       1                # Zero the rowset in reg 1
106937     **          Goto       B                # The loop is finished.
106938     **
106939     **       A: <loop body>                 # Return data, whatever.
106940     **
106941     **          Return     2                # Jump back to the Gosub
106942     **
106943     **       B: <after the loop>
106944     **
106945     */
106946     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
106947     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
106948     Index *pCov = 0;             /* Potential covering index (or NULL) */
106949     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
106950
106951     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
106952     int regRowset = 0;                        /* Register for RowSet object */
106953     int regRowid = 0;                         /* Register holding rowid */
106954     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
106955     int iRetInit;                             /* Address of regReturn init */
106956     int untestedTerms = 0;             /* Some terms not completely tested */
106957     int ii;                            /* Loop counter */
106958     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
106959    
106960     pTerm = pLevel->plan.u.pTerm;
106961     assert( pTerm!=0 );
106962     assert( pTerm->eOperator==WO_OR );
106963     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
106964     pOrWc = &pTerm->u.pOrInfo->wc;
106965     pLevel->op = OP_Return;
106966     pLevel->p1 = regReturn;
106967
106968     /* Set up a new SrcList in pOrTab containing the table being scanned
106969     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
106970     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
106971     */
106972     if( pWInfo->nLevel>1 ){
106973       int nNotReady;                 /* The number of notReady tables */
106974       struct SrcList_item *origSrc;     /* Original list of tables */
106975       nNotReady = pWInfo->nLevel - iLevel - 1;
106976       pOrTab = sqlite3StackAllocRaw(pParse->db,
106977                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
106978       if( pOrTab==0 ) return notReady;
106979       pOrTab->nAlloc = (i16)(nNotReady + 1);
106980       pOrTab->nSrc = pOrTab->nAlloc;
106981       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
106982       origSrc = pWInfo->pTabList->a;
106983       for(k=1; k<=nNotReady; k++){
106984         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
106985       }
106986     }else{
106987       pOrTab = pWInfo->pTabList;
106988     }
106989
106990     /* Initialize the rowset register to contain NULL. An SQL NULL is 
106991     ** equivalent to an empty rowset.
106992     **
106993     ** Also initialize regReturn to contain the address of the instruction 
106994     ** immediately following the OP_Return at the bottom of the loop. This
106995     ** is required in a few obscure LEFT JOIN cases where control jumps
106996     ** over the top of the loop into the body of it. In this case the 
106997     ** correct response for the end-of-loop code (the OP_Return) is to 
106998     ** fall through to the next instruction, just as an OP_Next does if
106999     ** called on an uninitialized cursor.
107000     */
107001     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107002       regRowset = ++pParse->nMem;
107003       regRowid = ++pParse->nMem;
107004       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
107005     }
107006     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
107007
107008     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
107009     ** Then for every term xN, evaluate as the subexpression: xN AND z
107010     ** That way, terms in y that are factored into the disjunction will
107011     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
107012     **
107013     ** Actually, each subexpression is converted to "xN AND w" where w is
107014     ** the "interesting" terms of z - terms that did not originate in the
107015     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
107016     ** indices.
107017     */
107018     if( pWC->nTerm>1 ){
107019       int iTerm;
107020       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
107021         Expr *pExpr = pWC->a[iTerm].pExpr;
107022         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
107023         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
107024         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
107025         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
107026         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
107027       }
107028       if( pAndExpr ){
107029         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
107030       }
107031     }
107032
107033     for(ii=0; ii<pOrWc->nTerm; ii++){
107034       WhereTerm *pOrTerm = &pOrWc->a[ii];
107035       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
107036         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
107037         Expr *pOrExpr = pOrTerm->pExpr;
107038         if( pAndExpr ){
107039           pAndExpr->pLeft = pOrExpr;
107040           pOrExpr = pAndExpr;
107041         }
107042         /* Loop through table entries that match term pOrTerm. */
107043         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
107044                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
107045                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
107046         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
107047         if( pSubWInfo ){
107048           WhereLevel *pLvl;
107049           explainOneScan(
107050               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
107051           );
107052           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107053             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
107054             int r;
107055             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
107056                                          regRowid, 0);
107057             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
107058                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
107059           }
107060           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
107061
107062           /* The pSubWInfo->untestedTerms flag means that this OR term
107063           ** contained one or more AND term from a notReady table.  The
107064           ** terms from the notReady table could not be tested and will
107065           ** need to be tested later.
107066           */
107067           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
107068
107069           /* If all of the OR-connected terms are optimized using the same
107070           ** index, and the index is opened using the same cursor number
107071           ** by each call to sqlite3WhereBegin() made by this loop, it may
107072           ** be possible to use that index as a covering index.
107073           **
107074           ** If the call to sqlite3WhereBegin() above resulted in a scan that
107075           ** uses an index, and this is either the first OR-connected term
107076           ** processed or the index is the same as that used by all previous
107077           ** terms, set pCov to the candidate covering index. Otherwise, set 
107078           ** pCov to NULL to indicate that no candidate covering index will 
107079           ** be available.
107080           */
107081           pLvl = &pSubWInfo->a[0];
107082           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
107083            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
107084            && (ii==0 || pLvl->plan.u.pIdx==pCov)
107085           ){
107086             assert( pLvl->iIdxCur==iCovCur );
107087             pCov = pLvl->plan.u.pIdx;
107088           }else{
107089             pCov = 0;
107090           }
107091
107092           /* Finish the loop through table entries that match term pOrTerm. */
107093           sqlite3WhereEnd(pSubWInfo);
107094         }
107095       }
107096     }
107097     pLevel->u.pCovidx = pCov;
107098     if( pCov ) pLevel->iIdxCur = iCovCur;
107099     if( pAndExpr ){
107100       pAndExpr->pLeft = 0;
107101       sqlite3ExprDelete(pParse->db, pAndExpr);
107102     }
107103     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
107104     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
107105     sqlite3VdbeResolveLabel(v, iLoopBody);
107106
107107     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
107108     if( !untestedTerms ) disableTerm(pLevel, pTerm);
107109   }else
107110 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
107111
107112   {
107113     /* Case 5:  There is no usable index.  We must do a complete
107114     **          scan of the entire table.
107115     */
107116     static const u8 aStep[] = { OP_Next, OP_Prev };
107117     static const u8 aStart[] = { OP_Rewind, OP_Last };
107118     assert( bRev==0 || bRev==1 );
107119     assert( omitTable==0 );
107120     pLevel->op = aStep[bRev];
107121     pLevel->p1 = iCur;
107122     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
107123     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107124   }
107125   notReady &= ~getMask(pWC->pMaskSet, iCur);
107126
107127   /* Insert code to test every subexpression that can be completely
107128   ** computed using the current set of tables.
107129   **
107130   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
107131   ** the use of indices become tests that are evaluated against each row of
107132   ** the relevant input tables.
107133   */
107134   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
107135     Expr *pE;
107136     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
107137     testcase( pTerm->wtFlags & TERM_CODED );
107138     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107139     if( (pTerm->prereqAll & notReady)!=0 ){
107140       testcase( pWInfo->untestedTerms==0
107141                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
107142       pWInfo->untestedTerms = 1;
107143       continue;
107144     }
107145     pE = pTerm->pExpr;
107146     assert( pE!=0 );
107147     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
107148       continue;
107149     }
107150     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
107151     pTerm->wtFlags |= TERM_CODED;
107152   }
107153
107154   /* For a LEFT OUTER JOIN, generate code that will record the fact that
107155   ** at least one row of the right table has matched the left table.  
107156   */
107157   if( pLevel->iLeftJoin ){
107158     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
107159     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
107160     VdbeComment((v, "record LEFT JOIN hit"));
107161     sqlite3ExprCacheClear(pParse);
107162     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
107163       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
107164       testcase( pTerm->wtFlags & TERM_CODED );
107165       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107166       if( (pTerm->prereqAll & notReady)!=0 ){
107167         assert( pWInfo->untestedTerms );
107168         continue;
107169       }
107170       assert( pTerm->pExpr );
107171       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
107172       pTerm->wtFlags |= TERM_CODED;
107173     }
107174   }
107175   sqlite3ReleaseTempReg(pParse, iReleaseReg);
107176
107177   return notReady;
107178 }
107179
107180 #if defined(SQLITE_TEST)
107181 /*
107182 ** The following variable holds a text description of query plan generated
107183 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
107184 ** overwrites the previous.  This information is used for testing and
107185 ** analysis only.
107186 */
107187 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
107188 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
107189
107190 #endif /* SQLITE_TEST */
107191
107192
107193 /*
107194 ** Free a WhereInfo structure
107195 */
107196 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
107197   if( ALWAYS(pWInfo) ){
107198     int i;
107199     for(i=0; i<pWInfo->nLevel; i++){
107200       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
107201       if( pInfo ){
107202         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
107203         if( pInfo->needToFreeIdxStr ){
107204           sqlite3_free(pInfo->idxStr);
107205         }
107206         sqlite3DbFree(db, pInfo);
107207       }
107208       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
107209         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
107210         if( pIdx ){
107211           sqlite3DbFree(db, pIdx->zColAff);
107212           sqlite3DbFree(db, pIdx);
107213         }
107214       }
107215     }
107216     whereClauseClear(pWInfo->pWC);
107217     sqlite3DbFree(db, pWInfo);
107218   }
107219 }
107220
107221
107222 /*
107223 ** Generate the beginning of the loop used for WHERE clause processing.
107224 ** The return value is a pointer to an opaque structure that contains
107225 ** information needed to terminate the loop.  Later, the calling routine
107226 ** should invoke sqlite3WhereEnd() with the return value of this function
107227 ** in order to complete the WHERE clause processing.
107228 **
107229 ** If an error occurs, this routine returns NULL.
107230 **
107231 ** The basic idea is to do a nested loop, one loop for each table in
107232 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
107233 ** same as a SELECT with only a single table in the FROM clause.)  For
107234 ** example, if the SQL is this:
107235 **
107236 **       SELECT * FROM t1, t2, t3 WHERE ...;
107237 **
107238 ** Then the code generated is conceptually like the following:
107239 **
107240 **      foreach row1 in t1 do       \    Code generated
107241 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
107242 **          foreach row3 in t3 do   /
107243 **            ...
107244 **          end                     \    Code generated
107245 **        end                        |-- by sqlite3WhereEnd()
107246 **      end                         /
107247 **
107248 ** Note that the loops might not be nested in the order in which they
107249 ** appear in the FROM clause if a different order is better able to make
107250 ** use of indices.  Note also that when the IN operator appears in
107251 ** the WHERE clause, it might result in additional nested loops for
107252 ** scanning through all values on the right-hand side of the IN.
107253 **
107254 ** There are Btree cursors associated with each table.  t1 uses cursor
107255 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
107256 ** And so forth.  This routine generates code to open those VDBE cursors
107257 ** and sqlite3WhereEnd() generates the code to close them.
107258 **
107259 ** The code that sqlite3WhereBegin() generates leaves the cursors named
107260 ** in pTabList pointing at their appropriate entries.  The [...] code
107261 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
107262 ** data from the various tables of the loop.
107263 **
107264 ** If the WHERE clause is empty, the foreach loops must each scan their
107265 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
107266 ** the tables have indices and there are terms in the WHERE clause that
107267 ** refer to those indices, a complete table scan can be avoided and the
107268 ** code will run much faster.  Most of the work of this routine is checking
107269 ** to see if there are indices that can be used to speed up the loop.
107270 **
107271 ** Terms of the WHERE clause are also used to limit which rows actually
107272 ** make it to the "..." in the middle of the loop.  After each "foreach",
107273 ** terms of the WHERE clause that use only terms in that loop and outer
107274 ** loops are evaluated and if false a jump is made around all subsequent
107275 ** inner loops (or around the "..." if the test occurs within the inner-
107276 ** most loop)
107277 **
107278 ** OUTER JOINS
107279 **
107280 ** An outer join of tables t1 and t2 is conceptally coded as follows:
107281 **
107282 **    foreach row1 in t1 do
107283 **      flag = 0
107284 **      foreach row2 in t2 do
107285 **        start:
107286 **          ...
107287 **          flag = 1
107288 **      end
107289 **      if flag==0 then
107290 **        move the row2 cursor to a null row
107291 **        goto start
107292 **      fi
107293 **    end
107294 **
107295 ** ORDER BY CLAUSE PROCESSING
107296 **
107297 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
107298 ** if there is one.  If there is no ORDER BY clause or if this routine
107299 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
107300 **
107301 ** If an index can be used so that the natural output order of the table
107302 ** scan is correct for the ORDER BY clause, then that index is used and
107303 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
107304 ** is an optimization that prevents an unnecessary sort of the result set
107305 ** if an index appropriate for the ORDER BY clause already exists.
107306 **
107307 ** If the where clause loops cannot be arranged to provide the correct
107308 ** output order, then WhereInfo.nOBSat is 0.
107309 */
107310 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
107311   Parse *pParse,        /* The parser context */
107312   SrcList *pTabList,    /* A list of all tables to be scanned */
107313   Expr *pWhere,         /* The WHERE clause */
107314   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
107315   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
107316   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
107317   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
107318 ){
107319   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
107320   int nTabList;              /* Number of elements in pTabList */
107321   WhereInfo *pWInfo;         /* Will become the return value of this function */
107322   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
107323   Bitmask notReady;          /* Cursors that are not yet positioned */
107324   WhereBestIdx sWBI;         /* Best index search context */
107325   WhereMaskSet *pMaskSet;    /* The expression mask set */
107326   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
107327   int iFrom;                 /* First unused FROM clause element */
107328   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
107329   int ii;                    /* Loop counter */
107330   sqlite3 *db;               /* Database connection */
107331
107332
107333   /* Variable initialization */
107334   memset(&sWBI, 0, sizeof(sWBI));
107335   sWBI.pParse = pParse;
107336
107337   /* The number of tables in the FROM clause is limited by the number of
107338   ** bits in a Bitmask 
107339   */
107340   testcase( pTabList->nSrc==BMS );
107341   if( pTabList->nSrc>BMS ){
107342     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
107343     return 0;
107344   }
107345
107346   /* This function normally generates a nested loop for all tables in 
107347   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
107348   ** only generate code for the first table in pTabList and assume that
107349   ** any cursors associated with subsequent tables are uninitialized.
107350   */
107351   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
107352
107353   /* Allocate and initialize the WhereInfo structure that will become the
107354   ** return value. A single allocation is used to store the WhereInfo
107355   ** struct, the contents of WhereInfo.a[], the WhereClause structure
107356   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
107357   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
107358   ** some architectures. Hence the ROUND8() below.
107359   */
107360   db = pParse->db;
107361   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
107362   pWInfo = sqlite3DbMallocZero(db, 
107363       nByteWInfo + 
107364       sizeof(WhereClause) +
107365       sizeof(WhereMaskSet)
107366   );
107367   if( db->mallocFailed ){
107368     sqlite3DbFree(db, pWInfo);
107369     pWInfo = 0;
107370     goto whereBeginError;
107371   }
107372   pWInfo->nLevel = nTabList;
107373   pWInfo->pParse = pParse;
107374   pWInfo->pTabList = pTabList;
107375   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
107376   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
107377   pWInfo->wctrlFlags = wctrlFlags;
107378   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
107379   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
107380   sWBI.aLevel = pWInfo->a;
107381
107382   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
107383   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
107384   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
107385
107386   /* Split the WHERE clause into separate subexpressions where each
107387   ** subexpression is separated by an AND operator.
107388   */
107389   initMaskSet(pMaskSet);
107390   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
107391   sqlite3ExprCodeConstants(pParse, pWhere);
107392   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
107393     
107394   /* Special case: a WHERE clause that is constant.  Evaluate the
107395   ** expression and either jump over all of the code or fall thru.
107396   */
107397   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
107398     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
107399     pWhere = 0;
107400   }
107401
107402   /* Assign a bit from the bitmask to every term in the FROM clause.
107403   **
107404   ** When assigning bitmask values to FROM clause cursors, it must be
107405   ** the case that if X is the bitmask for the N-th FROM clause term then
107406   ** the bitmask for all FROM clause terms to the left of the N-th term
107407   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
107408   ** its Expr.iRightJoinTable value to find the bitmask of the right table
107409   ** of the join.  Subtracting one from the right table bitmask gives a
107410   ** bitmask for all tables to the left of the join.  Knowing the bitmask
107411   ** for all tables to the left of a left join is important.  Ticket #3015.
107412   **
107413   ** Configure the WhereClause.vmask variable so that bits that correspond
107414   ** to virtual table cursors are set. This is used to selectively disable 
107415   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
107416   ** with virtual tables.
107417   **
107418   ** Note that bitmasks are created for all pTabList->nSrc tables in
107419   ** pTabList, not just the first nTabList tables.  nTabList is normally
107420   ** equal to pTabList->nSrc but might be shortened to 1 if the
107421   ** WHERE_ONETABLE_ONLY flag is set.
107422   */
107423   assert( sWBI.pWC->vmask==0 && pMaskSet->n==0 );
107424   for(ii=0; ii<pTabList->nSrc; ii++){
107425     createMask(pMaskSet, pTabList->a[ii].iCursor);
107426 #ifndef SQLITE_OMIT_VIRTUALTABLE
107427     if( ALWAYS(pTabList->a[ii].pTab) && IsVirtual(pTabList->a[ii].pTab) ){
107428       sWBI.pWC->vmask |= ((Bitmask)1 << ii);
107429     }
107430 #endif
107431   }
107432 #ifndef NDEBUG
107433   {
107434     Bitmask toTheLeft = 0;
107435     for(ii=0; ii<pTabList->nSrc; ii++){
107436       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
107437       assert( (m-1)==toTheLeft );
107438       toTheLeft |= m;
107439     }
107440   }
107441 #endif
107442
107443   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
107444   ** add new virtual terms onto the end of the WHERE clause.  We do not
107445   ** want to analyze these virtual terms, so start analyzing at the end
107446   ** and work forward so that the added virtual terms are never processed.
107447   */
107448   exprAnalyzeAll(pTabList, sWBI.pWC);
107449   if( db->mallocFailed ){
107450     goto whereBeginError;
107451   }
107452
107453   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
107454   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
107455   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
107456   */
107457   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
107458     pDistinct = 0;
107459     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
107460   }
107461
107462   /* Chose the best index to use for each table in the FROM clause.
107463   **
107464   ** This loop fills in the following fields:
107465   **
107466   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
107467   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
107468   **   pWInfo->a[].nEq       The number of == and IN constraints
107469   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
107470   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
107471   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
107472   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
107473   **
107474   ** This loop also figures out the nesting order of tables in the FROM
107475   ** clause.
107476   */
107477   sWBI.notValid = ~(Bitmask)0;
107478   sWBI.pOrderBy = pOrderBy;
107479   sWBI.n = nTabList;
107480   sWBI.pDistinct = pDistinct;
107481   andFlags = ~0;
107482   WHERETRACE(("*** Optimizer Start ***\n"));
107483   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
107484     WhereCost bestPlan;         /* Most efficient plan seen so far */
107485     Index *pIdx;                /* Index for FROM table at pTabItem */
107486     int j;                      /* For looping over FROM tables */
107487     int bestJ = -1;             /* The value of j */
107488     Bitmask m;                  /* Bitmask value for j or bestJ */
107489     int isOptimal;              /* Iterator for optimal/non-optimal search */
107490     int nUnconstrained;         /* Number tables without INDEXED BY */
107491     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
107492
107493     memset(&bestPlan, 0, sizeof(bestPlan));
107494     bestPlan.rCost = SQLITE_BIG_DBL;
107495     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
107496
107497     /* Loop through the remaining entries in the FROM clause to find the
107498     ** next nested loop. The loop tests all FROM clause entries
107499     ** either once or twice. 
107500     **
107501     ** The first test is always performed if there are two or more entries
107502     ** remaining and never performed if there is only one FROM clause entry
107503     ** to choose from.  The first test looks for an "optimal" scan.  In
107504     ** this context an optimal scan is one that uses the same strategy
107505     ** for the given FROM clause entry as would be selected if the entry
107506     ** were used as the innermost nested loop.  In other words, a table
107507     ** is chosen such that the cost of running that table cannot be reduced
107508     ** by waiting for other tables to run first.  This "optimal" test works
107509     ** by first assuming that the FROM clause is on the inner loop and finding
107510     ** its query plan, then checking to see if that query plan uses any
107511     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
107512     ** are used then the "optimal" query plan works.
107513     **
107514     ** Note that the WhereCost.nRow parameter for an optimal scan might
107515     ** not be as small as it would be if the table really were the innermost
107516     ** join.  The nRow value can be reduced by WHERE clause constraints
107517     ** that do not use indices.  But this nRow reduction only happens if the
107518     ** table really is the innermost join.  
107519     **
107520     ** The second loop iteration is only performed if no optimal scan
107521     ** strategies were found by the first iteration. This second iteration
107522     ** is used to search for the lowest cost scan overall.
107523     **
107524     ** Previous versions of SQLite performed only the second iteration -
107525     ** the next outermost loop was always that with the lowest overall
107526     ** cost. However, this meant that SQLite could select the wrong plan
107527     ** for scripts such as the following:
107528     **   
107529     **   CREATE TABLE t1(a, b); 
107530     **   CREATE TABLE t2(c, d);
107531     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
107532     **
107533     ** The best strategy is to iterate through table t1 first. However it
107534     ** is not possible to determine this with a simple greedy algorithm.
107535     ** Since the cost of a linear scan through table t2 is the same 
107536     ** as the cost of a linear scan through table t1, a simple greedy 
107537     ** algorithm may choose to use t2 for the outer loop, which is a much
107538     ** costlier approach.
107539     */
107540     nUnconstrained = 0;
107541     notIndexed = 0;
107542     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
107543       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
107544         int doNotReorder;    /* True if this table should not be reordered */
107545   
107546         doNotReorder =  (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0;
107547         if( j!=iFrom && doNotReorder ) break;
107548         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
107549         if( (m & sWBI.notValid)==0 ){
107550           if( j==iFrom ) iFrom++;
107551           continue;
107552         }
107553         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
107554         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
107555   
107556         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
107557                     j, sWBI.pSrc->pTab->zName, isOptimal));
107558         assert( sWBI.pSrc->pTab );
107559 #ifndef SQLITE_OMIT_VIRTUALTABLE
107560         if( IsVirtual(sWBI.pSrc->pTab) ){
107561           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
107562           bestVirtualIndex(&sWBI);
107563         }else 
107564 #endif
107565         {
107566           bestBtreeIndex(&sWBI);
107567         }
107568         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
107569
107570         /* If an INDEXED BY clause is present, then the plan must use that
107571         ** index if it uses any index at all */
107572         assert( sWBI.pSrc->pIndex==0 
107573                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107574                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
107575
107576         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107577           notIndexed |= m;
107578         }
107579         if( isOptimal ){
107580           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
107581         }else if( iFrom<nTabList-1 ){
107582           /* If two or more tables have nearly the same outer loop cost,
107583           ** very different inner loop (optimal) cost, we want to choose
107584           ** for the outer loop that table which benefits the least from
107585           ** being in the inner loop.  The following code scales the 
107586           ** outer loop cost estimate to accomplish that. */
107587           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
107588                       sWBI.cost.rCost,
107589                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
107590           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
107591         }
107592
107593         /* Conditions under which this table becomes the best so far:
107594         **
107595         **   (1) The table must not depend on other tables that have not
107596         **       yet run.  (In other words, it must not depend on tables
107597         **       in inner loops.)
107598         **
107599         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
107600         **       cost using the optimal scan cost made this rule obsolete.)
107601         **
107602         **   (3) All tables have an INDEXED BY clause or this table lacks an
107603         **       INDEXED BY clause or this table uses the specific
107604         **       index specified by its INDEXED BY clause.  This rule ensures
107605         **       that a best-so-far is always selected even if an impossible
107606         **       combination of INDEXED BY clauses are given.  The error
107607         **       will be detected and relayed back to the application later.
107608         **       The NEVER() comes about because rule (2) above prevents
107609         **       An indexable full-table-scan from reaching rule (3).
107610         **
107611         **   (4) The plan cost must be lower than prior plans, where "cost"
107612         **       is defined by the compareCost() function above. 
107613         */
107614         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
107615             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
107616                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
107617             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
107618         ){
107619           WHERETRACE(("   === table %d (%s) is best so far\n"
107620                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
107621                       j, sWBI.pSrc->pTab->zName,
107622                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
107623                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
107624           bestPlan = sWBI.cost;
107625           bestJ = j;
107626         }
107627         if( doNotReorder ) break;
107628       }
107629     }
107630     assert( bestJ>=0 );
107631     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
107632     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
107633                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
107634                 bestJ, pTabList->a[bestJ].pTab->zName,
107635                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
107636                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
107637     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
107638       assert( pWInfo->eDistinct==0 );
107639       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
107640     }
107641     andFlags &= bestPlan.plan.wsFlags;
107642     pLevel->plan = bestPlan.plan;
107643     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
107644     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
107645     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
107646     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
107647       if( (wctrlFlags & WHERE_ONETABLE_ONLY) 
107648        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0 
107649       ){
107650         pLevel->iIdxCur = iIdxCur;
107651       }else{
107652         pLevel->iIdxCur = pParse->nTab++;
107653       }
107654     }else{
107655       pLevel->iIdxCur = -1;
107656     }
107657     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
107658     pLevel->iFrom = (u8)bestJ;
107659     if( bestPlan.plan.nRow>=(double)1 ){
107660       pParse->nQueryLoop *= bestPlan.plan.nRow;
107661     }
107662
107663     /* Check that if the table scanned by this loop iteration had an
107664     ** INDEXED BY clause attached to it, that the named index is being
107665     ** used for the scan. If not, then query compilation has failed.
107666     ** Return an error.
107667     */
107668     pIdx = pTabList->a[bestJ].pIndex;
107669     if( pIdx ){
107670       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
107671         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
107672         goto whereBeginError;
107673       }else{
107674         /* If an INDEXED BY clause is used, the bestIndex() function is
107675         ** guaranteed to find the index specified in the INDEXED BY clause
107676         ** if it find an index at all. */
107677         assert( bestPlan.plan.u.pIdx==pIdx );
107678       }
107679     }
107680   }
107681   WHERETRACE(("*** Optimizer Finished ***\n"));
107682   if( pParse->nErr || db->mallocFailed ){
107683     goto whereBeginError;
107684   }
107685   if( nTabList ){
107686     pLevel--;
107687     pWInfo->nOBSat = pLevel->plan.nOBSat;
107688   }else{
107689     pWInfo->nOBSat = 0;
107690   }
107691
107692   /* If the total query only selects a single row, then the ORDER BY
107693   ** clause is irrelevant.
107694   */
107695   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
107696     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
107697     pWInfo->nOBSat = pOrderBy->nExpr;
107698   }
107699
107700   /* If the caller is an UPDATE or DELETE statement that is requesting
107701   ** to use a one-pass algorithm, determine if this is appropriate.
107702   ** The one-pass algorithm only works if the WHERE clause constraints
107703   ** the statement to update a single row.
107704   */
107705   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
107706   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
107707     pWInfo->okOnePass = 1;
107708     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
107709   }
107710
107711   /* Open all tables in the pTabList and any indices selected for
107712   ** searching those tables.
107713   */
107714   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
107715   notReady = ~(Bitmask)0;
107716   pWInfo->nRowOut = (double)1;
107717   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
107718     Table *pTab;     /* Table to open */
107719     int iDb;         /* Index of database containing table/index */
107720     struct SrcList_item *pTabItem;
107721
107722     pTabItem = &pTabList->a[pLevel->iFrom];
107723     pTab = pTabItem->pTab;
107724     pWInfo->nRowOut *= pLevel->plan.nRow;
107725     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107726     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
107727       /* Do nothing */
107728     }else
107729 #ifndef SQLITE_OMIT_VIRTUALTABLE
107730     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107731       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107732       int iCur = pTabItem->iCursor;
107733       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
107734     }else if( IsVirtual(pTab) ){
107735       /* noop */
107736     }else
107737 #endif
107738     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107739          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
107740       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
107741       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
107742       testcase( pTab->nCol==BMS-1 );
107743       testcase( pTab->nCol==BMS );
107744       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
107745         Bitmask b = pTabItem->colUsed;
107746         int n = 0;
107747         for(; b; b=b>>1, n++){}
107748         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
107749                             SQLITE_INT_TO_PTR(n), P4_INT32);
107750         assert( n<=pTab->nCol );
107751       }
107752     }else{
107753       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107754     }
107755 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
107756     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
107757       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
107758     }else
107759 #endif
107760     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107761       Index *pIx = pLevel->plan.u.pIdx;
107762       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
107763       int iIndexCur = pLevel->iIdxCur;
107764       assert( pIx->pSchema==pTab->pSchema );
107765       assert( iIndexCur>=0 );
107766       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
107767                         (char*)pKey, P4_KEYINFO_HANDOFF);
107768       VdbeComment((v, "%s", pIx->zName));
107769     }
107770     sqlite3CodeVerifySchema(pParse, iDb);
107771     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
107772   }
107773   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
107774   if( db->mallocFailed ) goto whereBeginError;
107775
107776   /* Generate the code to do the search.  Each iteration of the for
107777   ** loop below generates code for a single nested loop of the VM
107778   ** program.
107779   */
107780   notReady = ~(Bitmask)0;
107781   for(ii=0; ii<nTabList; ii++){
107782     pLevel = &pWInfo->a[ii];
107783     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
107784     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
107785     pWInfo->iContinue = pLevel->addrCont;
107786   }
107787
107788 #ifdef SQLITE_TEST  /* For testing and debugging use only */
107789   /* Record in the query plan information about the current table
107790   ** and the index used to access it (if any).  If the table itself
107791   ** is not used, its name is just '{}'.  If no index is used
107792   ** the index is listed as "{}".  If the primary key is used the
107793   ** index name is '*'.
107794   */
107795   for(ii=0; ii<nTabList; ii++){
107796     char *z;
107797     int n;
107798     int w;
107799     struct SrcList_item *pTabItem;
107800
107801     pLevel = &pWInfo->a[ii];
107802     w = pLevel->plan.wsFlags;
107803     pTabItem = &pTabList->a[pLevel->iFrom];
107804     z = pTabItem->zAlias;
107805     if( z==0 ) z = pTabItem->pTab->zName;
107806     n = sqlite3Strlen30(z);
107807     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
107808       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
107809         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
107810         nQPlan += 2;
107811       }else{
107812         memcpy(&sqlite3_query_plan[nQPlan], z, n);
107813         nQPlan += n;
107814       }
107815       sqlite3_query_plan[nQPlan++] = ' ';
107816     }
107817     testcase( w & WHERE_ROWID_EQ );
107818     testcase( w & WHERE_ROWID_RANGE );
107819     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107820       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
107821       nQPlan += 2;
107822     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
107823       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
107824       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
107825         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
107826         nQPlan += n;
107827         sqlite3_query_plan[nQPlan++] = ' ';
107828       }
107829     }else{
107830       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
107831       nQPlan += 3;
107832     }
107833   }
107834   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
107835     sqlite3_query_plan[--nQPlan] = 0;
107836   }
107837   sqlite3_query_plan[nQPlan] = 0;
107838   nQPlan = 0;
107839 #endif /* SQLITE_TEST // Testing and debugging use only */
107840
107841   /* Record the continuation address in the WhereInfo structure.  Then
107842   ** clean up and return.
107843   */
107844   return pWInfo;
107845
107846   /* Jump here if malloc fails */
107847 whereBeginError:
107848   if( pWInfo ){
107849     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107850     whereInfoFree(db, pWInfo);
107851   }
107852   return 0;
107853 }
107854
107855 /*
107856 ** Generate the end of the WHERE loop.  See comments on 
107857 ** sqlite3WhereBegin() for additional information.
107858 */
107859 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
107860   Parse *pParse = pWInfo->pParse;
107861   Vdbe *v = pParse->pVdbe;
107862   int i;
107863   WhereLevel *pLevel;
107864   SrcList *pTabList = pWInfo->pTabList;
107865   sqlite3 *db = pParse->db;
107866
107867   /* Generate loop termination code.
107868   */
107869   sqlite3ExprCacheClear(pParse);
107870   for(i=pWInfo->nLevel-1; i>=0; i--){
107871     pLevel = &pWInfo->a[i];
107872     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
107873     if( pLevel->op!=OP_Noop ){
107874       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
107875       sqlite3VdbeChangeP5(v, pLevel->p5);
107876     }
107877     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
107878       struct InLoop *pIn;
107879       int j;
107880       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
107881       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
107882         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
107883         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
107884         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
107885       }
107886       sqlite3DbFree(db, pLevel->u.in.aInLoop);
107887     }
107888     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
107889     if( pLevel->iLeftJoin ){
107890       int addr;
107891       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
107892       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107893            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
107894       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
107895         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
107896       }
107897       if( pLevel->iIdxCur>=0 ){
107898         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
107899       }
107900       if( pLevel->op==OP_Return ){
107901         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
107902       }else{
107903         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
107904       }
107905       sqlite3VdbeJumpHere(v, addr);
107906     }
107907   }
107908
107909   /* The "break" point is here, just past the end of the outer loop.
107910   ** Set it.
107911   */
107912   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
107913
107914   /* Close all of the cursors that were opened by sqlite3WhereBegin.
107915   */
107916   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
107917   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
107918     Index *pIdx = 0;
107919     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
107920     Table *pTab = pTabItem->pTab;
107921     assert( pTab!=0 );
107922     if( (pTab->tabFlags & TF_Ephemeral)==0
107923      && pTab->pSelect==0
107924      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
107925     ){
107926       int ws = pLevel->plan.wsFlags;
107927       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
107928         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
107929       }
107930       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
107931         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
107932       }
107933     }
107934
107935     /* If this scan uses an index, make code substitutions to read data
107936     ** from the index in preference to the table. Sometimes, this means
107937     ** the table need never be read from. This is a performance boost,
107938     ** as the vdbe level waits until the table is read before actually
107939     ** seeking the table cursor to the record corresponding to the current
107940     ** position in the index.
107941     ** 
107942     ** Calls to the code generator in between sqlite3WhereBegin and
107943     ** sqlite3WhereEnd will have created code that references the table
107944     ** directly.  This loop scans all that code looking for opcodes
107945     ** that reference the table and converts them into opcodes that
107946     ** reference the index.
107947     */
107948     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
107949       pIdx = pLevel->plan.u.pIdx;
107950     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
107951       pIdx = pLevel->u.pCovidx;
107952     }
107953     if( pIdx && !db->mallocFailed){
107954       int k, j, last;
107955       VdbeOp *pOp;
107956
107957       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
107958       last = sqlite3VdbeCurrentAddr(v);
107959       for(k=pWInfo->iTop; k<last; k++, pOp++){
107960         if( pOp->p1!=pLevel->iTabCur ) continue;
107961         if( pOp->opcode==OP_Column ){
107962           for(j=0; j<pIdx->nColumn; j++){
107963             if( pOp->p2==pIdx->aiColumn[j] ){
107964               pOp->p2 = j;
107965               pOp->p1 = pLevel->iIdxCur;
107966               break;
107967             }
107968           }
107969           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107970                || j<pIdx->nColumn );
107971         }else if( pOp->opcode==OP_Rowid ){
107972           pOp->p1 = pLevel->iIdxCur;
107973           pOp->opcode = OP_IdxRowid;
107974         }
107975       }
107976     }
107977   }
107978
107979   /* Final cleanup
107980   */
107981   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107982   whereInfoFree(db, pWInfo);
107983   return;
107984 }
107985
107986 /************** End of where.c ***********************************************/
107987 /************** Begin file parse.c *******************************************/
107988 /* Driver template for the LEMON parser generator.
107989 ** The author disclaims copyright to this source code.
107990 **
107991 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
107992 ** The only modifications are the addition of a couple of NEVER()
107993 ** macros to disable tests that are needed in the case of a general
107994 ** LALR(1) grammar but which are always false in the
107995 ** specific grammar used by SQLite.
107996 */
107997 /* First off, code is included that follows the "include" declaration
107998 ** in the input grammar file. */
107999 /* #include <stdio.h> */
108000
108001
108002 /*
108003 ** Disable all error recovery processing in the parser push-down
108004 ** automaton.
108005 */
108006 #define YYNOERRORRECOVERY 1
108007
108008 /*
108009 ** Make yytestcase() the same as testcase()
108010 */
108011 #define yytestcase(X) testcase(X)
108012
108013 /*
108014 ** An instance of this structure holds information about the
108015 ** LIMIT clause of a SELECT statement.
108016 */
108017 struct LimitVal {
108018   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
108019   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
108020 };
108021
108022 /*
108023 ** An instance of this structure is used to store the LIKE,
108024 ** GLOB, NOT LIKE, and NOT GLOB operators.
108025 */
108026 struct LikeOp {
108027   Token eOperator;  /* "like" or "glob" or "regexp" */
108028   int bNot;         /* True if the NOT keyword is present */
108029 };
108030
108031 /*
108032 ** An instance of the following structure describes the event of a
108033 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
108034 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
108035 **
108036 **      UPDATE ON (a,b,c)
108037 **
108038 ** Then the "b" IdList records the list "a,b,c".
108039 */
108040 struct TrigEvent { int a; IdList * b; };
108041
108042 /*
108043 ** An instance of this structure holds the ATTACH key and the key type.
108044 */
108045 struct AttachKey { int type;  Token key; };
108046
108047 /*
108048 ** One or more VALUES claues
108049 */
108050 struct ValueList {
108051   ExprList *pList;
108052   Select *pSelect;
108053 };
108054
108055
108056   /* This is a utility routine used to set the ExprSpan.zStart and
108057   ** ExprSpan.zEnd values of pOut so that the span covers the complete
108058   ** range of text beginning with pStart and going to the end of pEnd.
108059   */
108060   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
108061     pOut->zStart = pStart->z;
108062     pOut->zEnd = &pEnd->z[pEnd->n];
108063   }
108064
108065   /* Construct a new Expr object from a single identifier.  Use the
108066   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
108067   ** that created the expression.
108068   */
108069   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
108070     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
108071     pOut->zStart = pValue->z;
108072     pOut->zEnd = &pValue->z[pValue->n];
108073   }
108074
108075   /* This routine constructs a binary expression node out of two ExprSpan
108076   ** objects and uses the result to populate a new ExprSpan object.
108077   */
108078   static void spanBinaryExpr(
108079     ExprSpan *pOut,     /* Write the result here */
108080     Parse *pParse,      /* The parsing context.  Errors accumulate here */
108081     int op,             /* The binary operation */
108082     ExprSpan *pLeft,    /* The left operand */
108083     ExprSpan *pRight    /* The right operand */
108084   ){
108085     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
108086     pOut->zStart = pLeft->zStart;
108087     pOut->zEnd = pRight->zEnd;
108088   }
108089
108090   /* Construct an expression node for a unary postfix operator
108091   */
108092   static void spanUnaryPostfix(
108093     ExprSpan *pOut,        /* Write the new expression node here */
108094     Parse *pParse,         /* Parsing context to record errors */
108095     int op,                /* The operator */
108096     ExprSpan *pOperand,    /* The operand */
108097     Token *pPostOp         /* The operand token for setting the span */
108098   ){
108099     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108100     pOut->zStart = pOperand->zStart;
108101     pOut->zEnd = &pPostOp->z[pPostOp->n];
108102   }                           
108103
108104   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
108105   ** unary TK_ISNULL or TK_NOTNULL expression. */
108106   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
108107     sqlite3 *db = pParse->db;
108108     if( db->mallocFailed==0 && pY->op==TK_NULL ){
108109       pA->op = (u8)op;
108110       sqlite3ExprDelete(db, pA->pRight);
108111       pA->pRight = 0;
108112     }
108113   }
108114
108115   /* Construct an expression node for a unary prefix operator
108116   */
108117   static void spanUnaryPrefix(
108118     ExprSpan *pOut,        /* Write the new expression node here */
108119     Parse *pParse,         /* Parsing context to record errors */
108120     int op,                /* The operator */
108121     ExprSpan *pOperand,    /* The operand */
108122     Token *pPreOp         /* The operand token for setting the span */
108123   ){
108124     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108125     pOut->zStart = pPreOp->z;
108126     pOut->zEnd = pOperand->zEnd;
108127   }
108128 /* Next is all token values, in a form suitable for use by makeheaders.
108129 ** This section will be null unless lemon is run with the -m switch.
108130 */
108131 /* 
108132 ** These constants (all generated automatically by the parser generator)
108133 ** specify the various kinds of tokens (terminals) that the parser
108134 ** understands. 
108135 **
108136 ** Each symbol here is a terminal symbol in the grammar.
108137 */
108138 /* Make sure the INTERFACE macro is defined.
108139 */
108140 #ifndef INTERFACE
108141 # define INTERFACE 1
108142 #endif
108143 /* The next thing included is series of defines which control
108144 ** various aspects of the generated parser.
108145 **    YYCODETYPE         is the data type used for storing terminal
108146 **                       and nonterminal numbers.  "unsigned char" is
108147 **                       used if there are fewer than 250 terminals
108148 **                       and nonterminals.  "int" is used otherwise.
108149 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
108150 **                       to no legal terminal or nonterminal number.  This
108151 **                       number is used to fill in empty slots of the hash 
108152 **                       table.
108153 **    YYFALLBACK         If defined, this indicates that one or more tokens
108154 **                       have fall-back values which should be used if the
108155 **                       original value of the token will not parse.
108156 **    YYACTIONTYPE       is the data type used for storing terminal
108157 **                       and nonterminal numbers.  "unsigned char" is
108158 **                       used if there are fewer than 250 rules and
108159 **                       states combined.  "int" is used otherwise.
108160 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
108161 **                       directly to the parser from the tokenizer.
108162 **    YYMINORTYPE        is the data type used for all minor tokens.
108163 **                       This is typically a union of many types, one of
108164 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
108165 **                       for base tokens is called "yy0".
108166 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
108167 **                       zero the stack is dynamically sized using realloc()
108168 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
108169 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
108170 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
108171 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
108172 **    YYNSTATE           the combined number of states.
108173 **    YYNRULE            the number of rules in the grammar
108174 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
108175 **                       defined, then do no error processing.
108176 */
108177 #define YYCODETYPE unsigned char
108178 #define YYNOCODE 251
108179 #define YYACTIONTYPE unsigned short int
108180 #define YYWILDCARD 67
108181 #define sqlite3ParserTOKENTYPE Token
108182 typedef union {
108183   int yyinit;
108184   sqlite3ParserTOKENTYPE yy0;
108185   struct LimitVal yy64;
108186   Expr* yy122;
108187   Select* yy159;
108188   IdList* yy180;
108189   struct {int value; int mask;} yy207;
108190   u8 yy258;
108191   struct LikeOp yy318;
108192   TriggerStep* yy327;
108193   ExprSpan yy342;
108194   SrcList* yy347;
108195   int yy392;
108196   struct TrigEvent yy410;
108197   ExprList* yy442;
108198   struct ValueList yy487;
108199 } YYMINORTYPE;
108200 #ifndef YYSTACKDEPTH
108201 #define YYSTACKDEPTH 100
108202 #endif
108203 #define sqlite3ParserARG_SDECL Parse *pParse;
108204 #define sqlite3ParserARG_PDECL ,Parse *pParse
108205 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
108206 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
108207 #define YYNSTATE 627
108208 #define YYNRULE 327
108209 #define YYFALLBACK 1
108210 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
108211 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
108212 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
108213
108214 /* The yyzerominor constant is used to initialize instances of
108215 ** YYMINORTYPE objects to zero. */
108216 static const YYMINORTYPE yyzerominor = { 0 };
108217
108218 /* Define the yytestcase() macro to be a no-op if is not already defined
108219 ** otherwise.
108220 **
108221 ** Applications can choose to define yytestcase() in the %include section
108222 ** to a macro that can assist in verifying code coverage.  For production
108223 ** code the yytestcase() macro should be turned off.  But it is useful
108224 ** for testing.
108225 */
108226 #ifndef yytestcase
108227 # define yytestcase(X)
108228 #endif
108229
108230
108231 /* Next are the tables used to determine what action to take based on the
108232 ** current state and lookahead token.  These tables are used to implement
108233 ** functions that take a state number and lookahead value and return an
108234 ** action integer.  
108235 **
108236 ** Suppose the action integer is N.  Then the action is determined as
108237 ** follows
108238 **
108239 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
108240 **                                      token onto the stack and goto state N.
108241 **
108242 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
108243 **
108244 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
108245 **
108246 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
108247 **
108248 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
108249 **                                      slots in the yy_action[] table.
108250 **
108251 ** The action table is constructed as a single large table named yy_action[].
108252 ** Given state S and lookahead X, the action is computed as
108253 **
108254 **      yy_action[ yy_shift_ofst[S] + X ]
108255 **
108256 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
108257 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
108258 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
108259 ** and that yy_default[S] should be used instead.  
108260 **
108261 ** The formula above is for computing the action when the lookahead is
108262 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
108263 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
108264 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
108265 ** YY_SHIFT_USE_DFLT.
108266 **
108267 ** The following are the tables generated in this section:
108268 **
108269 **  yy_action[]        A single table containing all actions.
108270 **  yy_lookahead[]     A table containing the lookahead for each entry in
108271 **                     yy_action.  Used to detect hash collisions.
108272 **  yy_shift_ofst[]    For each state, the offset into yy_action for
108273 **                     shifting terminals.
108274 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
108275 **                     shifting non-terminals after a reduce.
108276 **  yy_default[]       Default action for each state.
108277 */
108278 #define YY_ACTTAB_COUNT (1564)
108279 static const YYACTIONTYPE yy_action[] = {
108280  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
108281  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
108282  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
108283  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
108284  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
108285  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108286  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
108287  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
108288  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108289  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
108290  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
108291  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
108292  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
108293  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
108294  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
108295  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
108296  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
108297  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
108298  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
108299  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
108300  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
108301  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108302  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
108303  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
108304  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
108305  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
108306  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
108307  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
108308  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
108309  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
108310  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
108311  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
108312  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
108313  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
108314  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
108315  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
108316  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
108317  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
108318  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
108319  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
108320  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
108321  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
108322  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108323  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
108324  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
108325  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
108326  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
108327  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
108328  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
108329  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
108330  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
108331  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
108332  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
108333  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
108334  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
108335  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
108336  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
108337  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
108338  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108339  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
108340  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
108341  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
108342  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
108343  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
108344  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
108345  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
108346  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
108347  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
108348  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
108349  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
108350  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
108351  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
108352  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
108353  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
108354  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
108355  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
108356  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
108357  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
108358  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
108359  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108360  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
108361  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
108362  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
108363  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
108364  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
108365  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
108366  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
108367  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
108368  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
108369  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
108370  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
108371  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
108372  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
108373  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
108374  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
108375  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108376  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
108377  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
108378  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
108379  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
108380  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
108381  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
108382  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
108383  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
108384  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
108385  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
108386  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
108387  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
108388  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
108389  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
108390  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
108391  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
108392  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
108393  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
108394  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
108395  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
108396  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108397  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
108398  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
108399  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
108400  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
108401  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
108402  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
108403  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
108404  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
108405  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
108406  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
108407  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
108408  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
108409  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
108410  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
108411  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
108412  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
108413  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
108414  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
108415  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
108416  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
108417  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
108418  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
108419  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
108420  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
108421  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
108422  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
108423  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
108424  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
108425  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
108426  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
108427  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
108428  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
108429  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
108430  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
108431  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
108432  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
108433  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
108434  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
108435  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
108436  /*  1560 */   295,  498,  956,  488,
108437 };
108438 static const YYCODETYPE yy_lookahead[] = {
108439  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
108440  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
108441  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
108442  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
108443  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
108444  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108445  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
108446  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
108447  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108448  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
108449  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
108450  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
108451  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
108452  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
108453  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
108454  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
108455  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
108456  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
108457  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
108458  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
108459  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108460  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108461  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
108462  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
108463  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
108464  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
108465  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
108466  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108467  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
108468  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
108469  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
108470  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
108471  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
108472  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
108473  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
108474  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
108475  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108476  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
108477  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
108478  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
108479  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
108480  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
108481  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108482  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
108483  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
108484  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
108485  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
108486  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
108487  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
108488  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
108489  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
108490  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
108491  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
108492  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
108493  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
108494  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
108495  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
108496  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108497  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108498  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
108499  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
108500  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
108501  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
108502  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
108503  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108504  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
108505  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
108506  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
108507  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
108508  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
108509  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
108510  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
108511  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
108512  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108513  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
108514  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
108515  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
108516  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
108517  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
108518  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108519  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
108520  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
108521  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
108522  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
108523  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
108524  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
108525  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
108526  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
108527  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
108528  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
108529  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
108530  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
108531  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
108532  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
108533  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108534  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108535  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
108536  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
108537  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
108538  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
108539  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
108540  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108541  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
108542  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
108543  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
108544  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
108545  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
108546  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
108547  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
108548  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
108549  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108550  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
108551  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
108552  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
108553  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
108554  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
108555  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108556  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
108557  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
108558  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
108559  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
108560  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
108561  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
108562  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
108563  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
108564  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
108565  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
108566  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
108567  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
108568  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
108569  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
108570  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
108571  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
108572  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
108573  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
108574  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
108575  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
108576  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
108577  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
108578  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
108579  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
108580  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
108581  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
108582  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
108583  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
108584  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
108585  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
108586  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
108587  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
108588  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
108589  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
108590  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
108591  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
108592  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
108593  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
108594  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
108595  /*  1560 */   195,  182,  250,  186,
108596 };
108597 #define YY_SHIFT_USE_DFLT (-70)
108598 #define YY_SHIFT_COUNT (416)
108599 #define YY_SHIFT_MIN   (-69)
108600 #define YY_SHIFT_MAX   (1487)
108601 static const short yy_shift_ofst[] = {
108602  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
108603  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
108604  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108605  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108606  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
108607  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108608  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
108609  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
108610  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
108611  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
108612  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
108613  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
108614  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
108615  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
108616  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
108617  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
108618  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
108619  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
108620  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
108621  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
108622  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
108623  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
108624  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
108625  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
108626  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
108627  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
108628  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
108629  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
108630  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
108631  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
108632  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
108633  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
108634  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
108635  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
108636  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
108637  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
108638  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
108639  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
108640  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
108641  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
108642  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
108643  /*   410 */    92,   75,   45,  114,   25,   11,    5,
108644 };
108645 #define YY_REDUCE_USE_DFLT (-169)
108646 #define YY_REDUCE_COUNT (308)
108647 #define YY_REDUCE_MIN   (-168)
108648 #define YY_REDUCE_MAX   (1391)
108649 static const short yy_reduce_ofst[] = {
108650  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
108651  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
108652  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
108653  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
108654  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
108655  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
108656  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
108657  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
108658  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
108659  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
108660  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
108661  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
108662  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
108663  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
108664  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
108665  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
108666  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
108667  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
108668  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
108669  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
108670  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
108671  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
108672  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
108673  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
108674  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
108675  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
108676  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
108677  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
108678  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
108679  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
108680  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
108681 };
108682 static const YYACTIONTYPE yy_default[] = {
108683  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
108684  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
108685  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108686  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108687  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108688  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108689  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
108690  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
108691  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
108692  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
108693  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
108694  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108695  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
108696  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
108697  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108698  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
108699  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108700  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108701  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
108702  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108703  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
108704  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
108705  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
108706  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
108707  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
108708  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
108709  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
108710  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
108711  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
108712  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
108713  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
108714  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
108715  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
108716  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
108717  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
108718  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
108719  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
108720  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108721  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
108722  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
108723  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
108724  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
108725  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
108726  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
108727  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
108728  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
108729  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
108730  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
108731  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
108732  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
108733  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
108734  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
108735  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
108736  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
108737  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
108738  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
108739  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
108740  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
108741  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
108742  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
108743  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
108744  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
108745  /*   620 */   665,  639,  636,  635,  631,  630,  628,
108746 };
108747
108748 /* The next table maps tokens into fallback tokens.  If a construct
108749 ** like the following:
108750 ** 
108751 **      %fallback ID X Y Z.
108752 **
108753 ** appears in the grammar, then ID becomes a fallback token for X, Y,
108754 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
108755 ** but it does not parse, the type of the token is changed to ID and
108756 ** the parse is retried before an error is thrown.
108757 */
108758 #ifdef YYFALLBACK
108759 static const YYCODETYPE yyFallback[] = {
108760     0,  /*          $ => nothing */
108761     0,  /*       SEMI => nothing */
108762    26,  /*    EXPLAIN => ID */
108763    26,  /*      QUERY => ID */
108764    26,  /*       PLAN => ID */
108765    26,  /*      BEGIN => ID */
108766     0,  /* TRANSACTION => nothing */
108767    26,  /*   DEFERRED => ID */
108768    26,  /*  IMMEDIATE => ID */
108769    26,  /*  EXCLUSIVE => ID */
108770     0,  /*     COMMIT => nothing */
108771    26,  /*        END => ID */
108772    26,  /*   ROLLBACK => ID */
108773    26,  /*  SAVEPOINT => ID */
108774    26,  /*    RELEASE => ID */
108775     0,  /*         TO => nothing */
108776     0,  /*      TABLE => nothing */
108777     0,  /*     CREATE => nothing */
108778    26,  /*         IF => ID */
108779     0,  /*        NOT => nothing */
108780     0,  /*     EXISTS => nothing */
108781    26,  /*       TEMP => ID */
108782     0,  /*         LP => nothing */
108783     0,  /*         RP => nothing */
108784     0,  /*         AS => nothing */
108785     0,  /*      COMMA => nothing */
108786     0,  /*         ID => nothing */
108787     0,  /*    INDEXED => nothing */
108788    26,  /*      ABORT => ID */
108789    26,  /*     ACTION => ID */
108790    26,  /*      AFTER => ID */
108791    26,  /*    ANALYZE => ID */
108792    26,  /*        ASC => ID */
108793    26,  /*     ATTACH => ID */
108794    26,  /*     BEFORE => ID */
108795    26,  /*         BY => ID */
108796    26,  /*    CASCADE => ID */
108797    26,  /*       CAST => ID */
108798    26,  /*   COLUMNKW => ID */
108799    26,  /*   CONFLICT => ID */
108800    26,  /*   DATABASE => ID */
108801    26,  /*       DESC => ID */
108802    26,  /*     DETACH => ID */
108803    26,  /*       EACH => ID */
108804    26,  /*       FAIL => ID */
108805    26,  /*        FOR => ID */
108806    26,  /*     IGNORE => ID */
108807    26,  /*  INITIALLY => ID */
108808    26,  /*    INSTEAD => ID */
108809    26,  /*    LIKE_KW => ID */
108810    26,  /*      MATCH => ID */
108811    26,  /*         NO => ID */
108812    26,  /*        KEY => ID */
108813    26,  /*         OF => ID */
108814    26,  /*     OFFSET => ID */
108815    26,  /*     PRAGMA => ID */
108816    26,  /*      RAISE => ID */
108817    26,  /*    REPLACE => ID */
108818    26,  /*   RESTRICT => ID */
108819    26,  /*        ROW => ID */
108820    26,  /*    TRIGGER => ID */
108821    26,  /*     VACUUM => ID */
108822    26,  /*       VIEW => ID */
108823    26,  /*    VIRTUAL => ID */
108824    26,  /*    REINDEX => ID */
108825    26,  /*     RENAME => ID */
108826    26,  /*   CTIME_KW => ID */
108827 };
108828 #endif /* YYFALLBACK */
108829
108830 /* The following structure represents a single element of the
108831 ** parser's stack.  Information stored includes:
108832 **
108833 **   +  The state number for the parser at this level of the stack.
108834 **
108835 **   +  The value of the token stored at this level of the stack.
108836 **      (In other words, the "major" token.)
108837 **
108838 **   +  The semantic value stored at this level of the stack.  This is
108839 **      the information used by the action routines in the grammar.
108840 **      It is sometimes called the "minor" token.
108841 */
108842 struct yyStackEntry {
108843   YYACTIONTYPE stateno;  /* The state-number */
108844   YYCODETYPE major;      /* The major token value.  This is the code
108845                          ** number for the token at this stack level */
108846   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
108847                          ** is the value of the token  */
108848 };
108849 typedef struct yyStackEntry yyStackEntry;
108850
108851 /* The state of the parser is completely contained in an instance of
108852 ** the following structure */
108853 struct yyParser {
108854   int yyidx;                    /* Index of top element in stack */
108855 #ifdef YYTRACKMAXSTACKDEPTH
108856   int yyidxMax;                 /* Maximum value of yyidx */
108857 #endif
108858   int yyerrcnt;                 /* Shifts left before out of the error */
108859   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
108860 #if YYSTACKDEPTH<=0
108861   int yystksz;                  /* Current side of the stack */
108862   yyStackEntry *yystack;        /* The parser's stack */
108863 #else
108864   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
108865 #endif
108866 };
108867 typedef struct yyParser yyParser;
108868
108869 #ifndef NDEBUG
108870 /* #include <stdio.h> */
108871 static FILE *yyTraceFILE = 0;
108872 static char *yyTracePrompt = 0;
108873 #endif /* NDEBUG */
108874
108875 #ifndef NDEBUG
108876 /* 
108877 ** Turn parser tracing on by giving a stream to which to write the trace
108878 ** and a prompt to preface each trace message.  Tracing is turned off
108879 ** by making either argument NULL 
108880 **
108881 ** Inputs:
108882 ** <ul>
108883 ** <li> A FILE* to which trace output should be written.
108884 **      If NULL, then tracing is turned off.
108885 ** <li> A prefix string written at the beginning of every
108886 **      line of trace output.  If NULL, then tracing is
108887 **      turned off.
108888 ** </ul>
108889 **
108890 ** Outputs:
108891 ** None.
108892 */
108893 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
108894   yyTraceFILE = TraceFILE;
108895   yyTracePrompt = zTracePrompt;
108896   if( yyTraceFILE==0 ) yyTracePrompt = 0;
108897   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
108898 }
108899 #endif /* NDEBUG */
108900
108901 #ifndef NDEBUG
108902 /* For tracing shifts, the names of all terminals and nonterminals
108903 ** are required.  The following table supplies these names */
108904 static const char *const yyTokenName[] = { 
108905   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
108906   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
108907   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
108908   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
108909   "TABLE",         "CREATE",        "IF",            "NOT",         
108910   "EXISTS",        "TEMP",          "LP",            "RP",          
108911   "AS",            "COMMA",         "ID",            "INDEXED",     
108912   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
108913   "ASC",           "ATTACH",        "BEFORE",        "BY",          
108914   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
108915   "DATABASE",      "DESC",          "DETACH",        "EACH",        
108916   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
108917   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
108918   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
108919   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
108920   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
108921   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
108922   "OR",            "AND",           "IS",            "BETWEEN",     
108923   "IN",            "ISNULL",        "NOTNULL",       "NE",          
108924   "EQ",            "GT",            "LE",            "LT",          
108925   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
108926   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
108927   "STAR",          "SLASH",         "REM",           "CONCAT",      
108928   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
108929   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
108930   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
108931   "ON",            "INSERT",        "DELETE",        "UPDATE",      
108932   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
108933   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
108934   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
108935   "JOIN",          "USING",         "ORDER",         "GROUP",       
108936   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
108937   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
108938   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
108939   "THEN",          "ELSE",          "INDEX",         "ALTER",       
108940   "ADD",           "error",         "input",         "cmdlist",     
108941   "ecmd",          "explain",       "cmdx",          "cmd",         
108942   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
108943   "create_table",  "create_table_args",  "createkw",      "temp",        
108944   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
108945   "select",        "column",        "columnid",      "type",        
108946   "carglist",      "id",            "ids",           "typetoken",   
108947   "typename",      "signed",        "plus_num",      "minus_num",   
108948   "ccons",         "term",          "expr",          "onconf",      
108949   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
108950   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
108951   "conslist",      "tconscomma",    "tcons",         "idxlist",     
108952   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
108953   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
108954   "distinct",      "selcollist",    "from",          "where_opt",   
108955   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
108956   "sclp",          "as",            "seltablist",    "stl_prefix",  
108957   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
108958   "joinop2",       "inscollist",    "sortlist",      "nexprlist",   
108959   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",   
108960   "exprlist",      "likeop",        "between_op",    "in_op",       
108961   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",  
108962   "collate",       "nmnum",         "number",        "trigger_decl",
108963   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
108964   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
108965   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
108966   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
108967   "lp",            "anylist",     
108968 };
108969 #endif /* NDEBUG */
108970
108971 #ifndef NDEBUG
108972 /* For tracing reduce actions, the names of all rules are required.
108973 */
108974 static const char *const yyRuleName[] = {
108975  /*   0 */ "input ::= cmdlist",
108976  /*   1 */ "cmdlist ::= cmdlist ecmd",
108977  /*   2 */ "cmdlist ::= ecmd",
108978  /*   3 */ "ecmd ::= SEMI",
108979  /*   4 */ "ecmd ::= explain cmdx SEMI",
108980  /*   5 */ "explain ::=",
108981  /*   6 */ "explain ::= EXPLAIN",
108982  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
108983  /*   8 */ "cmdx ::= cmd",
108984  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
108985  /*  10 */ "trans_opt ::=",
108986  /*  11 */ "trans_opt ::= TRANSACTION",
108987  /*  12 */ "trans_opt ::= TRANSACTION nm",
108988  /*  13 */ "transtype ::=",
108989  /*  14 */ "transtype ::= DEFERRED",
108990  /*  15 */ "transtype ::= IMMEDIATE",
108991  /*  16 */ "transtype ::= EXCLUSIVE",
108992  /*  17 */ "cmd ::= COMMIT trans_opt",
108993  /*  18 */ "cmd ::= END trans_opt",
108994  /*  19 */ "cmd ::= ROLLBACK trans_opt",
108995  /*  20 */ "savepoint_opt ::= SAVEPOINT",
108996  /*  21 */ "savepoint_opt ::=",
108997  /*  22 */ "cmd ::= SAVEPOINT nm",
108998  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
108999  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
109000  /*  25 */ "cmd ::= create_table create_table_args",
109001  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
109002  /*  27 */ "createkw ::= CREATE",
109003  /*  28 */ "ifnotexists ::=",
109004  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
109005  /*  30 */ "temp ::= TEMP",
109006  /*  31 */ "temp ::=",
109007  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
109008  /*  33 */ "create_table_args ::= AS select",
109009  /*  34 */ "columnlist ::= columnlist COMMA column",
109010  /*  35 */ "columnlist ::= column",
109011  /*  36 */ "column ::= columnid type carglist",
109012  /*  37 */ "columnid ::= nm",
109013  /*  38 */ "id ::= ID",
109014  /*  39 */ "id ::= INDEXED",
109015  /*  40 */ "ids ::= ID|STRING",
109016  /*  41 */ "nm ::= id",
109017  /*  42 */ "nm ::= STRING",
109018  /*  43 */ "nm ::= JOIN_KW",
109019  /*  44 */ "type ::=",
109020  /*  45 */ "type ::= typetoken",
109021  /*  46 */ "typetoken ::= typename",
109022  /*  47 */ "typetoken ::= typename LP signed RP",
109023  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
109024  /*  49 */ "typename ::= ids",
109025  /*  50 */ "typename ::= typename ids",
109026  /*  51 */ "signed ::= plus_num",
109027  /*  52 */ "signed ::= minus_num",
109028  /*  53 */ "carglist ::= carglist ccons",
109029  /*  54 */ "carglist ::=",
109030  /*  55 */ "ccons ::= CONSTRAINT nm",
109031  /*  56 */ "ccons ::= DEFAULT term",
109032  /*  57 */ "ccons ::= DEFAULT LP expr RP",
109033  /*  58 */ "ccons ::= DEFAULT PLUS term",
109034  /*  59 */ "ccons ::= DEFAULT MINUS term",
109035  /*  60 */ "ccons ::= DEFAULT id",
109036  /*  61 */ "ccons ::= NULL onconf",
109037  /*  62 */ "ccons ::= NOT NULL onconf",
109038  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
109039  /*  64 */ "ccons ::= UNIQUE onconf",
109040  /*  65 */ "ccons ::= CHECK LP expr RP",
109041  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
109042  /*  67 */ "ccons ::= defer_subclause",
109043  /*  68 */ "ccons ::= COLLATE ids",
109044  /*  69 */ "autoinc ::=",
109045  /*  70 */ "autoinc ::= AUTOINCR",
109046  /*  71 */ "refargs ::=",
109047  /*  72 */ "refargs ::= refargs refarg",
109048  /*  73 */ "refarg ::= MATCH nm",
109049  /*  74 */ "refarg ::= ON INSERT refact",
109050  /*  75 */ "refarg ::= ON DELETE refact",
109051  /*  76 */ "refarg ::= ON UPDATE refact",
109052  /*  77 */ "refact ::= SET NULL",
109053  /*  78 */ "refact ::= SET DEFAULT",
109054  /*  79 */ "refact ::= CASCADE",
109055  /*  80 */ "refact ::= RESTRICT",
109056  /*  81 */ "refact ::= NO ACTION",
109057  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
109058  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
109059  /*  84 */ "init_deferred_pred_opt ::=",
109060  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
109061  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
109062  /*  87 */ "conslist_opt ::=",
109063  /*  88 */ "conslist_opt ::= COMMA conslist",
109064  /*  89 */ "conslist ::= conslist tconscomma tcons",
109065  /*  90 */ "conslist ::= tcons",
109066  /*  91 */ "tconscomma ::= COMMA",
109067  /*  92 */ "tconscomma ::=",
109068  /*  93 */ "tcons ::= CONSTRAINT nm",
109069  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
109070  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
109071  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
109072  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
109073  /*  98 */ "defer_subclause_opt ::=",
109074  /*  99 */ "defer_subclause_opt ::= defer_subclause",
109075  /* 100 */ "onconf ::=",
109076  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
109077  /* 102 */ "orconf ::=",
109078  /* 103 */ "orconf ::= OR resolvetype",
109079  /* 104 */ "resolvetype ::= raisetype",
109080  /* 105 */ "resolvetype ::= IGNORE",
109081  /* 106 */ "resolvetype ::= REPLACE",
109082  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
109083  /* 108 */ "ifexists ::= IF EXISTS",
109084  /* 109 */ "ifexists ::=",
109085  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
109086  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
109087  /* 112 */ "cmd ::= select",
109088  /* 113 */ "select ::= oneselect",
109089  /* 114 */ "select ::= select multiselect_op oneselect",
109090  /* 115 */ "multiselect_op ::= UNION",
109091  /* 116 */ "multiselect_op ::= UNION ALL",
109092  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
109093  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
109094  /* 119 */ "distinct ::= DISTINCT",
109095  /* 120 */ "distinct ::= ALL",
109096  /* 121 */ "distinct ::=",
109097  /* 122 */ "sclp ::= selcollist COMMA",
109098  /* 123 */ "sclp ::=",
109099  /* 124 */ "selcollist ::= sclp expr as",
109100  /* 125 */ "selcollist ::= sclp STAR",
109101  /* 126 */ "selcollist ::= sclp nm DOT STAR",
109102  /* 127 */ "as ::= AS nm",
109103  /* 128 */ "as ::= ids",
109104  /* 129 */ "as ::=",
109105  /* 130 */ "from ::=",
109106  /* 131 */ "from ::= FROM seltablist",
109107  /* 132 */ "stl_prefix ::= seltablist joinop",
109108  /* 133 */ "stl_prefix ::=",
109109  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
109110  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
109111  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
109112  /* 137 */ "dbnm ::=",
109113  /* 138 */ "dbnm ::= DOT nm",
109114  /* 139 */ "fullname ::= nm dbnm",
109115  /* 140 */ "joinop ::= COMMA|JOIN",
109116  /* 141 */ "joinop ::= JOIN_KW JOIN",
109117  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
109118  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
109119  /* 144 */ "on_opt ::= ON expr",
109120  /* 145 */ "on_opt ::=",
109121  /* 146 */ "indexed_opt ::=",
109122  /* 147 */ "indexed_opt ::= INDEXED BY nm",
109123  /* 148 */ "indexed_opt ::= NOT INDEXED",
109124  /* 149 */ "using_opt ::= USING LP inscollist RP",
109125  /* 150 */ "using_opt ::=",
109126  /* 151 */ "orderby_opt ::=",
109127  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
109128  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
109129  /* 154 */ "sortlist ::= expr sortorder",
109130  /* 155 */ "sortorder ::= ASC",
109131  /* 156 */ "sortorder ::= DESC",
109132  /* 157 */ "sortorder ::=",
109133  /* 158 */ "groupby_opt ::=",
109134  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
109135  /* 160 */ "having_opt ::=",
109136  /* 161 */ "having_opt ::= HAVING expr",
109137  /* 162 */ "limit_opt ::=",
109138  /* 163 */ "limit_opt ::= LIMIT expr",
109139  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
109140  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
109141  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
109142  /* 167 */ "where_opt ::=",
109143  /* 168 */ "where_opt ::= WHERE expr",
109144  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
109145  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
109146  /* 171 */ "setlist ::= nm EQ expr",
109147  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
109148  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
109149  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
109150  /* 175 */ "insert_cmd ::= INSERT orconf",
109151  /* 176 */ "insert_cmd ::= REPLACE",
109152  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
109153  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
109154  /* 179 */ "inscollist_opt ::=",
109155  /* 180 */ "inscollist_opt ::= LP inscollist RP",
109156  /* 181 */ "inscollist ::= inscollist COMMA nm",
109157  /* 182 */ "inscollist ::= nm",
109158  /* 183 */ "expr ::= term",
109159  /* 184 */ "expr ::= LP expr RP",
109160  /* 185 */ "term ::= NULL",
109161  /* 186 */ "expr ::= id",
109162  /* 187 */ "expr ::= JOIN_KW",
109163  /* 188 */ "expr ::= nm DOT nm",
109164  /* 189 */ "expr ::= nm DOT nm DOT nm",
109165  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
109166  /* 191 */ "term ::= STRING",
109167  /* 192 */ "expr ::= REGISTER",
109168  /* 193 */ "expr ::= VARIABLE",
109169  /* 194 */ "expr ::= expr COLLATE ids",
109170  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
109171  /* 196 */ "expr ::= ID LP distinct exprlist RP",
109172  /* 197 */ "expr ::= ID LP STAR RP",
109173  /* 198 */ "term ::= CTIME_KW",
109174  /* 199 */ "expr ::= expr AND expr",
109175  /* 200 */ "expr ::= expr OR expr",
109176  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
109177  /* 202 */ "expr ::= expr EQ|NE expr",
109178  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
109179  /* 204 */ "expr ::= expr PLUS|MINUS expr",
109180  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
109181  /* 206 */ "expr ::= expr CONCAT expr",
109182  /* 207 */ "likeop ::= LIKE_KW",
109183  /* 208 */ "likeop ::= NOT LIKE_KW",
109184  /* 209 */ "likeop ::= MATCH",
109185  /* 210 */ "likeop ::= NOT MATCH",
109186  /* 211 */ "expr ::= expr likeop expr",
109187  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
109188  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
109189  /* 214 */ "expr ::= expr NOT NULL",
109190  /* 215 */ "expr ::= expr IS expr",
109191  /* 216 */ "expr ::= expr IS NOT expr",
109192  /* 217 */ "expr ::= NOT expr",
109193  /* 218 */ "expr ::= BITNOT expr",
109194  /* 219 */ "expr ::= MINUS expr",
109195  /* 220 */ "expr ::= PLUS expr",
109196  /* 221 */ "between_op ::= BETWEEN",
109197  /* 222 */ "between_op ::= NOT BETWEEN",
109198  /* 223 */ "expr ::= expr between_op expr AND expr",
109199  /* 224 */ "in_op ::= IN",
109200  /* 225 */ "in_op ::= NOT IN",
109201  /* 226 */ "expr ::= expr in_op LP exprlist RP",
109202  /* 227 */ "expr ::= LP select RP",
109203  /* 228 */ "expr ::= expr in_op LP select RP",
109204  /* 229 */ "expr ::= expr in_op nm dbnm",
109205  /* 230 */ "expr ::= EXISTS LP select RP",
109206  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
109207  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
109208  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
109209  /* 234 */ "case_else ::= ELSE expr",
109210  /* 235 */ "case_else ::=",
109211  /* 236 */ "case_operand ::= expr",
109212  /* 237 */ "case_operand ::=",
109213  /* 238 */ "exprlist ::= nexprlist",
109214  /* 239 */ "exprlist ::=",
109215  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
109216  /* 241 */ "nexprlist ::= expr",
109217  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
109218  /* 243 */ "uniqueflag ::= UNIQUE",
109219  /* 244 */ "uniqueflag ::=",
109220  /* 245 */ "idxlist_opt ::=",
109221  /* 246 */ "idxlist_opt ::= LP idxlist RP",
109222  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
109223  /* 248 */ "idxlist ::= nm collate sortorder",
109224  /* 249 */ "collate ::=",
109225  /* 250 */ "collate ::= COLLATE ids",
109226  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
109227  /* 252 */ "cmd ::= VACUUM",
109228  /* 253 */ "cmd ::= VACUUM nm",
109229  /* 254 */ "cmd ::= PRAGMA nm dbnm",
109230  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
109231  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
109232  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
109233  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
109234  /* 259 */ "nmnum ::= plus_num",
109235  /* 260 */ "nmnum ::= nm",
109236  /* 261 */ "nmnum ::= ON",
109237  /* 262 */ "nmnum ::= DELETE",
109238  /* 263 */ "nmnum ::= DEFAULT",
109239  /* 264 */ "plus_num ::= PLUS number",
109240  /* 265 */ "plus_num ::= number",
109241  /* 266 */ "minus_num ::= MINUS number",
109242  /* 267 */ "number ::= INTEGER|FLOAT",
109243  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
109244  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
109245  /* 270 */ "trigger_time ::= BEFORE",
109246  /* 271 */ "trigger_time ::= AFTER",
109247  /* 272 */ "trigger_time ::= INSTEAD OF",
109248  /* 273 */ "trigger_time ::=",
109249  /* 274 */ "trigger_event ::= DELETE|INSERT",
109250  /* 275 */ "trigger_event ::= UPDATE",
109251  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
109252  /* 277 */ "foreach_clause ::=",
109253  /* 278 */ "foreach_clause ::= FOR EACH ROW",
109254  /* 279 */ "when_clause ::=",
109255  /* 280 */ "when_clause ::= WHEN expr",
109256  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
109257  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
109258  /* 283 */ "trnm ::= nm",
109259  /* 284 */ "trnm ::= nm DOT nm",
109260  /* 285 */ "tridxby ::=",
109261  /* 286 */ "tridxby ::= INDEXED BY nm",
109262  /* 287 */ "tridxby ::= NOT INDEXED",
109263  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
109264  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
109265  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
109266  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
109267  /* 292 */ "trigger_cmd ::= select",
109268  /* 293 */ "expr ::= RAISE LP IGNORE RP",
109269  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
109270  /* 295 */ "raisetype ::= ROLLBACK",
109271  /* 296 */ "raisetype ::= ABORT",
109272  /* 297 */ "raisetype ::= FAIL",
109273  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
109274  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
109275  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
109276  /* 301 */ "key_opt ::=",
109277  /* 302 */ "key_opt ::= KEY expr",
109278  /* 303 */ "database_kw_opt ::= DATABASE",
109279  /* 304 */ "database_kw_opt ::=",
109280  /* 305 */ "cmd ::= REINDEX",
109281  /* 306 */ "cmd ::= REINDEX nm dbnm",
109282  /* 307 */ "cmd ::= ANALYZE",
109283  /* 308 */ "cmd ::= ANALYZE nm dbnm",
109284  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
109285  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
109286  /* 311 */ "add_column_fullname ::= fullname",
109287  /* 312 */ "kwcolumn_opt ::=",
109288  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
109289  /* 314 */ "cmd ::= create_vtab",
109290  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
109291  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
109292  /* 317 */ "vtabarglist ::= vtabarg",
109293  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
109294  /* 319 */ "vtabarg ::=",
109295  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
109296  /* 321 */ "vtabargtoken ::= ANY",
109297  /* 322 */ "vtabargtoken ::= lp anylist RP",
109298  /* 323 */ "lp ::= LP",
109299  /* 324 */ "anylist ::=",
109300  /* 325 */ "anylist ::= anylist LP anylist RP",
109301  /* 326 */ "anylist ::= anylist ANY",
109302 };
109303 #endif /* NDEBUG */
109304
109305
109306 #if YYSTACKDEPTH<=0
109307 /*
109308 ** Try to increase the size of the parser stack.
109309 */
109310 static void yyGrowStack(yyParser *p){
109311   int newSize;
109312   yyStackEntry *pNew;
109313
109314   newSize = p->yystksz*2 + 100;
109315   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
109316   if( pNew ){
109317     p->yystack = pNew;
109318     p->yystksz = newSize;
109319 #ifndef NDEBUG
109320     if( yyTraceFILE ){
109321       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
109322               yyTracePrompt, p->yystksz);
109323     }
109324 #endif
109325   }
109326 }
109327 #endif
109328
109329 /* 
109330 ** This function allocates a new parser.
109331 ** The only argument is a pointer to a function which works like
109332 ** malloc.
109333 **
109334 ** Inputs:
109335 ** A pointer to the function used to allocate memory.
109336 **
109337 ** Outputs:
109338 ** A pointer to a parser.  This pointer is used in subsequent calls
109339 ** to sqlite3Parser and sqlite3ParserFree.
109340 */
109341 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
109342   yyParser *pParser;
109343   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
109344   if( pParser ){
109345     pParser->yyidx = -1;
109346 #ifdef YYTRACKMAXSTACKDEPTH
109347     pParser->yyidxMax = 0;
109348 #endif
109349 #if YYSTACKDEPTH<=0
109350     pParser->yystack = NULL;
109351     pParser->yystksz = 0;
109352     yyGrowStack(pParser);
109353 #endif
109354   }
109355   return pParser;
109356 }
109357
109358 /* The following function deletes the value associated with a
109359 ** symbol.  The symbol can be either a terminal or nonterminal.
109360 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
109361 ** the value.
109362 */
109363 static void yy_destructor(
109364   yyParser *yypParser,    /* The parser */
109365   YYCODETYPE yymajor,     /* Type code for object to destroy */
109366   YYMINORTYPE *yypminor   /* The object to be destroyed */
109367 ){
109368   sqlite3ParserARG_FETCH;
109369   switch( yymajor ){
109370     /* Here is inserted the actions which take place when a
109371     ** terminal or non-terminal is destroyed.  This can happen
109372     ** when the symbol is popped from the stack during a
109373     ** reduce or during error processing or when a parser is 
109374     ** being destroyed before it is finished parsing.
109375     **
109376     ** Note: during a reduce, the only symbols destroyed are those
109377     ** which appear on the RHS of the rule, but which are not used
109378     ** inside the C code.
109379     */
109380     case 160: /* select */
109381     case 194: /* oneselect */
109382 {
109383 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
109384 }
109385       break;
109386     case 173: /* term */
109387     case 174: /* expr */
109388 {
109389 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
109390 }
109391       break;
109392     case 178: /* idxlist_opt */
109393     case 187: /* idxlist */
109394     case 197: /* selcollist */
109395     case 200: /* groupby_opt */
109396     case 202: /* orderby_opt */
109397     case 204: /* sclp */
109398     case 214: /* sortlist */
109399     case 215: /* nexprlist */
109400     case 216: /* setlist */
109401     case 220: /* exprlist */
109402     case 225: /* case_exprlist */
109403 {
109404 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
109405 }
109406       break;
109407     case 193: /* fullname */
109408     case 198: /* from */
109409     case 206: /* seltablist */
109410     case 207: /* stl_prefix */
109411 {
109412 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
109413 }
109414       break;
109415     case 199: /* where_opt */
109416     case 201: /* having_opt */
109417     case 210: /* on_opt */
109418     case 224: /* case_operand */
109419     case 226: /* case_else */
109420     case 236: /* when_clause */
109421     case 241: /* key_opt */
109422 {
109423 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
109424 }
109425       break;
109426     case 211: /* using_opt */
109427     case 213: /* inscollist */
109428     case 218: /* inscollist_opt */
109429 {
109430 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
109431 }
109432       break;
109433     case 219: /* valuelist */
109434 {
109435
109436   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
109437   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
109438
109439 }
109440       break;
109441     case 232: /* trigger_cmd_list */
109442     case 237: /* trigger_cmd */
109443 {
109444 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
109445 }
109446       break;
109447     case 234: /* trigger_event */
109448 {
109449 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
109450 }
109451       break;
109452     default:  break;   /* If no destructor action specified: do nothing */
109453   }
109454 }
109455
109456 /*
109457 ** Pop the parser's stack once.
109458 **
109459 ** If there is a destructor routine associated with the token which
109460 ** is popped from the stack, then call it.
109461 **
109462 ** Return the major token number for the symbol popped.
109463 */
109464 static int yy_pop_parser_stack(yyParser *pParser){
109465   YYCODETYPE yymajor;
109466   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
109467
109468   /* There is no mechanism by which the parser stack can be popped below
109469   ** empty in SQLite.  */
109470   if( NEVER(pParser->yyidx<0) ) return 0;
109471 #ifndef NDEBUG
109472   if( yyTraceFILE && pParser->yyidx>=0 ){
109473     fprintf(yyTraceFILE,"%sPopping %s\n",
109474       yyTracePrompt,
109475       yyTokenName[yytos->major]);
109476   }
109477 #endif
109478   yymajor = yytos->major;
109479   yy_destructor(pParser, yymajor, &yytos->minor);
109480   pParser->yyidx--;
109481   return yymajor;
109482 }
109483
109484 /* 
109485 ** Deallocate and destroy a parser.  Destructors are all called for
109486 ** all stack elements before shutting the parser down.
109487 **
109488 ** Inputs:
109489 ** <ul>
109490 ** <li>  A pointer to the parser.  This should be a pointer
109491 **       obtained from sqlite3ParserAlloc.
109492 ** <li>  A pointer to a function used to reclaim memory obtained
109493 **       from malloc.
109494 ** </ul>
109495 */
109496 SQLITE_PRIVATE void sqlite3ParserFree(
109497   void *p,                    /* The parser to be deleted */
109498   void (*freeProc)(void*)     /* Function used to reclaim memory */
109499 ){
109500   yyParser *pParser = (yyParser*)p;
109501   /* In SQLite, we never try to destroy a parser that was not successfully
109502   ** created in the first place. */
109503   if( NEVER(pParser==0) ) return;
109504   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
109505 #if YYSTACKDEPTH<=0
109506   free(pParser->yystack);
109507 #endif
109508   (*freeProc)((void*)pParser);
109509 }
109510
109511 /*
109512 ** Return the peak depth of the stack for a parser.
109513 */
109514 #ifdef YYTRACKMAXSTACKDEPTH
109515 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
109516   yyParser *pParser = (yyParser*)p;
109517   return pParser->yyidxMax;
109518 }
109519 #endif
109520
109521 /*
109522 ** Find the appropriate action for a parser given the terminal
109523 ** look-ahead token iLookAhead.
109524 **
109525 ** If the look-ahead token is YYNOCODE, then check to see if the action is
109526 ** independent of the look-ahead.  If it is, return the action, otherwise
109527 ** return YY_NO_ACTION.
109528 */
109529 static int yy_find_shift_action(
109530   yyParser *pParser,        /* The parser */
109531   YYCODETYPE iLookAhead     /* The look-ahead token */
109532 ){
109533   int i;
109534   int stateno = pParser->yystack[pParser->yyidx].stateno;
109535  
109536   if( stateno>YY_SHIFT_COUNT
109537    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
109538     return yy_default[stateno];
109539   }
109540   assert( iLookAhead!=YYNOCODE );
109541   i += iLookAhead;
109542   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109543     if( iLookAhead>0 ){
109544 #ifdef YYFALLBACK
109545       YYCODETYPE iFallback;            /* Fallback token */
109546       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
109547              && (iFallback = yyFallback[iLookAhead])!=0 ){
109548 #ifndef NDEBUG
109549         if( yyTraceFILE ){
109550           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
109551              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
109552         }
109553 #endif
109554         return yy_find_shift_action(pParser, iFallback);
109555       }
109556 #endif
109557 #ifdef YYWILDCARD
109558       {
109559         int j = i - iLookAhead + YYWILDCARD;
109560         if( 
109561 #if YY_SHIFT_MIN+YYWILDCARD<0
109562           j>=0 &&
109563 #endif
109564 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
109565           j<YY_ACTTAB_COUNT &&
109566 #endif
109567           yy_lookahead[j]==YYWILDCARD
109568         ){
109569 #ifndef NDEBUG
109570           if( yyTraceFILE ){
109571             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
109572                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
109573           }
109574 #endif /* NDEBUG */
109575           return yy_action[j];
109576         }
109577       }
109578 #endif /* YYWILDCARD */
109579     }
109580     return yy_default[stateno];
109581   }else{
109582     return yy_action[i];
109583   }
109584 }
109585
109586 /*
109587 ** Find the appropriate action for a parser given the non-terminal
109588 ** look-ahead token iLookAhead.
109589 **
109590 ** If the look-ahead token is YYNOCODE, then check to see if the action is
109591 ** independent of the look-ahead.  If it is, return the action, otherwise
109592 ** return YY_NO_ACTION.
109593 */
109594 static int yy_find_reduce_action(
109595   int stateno,              /* Current state number */
109596   YYCODETYPE iLookAhead     /* The look-ahead token */
109597 ){
109598   int i;
109599 #ifdef YYERRORSYMBOL
109600   if( stateno>YY_REDUCE_COUNT ){
109601     return yy_default[stateno];
109602   }
109603 #else
109604   assert( stateno<=YY_REDUCE_COUNT );
109605 #endif
109606   i = yy_reduce_ofst[stateno];
109607   assert( i!=YY_REDUCE_USE_DFLT );
109608   assert( iLookAhead!=YYNOCODE );
109609   i += iLookAhead;
109610 #ifdef YYERRORSYMBOL
109611   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109612     return yy_default[stateno];
109613   }
109614 #else
109615   assert( i>=0 && i<YY_ACTTAB_COUNT );
109616   assert( yy_lookahead[i]==iLookAhead );
109617 #endif
109618   return yy_action[i];
109619 }
109620
109621 /*
109622 ** The following routine is called if the stack overflows.
109623 */
109624 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
109625    sqlite3ParserARG_FETCH;
109626    yypParser->yyidx--;
109627 #ifndef NDEBUG
109628    if( yyTraceFILE ){
109629      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
109630    }
109631 #endif
109632    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109633    /* Here code is inserted which will execute if the parser
109634    ** stack every overflows */
109635
109636   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
109637   sqlite3ErrorMsg(pParse, "parser stack overflow");
109638    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
109639 }
109640
109641 /*
109642 ** Perform a shift action.
109643 */
109644 static void yy_shift(
109645   yyParser *yypParser,          /* The parser to be shifted */
109646   int yyNewState,               /* The new state to shift in */
109647   int yyMajor,                  /* The major token to shift in */
109648   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
109649 ){
109650   yyStackEntry *yytos;
109651   yypParser->yyidx++;
109652 #ifdef YYTRACKMAXSTACKDEPTH
109653   if( yypParser->yyidx>yypParser->yyidxMax ){
109654     yypParser->yyidxMax = yypParser->yyidx;
109655   }
109656 #endif
109657 #if YYSTACKDEPTH>0 
109658   if( yypParser->yyidx>=YYSTACKDEPTH ){
109659     yyStackOverflow(yypParser, yypMinor);
109660     return;
109661   }
109662 #else
109663   if( yypParser->yyidx>=yypParser->yystksz ){
109664     yyGrowStack(yypParser);
109665     if( yypParser->yyidx>=yypParser->yystksz ){
109666       yyStackOverflow(yypParser, yypMinor);
109667       return;
109668     }
109669   }
109670 #endif
109671   yytos = &yypParser->yystack[yypParser->yyidx];
109672   yytos->stateno = (YYACTIONTYPE)yyNewState;
109673   yytos->major = (YYCODETYPE)yyMajor;
109674   yytos->minor = *yypMinor;
109675 #ifndef NDEBUG
109676   if( yyTraceFILE && yypParser->yyidx>0 ){
109677     int i;
109678     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
109679     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
109680     for(i=1; i<=yypParser->yyidx; i++)
109681       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
109682     fprintf(yyTraceFILE,"\n");
109683   }
109684 #endif
109685 }
109686
109687 /* The following table contains information about every rule that
109688 ** is used during the reduce.
109689 */
109690 static const struct {
109691   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
109692   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
109693 } yyRuleInfo[] = {
109694   { 142, 1 },
109695   { 143, 2 },
109696   { 143, 1 },
109697   { 144, 1 },
109698   { 144, 3 },
109699   { 145, 0 },
109700   { 145, 1 },
109701   { 145, 3 },
109702   { 146, 1 },
109703   { 147, 3 },
109704   { 149, 0 },
109705   { 149, 1 },
109706   { 149, 2 },
109707   { 148, 0 },
109708   { 148, 1 },
109709   { 148, 1 },
109710   { 148, 1 },
109711   { 147, 2 },
109712   { 147, 2 },
109713   { 147, 2 },
109714   { 151, 1 },
109715   { 151, 0 },
109716   { 147, 2 },
109717   { 147, 3 },
109718   { 147, 5 },
109719   { 147, 2 },
109720   { 152, 6 },
109721   { 154, 1 },
109722   { 156, 0 },
109723   { 156, 3 },
109724   { 155, 1 },
109725   { 155, 0 },
109726   { 153, 4 },
109727   { 153, 2 },
109728   { 158, 3 },
109729   { 158, 1 },
109730   { 161, 3 },
109731   { 162, 1 },
109732   { 165, 1 },
109733   { 165, 1 },
109734   { 166, 1 },
109735   { 150, 1 },
109736   { 150, 1 },
109737   { 150, 1 },
109738   { 163, 0 },
109739   { 163, 1 },
109740   { 167, 1 },
109741   { 167, 4 },
109742   { 167, 6 },
109743   { 168, 1 },
109744   { 168, 2 },
109745   { 169, 1 },
109746   { 169, 1 },
109747   { 164, 2 },
109748   { 164, 0 },
109749   { 172, 2 },
109750   { 172, 2 },
109751   { 172, 4 },
109752   { 172, 3 },
109753   { 172, 3 },
109754   { 172, 2 },
109755   { 172, 2 },
109756   { 172, 3 },
109757   { 172, 5 },
109758   { 172, 2 },
109759   { 172, 4 },
109760   { 172, 4 },
109761   { 172, 1 },
109762   { 172, 2 },
109763   { 177, 0 },
109764   { 177, 1 },
109765   { 179, 0 },
109766   { 179, 2 },
109767   { 181, 2 },
109768   { 181, 3 },
109769   { 181, 3 },
109770   { 181, 3 },
109771   { 182, 2 },
109772   { 182, 2 },
109773   { 182, 1 },
109774   { 182, 1 },
109775   { 182, 2 },
109776   { 180, 3 },
109777   { 180, 2 },
109778   { 183, 0 },
109779   { 183, 2 },
109780   { 183, 2 },
109781   { 159, 0 },
109782   { 159, 2 },
109783   { 184, 3 },
109784   { 184, 1 },
109785   { 185, 1 },
109786   { 185, 0 },
109787   { 186, 2 },
109788   { 186, 7 },
109789   { 186, 5 },
109790   { 186, 5 },
109791   { 186, 10 },
109792   { 188, 0 },
109793   { 188, 1 },
109794   { 175, 0 },
109795   { 175, 3 },
109796   { 189, 0 },
109797   { 189, 2 },
109798   { 190, 1 },
109799   { 190, 1 },
109800   { 190, 1 },
109801   { 147, 4 },
109802   { 192, 2 },
109803   { 192, 0 },
109804   { 147, 8 },
109805   { 147, 4 },
109806   { 147, 1 },
109807   { 160, 1 },
109808   { 160, 3 },
109809   { 195, 1 },
109810   { 195, 2 },
109811   { 195, 1 },
109812   { 194, 9 },
109813   { 196, 1 },
109814   { 196, 1 },
109815   { 196, 0 },
109816   { 204, 2 },
109817   { 204, 0 },
109818   { 197, 3 },
109819   { 197, 2 },
109820   { 197, 4 },
109821   { 205, 2 },
109822   { 205, 1 },
109823   { 205, 0 },
109824   { 198, 0 },
109825   { 198, 2 },
109826   { 207, 2 },
109827   { 207, 0 },
109828   { 206, 7 },
109829   { 206, 7 },
109830   { 206, 7 },
109831   { 157, 0 },
109832   { 157, 2 },
109833   { 193, 2 },
109834   { 208, 1 },
109835   { 208, 2 },
109836   { 208, 3 },
109837   { 208, 4 },
109838   { 210, 2 },
109839   { 210, 0 },
109840   { 209, 0 },
109841   { 209, 3 },
109842   { 209, 2 },
109843   { 211, 4 },
109844   { 211, 0 },
109845   { 202, 0 },
109846   { 202, 3 },
109847   { 214, 4 },
109848   { 214, 2 },
109849   { 176, 1 },
109850   { 176, 1 },
109851   { 176, 0 },
109852   { 200, 0 },
109853   { 200, 3 },
109854   { 201, 0 },
109855   { 201, 2 },
109856   { 203, 0 },
109857   { 203, 2 },
109858   { 203, 4 },
109859   { 203, 4 },
109860   { 147, 5 },
109861   { 199, 0 },
109862   { 199, 2 },
109863   { 147, 7 },
109864   { 216, 5 },
109865   { 216, 3 },
109866   { 147, 5 },
109867   { 147, 5 },
109868   { 147, 6 },
109869   { 217, 2 },
109870   { 217, 1 },
109871   { 219, 4 },
109872   { 219, 5 },
109873   { 218, 0 },
109874   { 218, 3 },
109875   { 213, 3 },
109876   { 213, 1 },
109877   { 174, 1 },
109878   { 174, 3 },
109879   { 173, 1 },
109880   { 174, 1 },
109881   { 174, 1 },
109882   { 174, 3 },
109883   { 174, 5 },
109884   { 173, 1 },
109885   { 173, 1 },
109886   { 174, 1 },
109887   { 174, 1 },
109888   { 174, 3 },
109889   { 174, 6 },
109890   { 174, 5 },
109891   { 174, 4 },
109892   { 173, 1 },
109893   { 174, 3 },
109894   { 174, 3 },
109895   { 174, 3 },
109896   { 174, 3 },
109897   { 174, 3 },
109898   { 174, 3 },
109899   { 174, 3 },
109900   { 174, 3 },
109901   { 221, 1 },
109902   { 221, 2 },
109903   { 221, 1 },
109904   { 221, 2 },
109905   { 174, 3 },
109906   { 174, 5 },
109907   { 174, 2 },
109908   { 174, 3 },
109909   { 174, 3 },
109910   { 174, 4 },
109911   { 174, 2 },
109912   { 174, 2 },
109913   { 174, 2 },
109914   { 174, 2 },
109915   { 222, 1 },
109916   { 222, 2 },
109917   { 174, 5 },
109918   { 223, 1 },
109919   { 223, 2 },
109920   { 174, 5 },
109921   { 174, 3 },
109922   { 174, 5 },
109923   { 174, 4 },
109924   { 174, 4 },
109925   { 174, 5 },
109926   { 225, 5 },
109927   { 225, 4 },
109928   { 226, 2 },
109929   { 226, 0 },
109930   { 224, 1 },
109931   { 224, 0 },
109932   { 220, 1 },
109933   { 220, 0 },
109934   { 215, 3 },
109935   { 215, 1 },
109936   { 147, 11 },
109937   { 227, 1 },
109938   { 227, 0 },
109939   { 178, 0 },
109940   { 178, 3 },
109941   { 187, 5 },
109942   { 187, 3 },
109943   { 228, 0 },
109944   { 228, 2 },
109945   { 147, 4 },
109946   { 147, 1 },
109947   { 147, 2 },
109948   { 147, 3 },
109949   { 147, 5 },
109950   { 147, 6 },
109951   { 147, 5 },
109952   { 147, 6 },
109953   { 229, 1 },
109954   { 229, 1 },
109955   { 229, 1 },
109956   { 229, 1 },
109957   { 229, 1 },
109958   { 170, 2 },
109959   { 170, 1 },
109960   { 171, 2 },
109961   { 230, 1 },
109962   { 147, 5 },
109963   { 231, 11 },
109964   { 233, 1 },
109965   { 233, 1 },
109966   { 233, 2 },
109967   { 233, 0 },
109968   { 234, 1 },
109969   { 234, 1 },
109970   { 234, 3 },
109971   { 235, 0 },
109972   { 235, 3 },
109973   { 236, 0 },
109974   { 236, 2 },
109975   { 232, 3 },
109976   { 232, 2 },
109977   { 238, 1 },
109978   { 238, 3 },
109979   { 239, 0 },
109980   { 239, 3 },
109981   { 239, 2 },
109982   { 237, 7 },
109983   { 237, 5 },
109984   { 237, 5 },
109985   { 237, 5 },
109986   { 237, 1 },
109987   { 174, 4 },
109988   { 174, 6 },
109989   { 191, 1 },
109990   { 191, 1 },
109991   { 191, 1 },
109992   { 147, 4 },
109993   { 147, 6 },
109994   { 147, 3 },
109995   { 241, 0 },
109996   { 241, 2 },
109997   { 240, 1 },
109998   { 240, 0 },
109999   { 147, 1 },
110000   { 147, 3 },
110001   { 147, 1 },
110002   { 147, 3 },
110003   { 147, 6 },
110004   { 147, 6 },
110005   { 242, 1 },
110006   { 243, 0 },
110007   { 243, 1 },
110008   { 147, 1 },
110009   { 147, 4 },
110010   { 244, 8 },
110011   { 245, 1 },
110012   { 245, 3 },
110013   { 246, 0 },
110014   { 246, 2 },
110015   { 247, 1 },
110016   { 247, 3 },
110017   { 248, 1 },
110018   { 249, 0 },
110019   { 249, 4 },
110020   { 249, 2 },
110021 };
110022
110023 static void yy_accept(yyParser*);  /* Forward Declaration */
110024
110025 /*
110026 ** Perform a reduce action and the shift that must immediately
110027 ** follow the reduce.
110028 */
110029 static void yy_reduce(
110030   yyParser *yypParser,         /* The parser */
110031   int yyruleno                 /* Number of the rule by which to reduce */
110032 ){
110033   int yygoto;                     /* The next state */
110034   int yyact;                      /* The next action */
110035   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
110036   yyStackEntry *yymsp;            /* The top of the parser's stack */
110037   int yysize;                     /* Amount to pop the stack */
110038   sqlite3ParserARG_FETCH;
110039   yymsp = &yypParser->yystack[yypParser->yyidx];
110040 #ifndef NDEBUG
110041   if( yyTraceFILE && yyruleno>=0 
110042         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
110043     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
110044       yyRuleName[yyruleno]);
110045   }
110046 #endif /* NDEBUG */
110047
110048   /* Silence complaints from purify about yygotominor being uninitialized
110049   ** in some cases when it is copied into the stack after the following
110050   ** switch.  yygotominor is uninitialized when a rule reduces that does
110051   ** not set the value of its left-hand side nonterminal.  Leaving the
110052   ** value of the nonterminal uninitialized is utterly harmless as long
110053   ** as the value is never used.  So really the only thing this code
110054   ** accomplishes is to quieten purify.  
110055   **
110056   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
110057   ** without this code, their parser segfaults.  I'm not sure what there
110058   ** parser is doing to make this happen.  This is the second bug report
110059   ** from wireshark this week.  Clearly they are stressing Lemon in ways
110060   ** that it has not been previously stressed...  (SQLite ticket #2172)
110061   */
110062   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
110063   yygotominor = yyzerominor;
110064
110065
110066   switch( yyruleno ){
110067   /* Beginning here are the reduction cases.  A typical example
110068   ** follows:
110069   **   case 0:
110070   **  #line <lineno> <grammarfile>
110071   **     { ... }           // User supplied code
110072   **  #line <lineno> <thisfile>
110073   **     break;
110074   */
110075       case 5: /* explain ::= */
110076 { sqlite3BeginParse(pParse, 0); }
110077         break;
110078       case 6: /* explain ::= EXPLAIN */
110079 { sqlite3BeginParse(pParse, 1); }
110080         break;
110081       case 7: /* explain ::= EXPLAIN QUERY PLAN */
110082 { sqlite3BeginParse(pParse, 2); }
110083         break;
110084       case 8: /* cmdx ::= cmd */
110085 { sqlite3FinishCoding(pParse); }
110086         break;
110087       case 9: /* cmd ::= BEGIN transtype trans_opt */
110088 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
110089         break;
110090       case 13: /* transtype ::= */
110091 {yygotominor.yy392 = TK_DEFERRED;}
110092         break;
110093       case 14: /* transtype ::= DEFERRED */
110094       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
110095       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
110096       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
110097       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
110098 {yygotominor.yy392 = yymsp[0].major;}
110099         break;
110100       case 17: /* cmd ::= COMMIT trans_opt */
110101       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
110102 {sqlite3CommitTransaction(pParse);}
110103         break;
110104       case 19: /* cmd ::= ROLLBACK trans_opt */
110105 {sqlite3RollbackTransaction(pParse);}
110106         break;
110107       case 22: /* cmd ::= SAVEPOINT nm */
110108 {
110109   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
110110 }
110111         break;
110112       case 23: /* cmd ::= RELEASE savepoint_opt nm */
110113 {
110114   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
110115 }
110116         break;
110117       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
110118 {
110119   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
110120 }
110121         break;
110122       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
110123 {
110124    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
110125 }
110126         break;
110127       case 27: /* createkw ::= CREATE */
110128 {
110129   pParse->db->lookaside.bEnabled = 0;
110130   yygotominor.yy0 = yymsp[0].minor.yy0;
110131 }
110132         break;
110133       case 28: /* ifnotexists ::= */
110134       case 31: /* temp ::= */ yytestcase(yyruleno==31);
110135       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
110136       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
110137       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
110138       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
110139       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
110140       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
110141       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
110142       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
110143       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
110144       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
110145 {yygotominor.yy392 = 0;}
110146         break;
110147       case 29: /* ifnotexists ::= IF NOT EXISTS */
110148       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
110149       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
110150       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
110151       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
110152       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
110153       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
110154       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
110155 {yygotominor.yy392 = 1;}
110156         break;
110157       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
110158 {
110159   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
110160 }
110161         break;
110162       case 33: /* create_table_args ::= AS select */
110163 {
110164   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
110165   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110166 }
110167         break;
110168       case 36: /* column ::= columnid type carglist */
110169 {
110170   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
110171   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
110172 }
110173         break;
110174       case 37: /* columnid ::= nm */
110175 {
110176   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
110177   yygotominor.yy0 = yymsp[0].minor.yy0;
110178   pParse->constraintName.n = 0;
110179 }
110180         break;
110181       case 38: /* id ::= ID */
110182       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
110183       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
110184       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
110185       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
110186       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
110187       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
110188       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
110189       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
110190       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
110191       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
110192       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
110193       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
110194       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
110195       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
110196       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
110197       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
110198       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
110199       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
110200       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
110201       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
110202       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
110203       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
110204 {yygotominor.yy0 = yymsp[0].minor.yy0;}
110205         break;
110206       case 45: /* type ::= typetoken */
110207 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
110208         break;
110209       case 47: /* typetoken ::= typename LP signed RP */
110210 {
110211   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
110212   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
110213 }
110214         break;
110215       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
110216 {
110217   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
110218   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
110219 }
110220         break;
110221       case 50: /* typename ::= typename ids */
110222 {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);}
110223         break;
110224       case 55: /* ccons ::= CONSTRAINT nm */
110225       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110226 {pParse->constraintName = yymsp[0].minor.yy0;}
110227         break;
110228       case 56: /* ccons ::= DEFAULT term */
110229       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
110230 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
110231         break;
110232       case 57: /* ccons ::= DEFAULT LP expr RP */
110233 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
110234         break;
110235       case 59: /* ccons ::= DEFAULT MINUS term */
110236 {
110237   ExprSpan v;
110238   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
110239   v.zStart = yymsp[-1].minor.yy0.z;
110240   v.zEnd = yymsp[0].minor.yy342.zEnd;
110241   sqlite3AddDefaultValue(pParse,&v);
110242 }
110243         break;
110244       case 60: /* ccons ::= DEFAULT id */
110245 {
110246   ExprSpan v;
110247   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
110248   sqlite3AddDefaultValue(pParse,&v);
110249 }
110250         break;
110251       case 62: /* ccons ::= NOT NULL onconf */
110252 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
110253         break;
110254       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
110255 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
110256         break;
110257       case 64: /* ccons ::= UNIQUE onconf */
110258 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
110259         break;
110260       case 65: /* ccons ::= CHECK LP expr RP */
110261 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
110262         break;
110263       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
110264 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
110265         break;
110266       case 67: /* ccons ::= defer_subclause */
110267 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
110268         break;
110269       case 68: /* ccons ::= COLLATE ids */
110270 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
110271         break;
110272       case 71: /* refargs ::= */
110273 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
110274         break;
110275       case 72: /* refargs ::= refargs refarg */
110276 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
110277         break;
110278       case 73: /* refarg ::= MATCH nm */
110279       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
110280 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
110281         break;
110282       case 75: /* refarg ::= ON DELETE refact */
110283 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
110284         break;
110285       case 76: /* refarg ::= ON UPDATE refact */
110286 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
110287         break;
110288       case 77: /* refact ::= SET NULL */
110289 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
110290         break;
110291       case 78: /* refact ::= SET DEFAULT */
110292 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
110293         break;
110294       case 79: /* refact ::= CASCADE */
110295 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
110296         break;
110297       case 80: /* refact ::= RESTRICT */
110298 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
110299         break;
110300       case 81: /* refact ::= NO ACTION */
110301 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
110302         break;
110303       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
110304       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
110305       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
110306       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
110307 {yygotominor.yy392 = yymsp[0].minor.yy392;}
110308         break;
110309       case 87: /* conslist_opt ::= */
110310 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
110311         break;
110312       case 88: /* conslist_opt ::= COMMA conslist */
110313 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
110314         break;
110315       case 91: /* tconscomma ::= COMMA */
110316 {pParse->constraintName.n = 0;}
110317         break;
110318       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
110319 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
110320         break;
110321       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
110322 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
110323         break;
110324       case 96: /* tcons ::= CHECK LP expr RP onconf */
110325 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
110326         break;
110327       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
110328 {
110329     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
110330     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
110331 }
110332         break;
110333       case 100: /* onconf ::= */
110334 {yygotominor.yy392 = OE_Default;}
110335         break;
110336       case 102: /* orconf ::= */
110337 {yygotominor.yy258 = OE_Default;}
110338         break;
110339       case 103: /* orconf ::= OR resolvetype */
110340 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
110341         break;
110342       case 105: /* resolvetype ::= IGNORE */
110343 {yygotominor.yy392 = OE_Ignore;}
110344         break;
110345       case 106: /* resolvetype ::= REPLACE */
110346 {yygotominor.yy392 = OE_Replace;}
110347         break;
110348       case 107: /* cmd ::= DROP TABLE ifexists fullname */
110349 {
110350   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
110351 }
110352         break;
110353       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
110354 {
110355   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);
110356 }
110357         break;
110358       case 111: /* cmd ::= DROP VIEW ifexists fullname */
110359 {
110360   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
110361 }
110362         break;
110363       case 112: /* cmd ::= select */
110364 {
110365   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
110366   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
110367   sqlite3ExplainBegin(pParse->pVdbe);
110368   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
110369   sqlite3ExplainFinish(pParse->pVdbe);
110370   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110371 }
110372         break;
110373       case 113: /* select ::= oneselect */
110374 {yygotominor.yy159 = yymsp[0].minor.yy159;}
110375         break;
110376       case 114: /* select ::= select multiselect_op oneselect */
110377 {
110378   if( yymsp[0].minor.yy159 ){
110379     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
110380     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
110381   }else{
110382     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
110383   }
110384   yygotominor.yy159 = yymsp[0].minor.yy159;
110385 }
110386         break;
110387       case 116: /* multiselect_op ::= UNION ALL */
110388 {yygotominor.yy392 = TK_ALL;}
110389         break;
110390       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
110391 {
110392   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);
110393 }
110394         break;
110395       case 122: /* sclp ::= selcollist COMMA */
110396       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
110397 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
110398         break;
110399       case 123: /* sclp ::= */
110400       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
110401       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
110402       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
110403       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
110404 {yygotominor.yy442 = 0;}
110405         break;
110406       case 124: /* selcollist ::= sclp expr as */
110407 {
110408    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
110409    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
110410    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
110411 }
110412         break;
110413       case 125: /* selcollist ::= sclp STAR */
110414 {
110415   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
110416   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
110417 }
110418         break;
110419       case 126: /* selcollist ::= sclp nm DOT STAR */
110420 {
110421   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
110422   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110423   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
110424   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
110425 }
110426         break;
110427       case 129: /* as ::= */
110428 {yygotominor.yy0.n = 0;}
110429         break;
110430       case 130: /* from ::= */
110431 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
110432         break;
110433       case 131: /* from ::= FROM seltablist */
110434 {
110435   yygotominor.yy347 = yymsp[0].minor.yy347;
110436   sqlite3SrcListShiftJoinType(yygotominor.yy347);
110437 }
110438         break;
110439       case 132: /* stl_prefix ::= seltablist joinop */
110440 {
110441    yygotominor.yy347 = yymsp[-1].minor.yy347;
110442    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
110443 }
110444         break;
110445       case 133: /* stl_prefix ::= */
110446 {yygotominor.yy347 = 0;}
110447         break;
110448       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
110449 {
110450   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);
110451   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
110452 }
110453         break;
110454       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
110455 {
110456     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);
110457   }
110458         break;
110459       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
110460 {
110461     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
110462       yygotominor.yy347 = yymsp[-4].minor.yy347;
110463     }else{
110464       Select *pSubquery;
110465       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
110466       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
110467       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
110468     }
110469   }
110470         break;
110471       case 137: /* dbnm ::= */
110472       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
110473 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
110474         break;
110475       case 139: /* fullname ::= nm dbnm */
110476 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
110477         break;
110478       case 140: /* joinop ::= COMMA|JOIN */
110479 { yygotominor.yy392 = JT_INNER; }
110480         break;
110481       case 141: /* joinop ::= JOIN_KW JOIN */
110482 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
110483         break;
110484       case 142: /* joinop ::= JOIN_KW nm JOIN */
110485 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
110486         break;
110487       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
110488 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
110489         break;
110490       case 144: /* on_opt ::= ON expr */
110491       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
110492       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
110493       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
110494       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
110495 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
110496         break;
110497       case 145: /* on_opt ::= */
110498       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
110499       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
110500       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
110501       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
110502 {yygotominor.yy122 = 0;}
110503         break;
110504       case 148: /* indexed_opt ::= NOT INDEXED */
110505 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
110506         break;
110507       case 149: /* using_opt ::= USING LP inscollist RP */
110508       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
110509 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
110510         break;
110511       case 150: /* using_opt ::= */
110512       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
110513 {yygotominor.yy180 = 0;}
110514         break;
110515       case 152: /* orderby_opt ::= ORDER BY sortlist */
110516       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
110517       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
110518 {yygotominor.yy442 = yymsp[0].minor.yy442;}
110519         break;
110520       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
110521 {
110522   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
110523   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110524 }
110525         break;
110526       case 154: /* sortlist ::= expr sortorder */
110527 {
110528   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
110529   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
110530 }
110531         break;
110532       case 155: /* sortorder ::= ASC */
110533       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
110534 {yygotominor.yy392 = SQLITE_SO_ASC;}
110535         break;
110536       case 156: /* sortorder ::= DESC */
110537 {yygotominor.yy392 = SQLITE_SO_DESC;}
110538         break;
110539       case 162: /* limit_opt ::= */
110540 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
110541         break;
110542       case 163: /* limit_opt ::= LIMIT expr */
110543 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
110544         break;
110545       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
110546 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
110547         break;
110548       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
110549 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
110550         break;
110551       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
110552 {
110553   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
110554   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
110555 }
110556         break;
110557       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
110558 {
110559   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
110560   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
110561   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
110562 }
110563         break;
110564       case 170: /* setlist ::= setlist COMMA nm EQ expr */
110565 {
110566   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
110567   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110568 }
110569         break;
110570       case 171: /* setlist ::= nm EQ expr */
110571 {
110572   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
110573   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110574 }
110575         break;
110576       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
110577 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110578         break;
110579       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
110580 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110581         break;
110582       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
110583 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
110584         break;
110585       case 175: /* insert_cmd ::= INSERT orconf */
110586 {yygotominor.yy258 = yymsp[0].minor.yy258;}
110587         break;
110588       case 176: /* insert_cmd ::= REPLACE */
110589 {yygotominor.yy258 = OE_Replace;}
110590         break;
110591       case 177: /* valuelist ::= VALUES LP nexprlist RP */
110592 {
110593   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
110594   yygotominor.yy487.pSelect = 0;
110595 }
110596         break;
110597       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
110598 {
110599   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
110600   if( yymsp[-4].minor.yy487.pList ){
110601     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
110602     yymsp[-4].minor.yy487.pList = 0;
110603   }
110604   yygotominor.yy487.pList = 0;
110605   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
110606     sqlite3SelectDelete(pParse->db, pRight);
110607     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
110608     yygotominor.yy487.pSelect = 0;
110609   }else{
110610     pRight->op = TK_ALL;
110611     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
110612     pRight->selFlags |= SF_Values;
110613     pRight->pPrior->selFlags |= SF_Values;
110614     yygotominor.yy487.pSelect = pRight;
110615   }
110616 }
110617         break;
110618       case 181: /* inscollist ::= inscollist COMMA nm */
110619 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
110620         break;
110621       case 182: /* inscollist ::= nm */
110622 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
110623         break;
110624       case 183: /* expr ::= term */
110625 {yygotominor.yy342 = yymsp[0].minor.yy342;}
110626         break;
110627       case 184: /* expr ::= LP expr RP */
110628 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
110629         break;
110630       case 185: /* term ::= NULL */
110631       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
110632       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
110633 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
110634         break;
110635       case 186: /* expr ::= id */
110636       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
110637 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
110638         break;
110639       case 188: /* expr ::= nm DOT nm */
110640 {
110641   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110642   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110643   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
110644   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
110645 }
110646         break;
110647       case 189: /* expr ::= nm DOT nm DOT nm */
110648 {
110649   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
110650   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110651   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110652   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
110653   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
110654   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110655 }
110656         break;
110657       case 192: /* expr ::= REGISTER */
110658 {
110659   /* When doing a nested parse, one can include terms in an expression
110660   ** that look like this:   #1 #2 ...  These terms refer to registers
110661   ** in the virtual machine.  #N is the N-th register. */
110662   if( pParse->nested==0 ){
110663     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
110664     yygotominor.yy342.pExpr = 0;
110665   }else{
110666     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
110667     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
110668   }
110669   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110670 }
110671         break;
110672       case 193: /* expr ::= VARIABLE */
110673 {
110674   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
110675   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
110676   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110677 }
110678         break;
110679       case 194: /* expr ::= expr COLLATE ids */
110680 {
110681   yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
110682   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110683   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110684 }
110685         break;
110686       case 195: /* expr ::= CAST LP expr AS typetoken RP */
110687 {
110688   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
110689   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
110690 }
110691         break;
110692       case 196: /* expr ::= ID LP distinct exprlist RP */
110693 {
110694   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
110695     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
110696   }
110697   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
110698   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110699   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
110700     yygotominor.yy342.pExpr->flags |= EP_Distinct;
110701   }
110702 }
110703         break;
110704       case 197: /* expr ::= ID LP STAR RP */
110705 {
110706   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
110707   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
110708 }
110709         break;
110710       case 198: /* term ::= CTIME_KW */
110711 {
110712   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
110713   ** treated as functions that return constants */
110714   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
110715   if( yygotominor.yy342.pExpr ){
110716     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  
110717   }
110718   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110719 }
110720         break;
110721       case 199: /* expr ::= expr AND expr */
110722       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
110723       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
110724       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
110725       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
110726       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
110727       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
110728       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
110729 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
110730         break;
110731       case 207: /* likeop ::= LIKE_KW */
110732       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
110733 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
110734         break;
110735       case 208: /* likeop ::= NOT LIKE_KW */
110736       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
110737 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
110738         break;
110739       case 211: /* expr ::= expr likeop expr */
110740 {
110741   ExprList *pList;
110742   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
110743   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
110744   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
110745   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110746   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110747   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110748   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110749 }
110750         break;
110751       case 212: /* expr ::= expr likeop expr ESCAPE expr */
110752 {
110753   ExprList *pList;
110754   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110755   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
110756   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110757   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
110758   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110759   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110760   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110761   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110762 }
110763         break;
110764       case 213: /* expr ::= expr ISNULL|NOTNULL */
110765 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
110766         break;
110767       case 214: /* expr ::= expr NOT NULL */
110768 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
110769         break;
110770       case 215: /* expr ::= expr IS expr */
110771 {
110772   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
110773   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
110774 }
110775         break;
110776       case 216: /* expr ::= expr IS NOT expr */
110777 {
110778   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
110779   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
110780 }
110781         break;
110782       case 217: /* expr ::= NOT expr */
110783       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
110784 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110785         break;
110786       case 219: /* expr ::= MINUS expr */
110787 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110788         break;
110789       case 220: /* expr ::= PLUS expr */
110790 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110791         break;
110792       case 223: /* expr ::= expr between_op expr AND expr */
110793 {
110794   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110795   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110796   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110797   if( yygotominor.yy342.pExpr ){
110798     yygotominor.yy342.pExpr->x.pList = pList;
110799   }else{
110800     sqlite3ExprListDelete(pParse->db, pList);
110801   } 
110802   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110803   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110804   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110805 }
110806         break;
110807       case 226: /* expr ::= expr in_op LP exprlist RP */
110808 {
110809     if( yymsp[-1].minor.yy442==0 ){
110810       /* Expressions of the form
110811       **
110812       **      expr1 IN ()
110813       **      expr1 NOT IN ()
110814       **
110815       ** simplify to constants 0 (false) and 1 (true), respectively,
110816       ** regardless of the value of expr1.
110817       */
110818       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
110819       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
110820     }else{
110821       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110822       if( yygotominor.yy342.pExpr ){
110823         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
110824         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110825       }else{
110826         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
110827       }
110828       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110829     }
110830     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110831     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110832   }
110833         break;
110834       case 227: /* expr ::= LP select RP */
110835 {
110836     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
110837     if( yygotominor.yy342.pExpr ){
110838       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110839       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110840       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110841     }else{
110842       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110843     }
110844     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
110845     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110846   }
110847         break;
110848       case 228: /* expr ::= expr in_op LP select RP */
110849 {
110850     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110851     if( yygotominor.yy342.pExpr ){
110852       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110853       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110854       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110855     }else{
110856       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110857     }
110858     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110859     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110860     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110861   }
110862         break;
110863       case 229: /* expr ::= expr in_op nm dbnm */
110864 {
110865     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
110866     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
110867     if( yygotominor.yy342.pExpr ){
110868       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
110869       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110870       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110871     }else{
110872       sqlite3SrcListDelete(pParse->db, pSrc);
110873     }
110874     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110875     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
110876     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];
110877   }
110878         break;
110879       case 230: /* expr ::= EXISTS LP select RP */
110880 {
110881     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
110882     if( p ){
110883       p->x.pSelect = yymsp[-1].minor.yy159;
110884       ExprSetProperty(p, EP_xIsSelect);
110885       sqlite3ExprSetHeight(pParse, p);
110886     }else{
110887       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110888     }
110889     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110890     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110891   }
110892         break;
110893       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
110894 {
110895   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
110896   if( yygotominor.yy342.pExpr ){
110897     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
110898     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110899   }else{
110900     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
110901   }
110902   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
110903   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110904 }
110905         break;
110906       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
110907 {
110908   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
110909   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110910 }
110911         break;
110912       case 233: /* case_exprlist ::= WHEN expr THEN expr */
110913 {
110914   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110915   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110916 }
110917         break;
110918       case 240: /* nexprlist ::= nexprlist COMMA expr */
110919 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
110920         break;
110921       case 241: /* nexprlist ::= expr */
110922 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
110923         break;
110924       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
110925 {
110926   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
110927                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
110928                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
110929 }
110930         break;
110931       case 243: /* uniqueflag ::= UNIQUE */
110932       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
110933 {yygotominor.yy392 = OE_Abort;}
110934         break;
110935       case 244: /* uniqueflag ::= */
110936 {yygotominor.yy392 = OE_None;}
110937         break;
110938       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
110939 {
110940   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
110941   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
110942   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
110943   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110944   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110945 }
110946         break;
110947       case 248: /* idxlist ::= nm collate sortorder */
110948 {
110949   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
110950   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
110951   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110952   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110953   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110954 }
110955         break;
110956       case 249: /* collate ::= */
110957 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
110958         break;
110959       case 251: /* cmd ::= DROP INDEX ifexists fullname */
110960 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
110961         break;
110962       case 252: /* cmd ::= VACUUM */
110963       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
110964 {sqlite3Vacuum(pParse);}
110965         break;
110966       case 254: /* cmd ::= PRAGMA nm dbnm */
110967 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
110968         break;
110969       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
110970 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
110971         break;
110972       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
110973 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
110974         break;
110975       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
110976 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
110977         break;
110978       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
110979 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
110980         break;
110981       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
110982 {
110983   Token all;
110984   all.z = yymsp[-3].minor.yy0.z;
110985   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
110986   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
110987 }
110988         break;
110989       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
110990 {
110991   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);
110992   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
110993 }
110994         break;
110995       case 270: /* trigger_time ::= BEFORE */
110996       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
110997 { yygotominor.yy392 = TK_BEFORE; }
110998         break;
110999       case 271: /* trigger_time ::= AFTER */
111000 { yygotominor.yy392 = TK_AFTER;  }
111001         break;
111002       case 272: /* trigger_time ::= INSTEAD OF */
111003 { yygotominor.yy392 = TK_INSTEAD;}
111004         break;
111005       case 274: /* trigger_event ::= DELETE|INSERT */
111006       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
111007 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
111008         break;
111009       case 276: /* trigger_event ::= UPDATE OF inscollist */
111010 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
111011         break;
111012       case 279: /* when_clause ::= */
111013       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
111014 { yygotominor.yy122 = 0; }
111015         break;
111016       case 280: /* when_clause ::= WHEN expr */
111017       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
111018 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
111019         break;
111020       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
111021 {
111022   assert( yymsp[-2].minor.yy327!=0 );
111023   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
111024   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
111025   yygotominor.yy327 = yymsp[-2].minor.yy327;
111026 }
111027         break;
111028       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
111029
111030   assert( yymsp[-1].minor.yy327!=0 );
111031   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
111032   yygotominor.yy327 = yymsp[-1].minor.yy327;
111033 }
111034         break;
111035       case 284: /* trnm ::= nm DOT nm */
111036 {
111037   yygotominor.yy0 = yymsp[0].minor.yy0;
111038   sqlite3ErrorMsg(pParse, 
111039         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
111040         "statements within triggers");
111041 }
111042         break;
111043       case 286: /* tridxby ::= INDEXED BY nm */
111044 {
111045   sqlite3ErrorMsg(pParse,
111046         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
111047         "within triggers");
111048 }
111049         break;
111050       case 287: /* tridxby ::= NOT INDEXED */
111051 {
111052   sqlite3ErrorMsg(pParse,
111053         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
111054         "within triggers");
111055 }
111056         break;
111057       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
111058 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
111059         break;
111060       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
111061 {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);}
111062         break;
111063       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
111064 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
111065         break;
111066       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
111067 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
111068         break;
111069       case 292: /* trigger_cmd ::= select */
111070 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
111071         break;
111072       case 293: /* expr ::= RAISE LP IGNORE RP */
111073 {
111074   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
111075   if( yygotominor.yy342.pExpr ){
111076     yygotominor.yy342.pExpr->affinity = OE_Ignore;
111077   }
111078   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111079   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111080 }
111081         break;
111082       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
111083 {
111084   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
111085   if( yygotominor.yy342.pExpr ) {
111086     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
111087   }
111088   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
111089   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111090 }
111091         break;
111092       case 295: /* raisetype ::= ROLLBACK */
111093 {yygotominor.yy392 = OE_Rollback;}
111094         break;
111095       case 297: /* raisetype ::= FAIL */
111096 {yygotominor.yy392 = OE_Fail;}
111097         break;
111098       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
111099 {
111100   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
111101 }
111102         break;
111103       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
111104 {
111105   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
111106 }
111107         break;
111108       case 300: /* cmd ::= DETACH database_kw_opt expr */
111109 {
111110   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
111111 }
111112         break;
111113       case 305: /* cmd ::= REINDEX */
111114 {sqlite3Reindex(pParse, 0, 0);}
111115         break;
111116       case 306: /* cmd ::= REINDEX nm dbnm */
111117 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111118         break;
111119       case 307: /* cmd ::= ANALYZE */
111120 {sqlite3Analyze(pParse, 0, 0);}
111121         break;
111122       case 308: /* cmd ::= ANALYZE nm dbnm */
111123 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111124         break;
111125       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
111126 {
111127   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
111128 }
111129         break;
111130       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
111131 {
111132   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
111133 }
111134         break;
111135       case 311: /* add_column_fullname ::= fullname */
111136 {
111137   pParse->db->lookaside.bEnabled = 0;
111138   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
111139 }
111140         break;
111141       case 314: /* cmd ::= create_vtab */
111142 {sqlite3VtabFinishParse(pParse,0);}
111143         break;
111144       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
111145 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
111146         break;
111147       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
111148 {
111149     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
111150 }
111151         break;
111152       case 319: /* vtabarg ::= */
111153 {sqlite3VtabArgInit(pParse);}
111154         break;
111155       case 321: /* vtabargtoken ::= ANY */
111156       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
111157       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
111158 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
111159         break;
111160       default:
111161       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
111162       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
111163       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
111164       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
111165       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
111166       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
111167       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
111168       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
111169       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
111170       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
111171       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
111172       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
111173       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
111174       /* (44) type ::= */ yytestcase(yyruleno==44);
111175       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
111176       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
111177       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
111178       /* (54) carglist ::= */ yytestcase(yyruleno==54);
111179       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
111180       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
111181       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
111182       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
111183       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
111184       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
111185       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
111186       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
111187       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
111188       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
111189       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
111190       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
111191       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
111192       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
111193       /* (324) anylist ::= */ yytestcase(yyruleno==324);
111194       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
111195       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
111196         break;
111197   };
111198   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
111199   yygoto = yyRuleInfo[yyruleno].lhs;
111200   yysize = yyRuleInfo[yyruleno].nrhs;
111201   yypParser->yyidx -= yysize;
111202   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
111203   if( yyact < YYNSTATE ){
111204 #ifdef NDEBUG
111205     /* If we are not debugging and the reduce action popped at least
111206     ** one element off the stack, then we can push the new element back
111207     ** onto the stack here, and skip the stack overflow test in yy_shift().
111208     ** That gives a significant speed improvement. */
111209     if( yysize ){
111210       yypParser->yyidx++;
111211       yymsp -= yysize-1;
111212       yymsp->stateno = (YYACTIONTYPE)yyact;
111213       yymsp->major = (YYCODETYPE)yygoto;
111214       yymsp->minor = yygotominor;
111215     }else
111216 #endif
111217     {
111218       yy_shift(yypParser,yyact,yygoto,&yygotominor);
111219     }
111220   }else{
111221     assert( yyact == YYNSTATE + YYNRULE + 1 );
111222     yy_accept(yypParser);
111223   }
111224 }
111225
111226 /*
111227 ** The following code executes when the parse fails
111228 */
111229 #ifndef YYNOERRORRECOVERY
111230 static void yy_parse_failed(
111231   yyParser *yypParser           /* The parser */
111232 ){
111233   sqlite3ParserARG_FETCH;
111234 #ifndef NDEBUG
111235   if( yyTraceFILE ){
111236     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
111237   }
111238 #endif
111239   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111240   /* Here code is inserted which will be executed whenever the
111241   ** parser fails */
111242   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111243 }
111244 #endif /* YYNOERRORRECOVERY */
111245
111246 /*
111247 ** The following code executes when a syntax error first occurs.
111248 */
111249 static void yy_syntax_error(
111250   yyParser *yypParser,           /* The parser */
111251   int yymajor,                   /* The major type of the error token */
111252   YYMINORTYPE yyminor            /* The minor type of the error token */
111253 ){
111254   sqlite3ParserARG_FETCH;
111255 #define TOKEN (yyminor.yy0)
111256
111257   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
111258   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
111259   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
111260   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111261 }
111262
111263 /*
111264 ** The following is executed when the parser accepts
111265 */
111266 static void yy_accept(
111267   yyParser *yypParser           /* The parser */
111268 ){
111269   sqlite3ParserARG_FETCH;
111270 #ifndef NDEBUG
111271   if( yyTraceFILE ){
111272     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
111273   }
111274 #endif
111275   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111276   /* Here code is inserted which will be executed whenever the
111277   ** parser accepts */
111278   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111279 }
111280
111281 /* The main parser program.
111282 ** The first argument is a pointer to a structure obtained from
111283 ** "sqlite3ParserAlloc" which describes the current state of the parser.
111284 ** The second argument is the major token number.  The third is
111285 ** the minor token.  The fourth optional argument is whatever the
111286 ** user wants (and specified in the grammar) and is available for
111287 ** use by the action routines.
111288 **
111289 ** Inputs:
111290 ** <ul>
111291 ** <li> A pointer to the parser (an opaque structure.)
111292 ** <li> The major token number.
111293 ** <li> The minor token number.
111294 ** <li> An option argument of a grammar-specified type.
111295 ** </ul>
111296 **
111297 ** Outputs:
111298 ** None.
111299 */
111300 SQLITE_PRIVATE void sqlite3Parser(
111301   void *yyp,                   /* The parser */
111302   int yymajor,                 /* The major token code number */
111303   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
111304   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
111305 ){
111306   YYMINORTYPE yyminorunion;
111307   int yyact;            /* The parser action. */
111308 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111309   int yyendofinput;     /* True if we are at the end of input */
111310 #endif
111311 #ifdef YYERRORSYMBOL
111312   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
111313 #endif
111314   yyParser *yypParser;  /* The parser */
111315
111316   /* (re)initialize the parser, if necessary */
111317   yypParser = (yyParser*)yyp;
111318   if( yypParser->yyidx<0 ){
111319 #if YYSTACKDEPTH<=0
111320     if( yypParser->yystksz <=0 ){
111321       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
111322       yyminorunion = yyzerominor;
111323       yyStackOverflow(yypParser, &yyminorunion);
111324       return;
111325     }
111326 #endif
111327     yypParser->yyidx = 0;
111328     yypParser->yyerrcnt = -1;
111329     yypParser->yystack[0].stateno = 0;
111330     yypParser->yystack[0].major = 0;
111331   }
111332   yyminorunion.yy0 = yyminor;
111333 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111334   yyendofinput = (yymajor==0);
111335 #endif
111336   sqlite3ParserARG_STORE;
111337
111338 #ifndef NDEBUG
111339   if( yyTraceFILE ){
111340     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
111341   }
111342 #endif
111343
111344   do{
111345     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
111346     if( yyact<YYNSTATE ){
111347       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
111348       yypParser->yyerrcnt--;
111349       yymajor = YYNOCODE;
111350     }else if( yyact < YYNSTATE + YYNRULE ){
111351       yy_reduce(yypParser,yyact-YYNSTATE);
111352     }else{
111353       assert( yyact == YY_ERROR_ACTION );
111354 #ifdef YYERRORSYMBOL
111355       int yymx;
111356 #endif
111357 #ifndef NDEBUG
111358       if( yyTraceFILE ){
111359         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
111360       }
111361 #endif
111362 #ifdef YYERRORSYMBOL
111363       /* A syntax error has occurred.
111364       ** The response to an error depends upon whether or not the
111365       ** grammar defines an error token "ERROR".  
111366       **
111367       ** This is what we do if the grammar does define ERROR:
111368       **
111369       **  * Call the %syntax_error function.
111370       **
111371       **  * Begin popping the stack until we enter a state where
111372       **    it is legal to shift the error symbol, then shift
111373       **    the error symbol.
111374       **
111375       **  * Set the error count to three.
111376       **
111377       **  * Begin accepting and shifting new tokens.  No new error
111378       **    processing will occur until three tokens have been
111379       **    shifted successfully.
111380       **
111381       */
111382       if( yypParser->yyerrcnt<0 ){
111383         yy_syntax_error(yypParser,yymajor,yyminorunion);
111384       }
111385       yymx = yypParser->yystack[yypParser->yyidx].major;
111386       if( yymx==YYERRORSYMBOL || yyerrorhit ){
111387 #ifndef NDEBUG
111388         if( yyTraceFILE ){
111389           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
111390              yyTracePrompt,yyTokenName[yymajor]);
111391         }
111392 #endif
111393         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
111394         yymajor = YYNOCODE;
111395       }else{
111396          while(
111397           yypParser->yyidx >= 0 &&
111398           yymx != YYERRORSYMBOL &&
111399           (yyact = yy_find_reduce_action(
111400                         yypParser->yystack[yypParser->yyidx].stateno,
111401                         YYERRORSYMBOL)) >= YYNSTATE
111402         ){
111403           yy_pop_parser_stack(yypParser);
111404         }
111405         if( yypParser->yyidx < 0 || yymajor==0 ){
111406           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111407           yy_parse_failed(yypParser);
111408           yymajor = YYNOCODE;
111409         }else if( yymx!=YYERRORSYMBOL ){
111410           YYMINORTYPE u2;
111411           u2.YYERRSYMDT = 0;
111412           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
111413         }
111414       }
111415       yypParser->yyerrcnt = 3;
111416       yyerrorhit = 1;
111417 #elif defined(YYNOERRORRECOVERY)
111418       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
111419       ** do any kind of error recovery.  Instead, simply invoke the syntax
111420       ** error routine and continue going as if nothing had happened.
111421       **
111422       ** Applications can set this macro (for example inside %include) if
111423       ** they intend to abandon the parse upon the first syntax error seen.
111424       */
111425       yy_syntax_error(yypParser,yymajor,yyminorunion);
111426       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111427       yymajor = YYNOCODE;
111428       
111429 #else  /* YYERRORSYMBOL is not defined */
111430       /* This is what we do if the grammar does not define ERROR:
111431       **
111432       **  * Report an error message, and throw away the input token.
111433       **
111434       **  * If the input token is $, then fail the parse.
111435       **
111436       ** As before, subsequent error messages are suppressed until
111437       ** three input tokens have been successfully shifted.
111438       */
111439       if( yypParser->yyerrcnt<=0 ){
111440         yy_syntax_error(yypParser,yymajor,yyminorunion);
111441       }
111442       yypParser->yyerrcnt = 3;
111443       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111444       if( yyendofinput ){
111445         yy_parse_failed(yypParser);
111446       }
111447       yymajor = YYNOCODE;
111448 #endif
111449     }
111450   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
111451   return;
111452 }
111453
111454 /************** End of parse.c ***********************************************/
111455 /************** Begin file tokenize.c ****************************************/
111456 /*
111457 ** 2001 September 15
111458 **
111459 ** The author disclaims copyright to this source code.  In place of
111460 ** a legal notice, here is a blessing:
111461 **
111462 **    May you do good and not evil.
111463 **    May you find forgiveness for yourself and forgive others.
111464 **    May you share freely, never taking more than you give.
111465 **
111466 *************************************************************************
111467 ** An tokenizer for SQL
111468 **
111469 ** This file contains C code that splits an SQL input string up into
111470 ** individual tokens and sends those tokens one-by-one over to the
111471 ** parser for analysis.
111472 */
111473 /* #include <stdlib.h> */
111474
111475 /*
111476 ** The charMap() macro maps alphabetic characters into their
111477 ** lower-case ASCII equivalent.  On ASCII machines, this is just
111478 ** an upper-to-lower case map.  On EBCDIC machines we also need
111479 ** to adjust the encoding.  Only alphabetic characters and underscores
111480 ** need to be translated.
111481 */
111482 #ifdef SQLITE_ASCII
111483 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
111484 #endif
111485 #ifdef SQLITE_EBCDIC
111486 # define charMap(X) ebcdicToAscii[(unsigned char)X]
111487 const unsigned char ebcdicToAscii[] = {
111488 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
111489    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
111490    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
111491    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
111492    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
111493    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
111494    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
111495    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
111496    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
111497    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
111498    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
111499    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
111500    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
111501    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
111502    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
111503    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
111504    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
111505 };
111506 #endif
111507
111508 /*
111509 ** The sqlite3KeywordCode function looks up an identifier to determine if
111510 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
111511 ** returned.  If the input is not a keyword, TK_ID is returned.
111512 **
111513 ** The implementation of this routine was generated by a program,
111514 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
111515 ** The output of the mkkeywordhash.c program is written into a file
111516 ** named keywordhash.h and then included into this source file by
111517 ** the #include below.
111518 */
111519 /************** Include keywordhash.h in the middle of tokenize.c ************/
111520 /************** Begin file keywordhash.h *************************************/
111521 /***** This file contains automatically generated code ******
111522 **
111523 ** The code in this file has been automatically generated by
111524 **
111525 **   sqlite/tool/mkkeywordhash.c
111526 **
111527 ** The code in this file implements a function that determines whether
111528 ** or not a given identifier is really an SQL keyword.  The same thing
111529 ** might be implemented more directly using a hand-written hash table.
111530 ** But by using this automatically generated code, the size of the code
111531 ** is substantially reduced.  This is important for embedded applications
111532 ** on platforms with limited memory.
111533 */
111534 /* Hash score: 175 */
111535 static int keywordCode(const char *z, int n){
111536   /* zText[] encodes 811 bytes of keywords in 541 bytes */
111537   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
111538   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
111539   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
111540   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
111541   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
111542   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
111543   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
111544   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
111545   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
111546   /*   INITIALLY                                                          */
111547   static const char zText[540] = {
111548     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
111549     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
111550     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
111551     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
111552     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
111553     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
111554     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
111555     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
111556     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
111557     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
111558     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
111559     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
111560     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
111561     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
111562     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
111563     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
111564     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
111565     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
111566     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
111567     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
111568     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
111569     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
111570     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
111571     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
111572     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
111573     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
111574     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
111575     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
111576     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
111577     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
111578   };
111579   static const unsigned char aHash[127] = {
111580       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
111581       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
111582      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
111583        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
111584        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
111585       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
111586       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
111587       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
111588       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
111589       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
111590   };
111591   static const unsigned char aNext[121] = {
111592        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
111593        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
111594        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
111595        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
111596        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
111597       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
111598       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
111599        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
111600      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
111601       35,  64,   0,   0,
111602   };
111603   static const unsigned char aLen[121] = {
111604        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
111605        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
111606       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
111607        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
111608        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
111609        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
111610        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
111611        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
111612        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
111613        6,   4,   9,   3,
111614   };
111615   static const unsigned short int aOffset[121] = {
111616        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
111617       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
111618       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
111619      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
111620      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
111621      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
111622      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
111623      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
111624      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
111625      521, 527, 531, 536,
111626   };
111627   static const unsigned char aCode[121] = {
111628     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
111629     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
111630     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
111631     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
111632     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
111633     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
111634     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
111635     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
111636     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
111637     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
111638     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
111639     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
111640     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
111641     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
111642     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
111643     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
111644     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
111645     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
111646     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
111647     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
111648     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
111649     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
111650     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
111651     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
111652     TK_ALL,        
111653   };
111654   int h, i;
111655   if( n<2 ) return TK_ID;
111656   h = ((charMap(z[0])*4) ^
111657       (charMap(z[n-1])*3) ^
111658       n) % 127;
111659   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
111660     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
111661       testcase( i==0 ); /* REINDEX */
111662       testcase( i==1 ); /* INDEXED */
111663       testcase( i==2 ); /* INDEX */
111664       testcase( i==3 ); /* DESC */
111665       testcase( i==4 ); /* ESCAPE */
111666       testcase( i==5 ); /* EACH */
111667       testcase( i==6 ); /* CHECK */
111668       testcase( i==7 ); /* KEY */
111669       testcase( i==8 ); /* BEFORE */
111670       testcase( i==9 ); /* FOREIGN */
111671       testcase( i==10 ); /* FOR */
111672       testcase( i==11 ); /* IGNORE */
111673       testcase( i==12 ); /* REGEXP */
111674       testcase( i==13 ); /* EXPLAIN */
111675       testcase( i==14 ); /* INSTEAD */
111676       testcase( i==15 ); /* ADD */
111677       testcase( i==16 ); /* DATABASE */
111678       testcase( i==17 ); /* AS */
111679       testcase( i==18 ); /* SELECT */
111680       testcase( i==19 ); /* TABLE */
111681       testcase( i==20 ); /* LEFT */
111682       testcase( i==21 ); /* THEN */
111683       testcase( i==22 ); /* END */
111684       testcase( i==23 ); /* DEFERRABLE */
111685       testcase( i==24 ); /* ELSE */
111686       testcase( i==25 ); /* EXCEPT */
111687       testcase( i==26 ); /* TRANSACTION */
111688       testcase( i==27 ); /* ACTION */
111689       testcase( i==28 ); /* ON */
111690       testcase( i==29 ); /* NATURAL */
111691       testcase( i==30 ); /* ALTER */
111692       testcase( i==31 ); /* RAISE */
111693       testcase( i==32 ); /* EXCLUSIVE */
111694       testcase( i==33 ); /* EXISTS */
111695       testcase( i==34 ); /* SAVEPOINT */
111696       testcase( i==35 ); /* INTERSECT */
111697       testcase( i==36 ); /* TRIGGER */
111698       testcase( i==37 ); /* REFERENCES */
111699       testcase( i==38 ); /* CONSTRAINT */
111700       testcase( i==39 ); /* INTO */
111701       testcase( i==40 ); /* OFFSET */
111702       testcase( i==41 ); /* OF */
111703       testcase( i==42 ); /* SET */
111704       testcase( i==43 ); /* TEMPORARY */
111705       testcase( i==44 ); /* TEMP */
111706       testcase( i==45 ); /* OR */
111707       testcase( i==46 ); /* UNIQUE */
111708       testcase( i==47 ); /* QUERY */
111709       testcase( i==48 ); /* ATTACH */
111710       testcase( i==49 ); /* HAVING */
111711       testcase( i==50 ); /* GROUP */
111712       testcase( i==51 ); /* UPDATE */
111713       testcase( i==52 ); /* BEGIN */
111714       testcase( i==53 ); /* INNER */
111715       testcase( i==54 ); /* RELEASE */
111716       testcase( i==55 ); /* BETWEEN */
111717       testcase( i==56 ); /* NOTNULL */
111718       testcase( i==57 ); /* NOT */
111719       testcase( i==58 ); /* NO */
111720       testcase( i==59 ); /* NULL */
111721       testcase( i==60 ); /* LIKE */
111722       testcase( i==61 ); /* CASCADE */
111723       testcase( i==62 ); /* ASC */
111724       testcase( i==63 ); /* DELETE */
111725       testcase( i==64 ); /* CASE */
111726       testcase( i==65 ); /* COLLATE */
111727       testcase( i==66 ); /* CREATE */
111728       testcase( i==67 ); /* CURRENT_DATE */
111729       testcase( i==68 ); /* DETACH */
111730       testcase( i==69 ); /* IMMEDIATE */
111731       testcase( i==70 ); /* JOIN */
111732       testcase( i==71 ); /* INSERT */
111733       testcase( i==72 ); /* MATCH */
111734       testcase( i==73 ); /* PLAN */
111735       testcase( i==74 ); /* ANALYZE */
111736       testcase( i==75 ); /* PRAGMA */
111737       testcase( i==76 ); /* ABORT */
111738       testcase( i==77 ); /* VALUES */
111739       testcase( i==78 ); /* VIRTUAL */
111740       testcase( i==79 ); /* LIMIT */
111741       testcase( i==80 ); /* WHEN */
111742       testcase( i==81 ); /* WHERE */
111743       testcase( i==82 ); /* RENAME */
111744       testcase( i==83 ); /* AFTER */
111745       testcase( i==84 ); /* REPLACE */
111746       testcase( i==85 ); /* AND */
111747       testcase( i==86 ); /* DEFAULT */
111748       testcase( i==87 ); /* AUTOINCREMENT */
111749       testcase( i==88 ); /* TO */
111750       testcase( i==89 ); /* IN */
111751       testcase( i==90 ); /* CAST */
111752       testcase( i==91 ); /* COLUMN */
111753       testcase( i==92 ); /* COMMIT */
111754       testcase( i==93 ); /* CONFLICT */
111755       testcase( i==94 ); /* CROSS */
111756       testcase( i==95 ); /* CURRENT_TIMESTAMP */
111757       testcase( i==96 ); /* CURRENT_TIME */
111758       testcase( i==97 ); /* PRIMARY */
111759       testcase( i==98 ); /* DEFERRED */
111760       testcase( i==99 ); /* DISTINCT */
111761       testcase( i==100 ); /* IS */
111762       testcase( i==101 ); /* DROP */
111763       testcase( i==102 ); /* FAIL */
111764       testcase( i==103 ); /* FROM */
111765       testcase( i==104 ); /* FULL */
111766       testcase( i==105 ); /* GLOB */
111767       testcase( i==106 ); /* BY */
111768       testcase( i==107 ); /* IF */
111769       testcase( i==108 ); /* ISNULL */
111770       testcase( i==109 ); /* ORDER */
111771       testcase( i==110 ); /* RESTRICT */
111772       testcase( i==111 ); /* OUTER */
111773       testcase( i==112 ); /* RIGHT */
111774       testcase( i==113 ); /* ROLLBACK */
111775       testcase( i==114 ); /* ROW */
111776       testcase( i==115 ); /* UNION */
111777       testcase( i==116 ); /* USING */
111778       testcase( i==117 ); /* VACUUM */
111779       testcase( i==118 ); /* VIEW */
111780       testcase( i==119 ); /* INITIALLY */
111781       testcase( i==120 ); /* ALL */
111782       return aCode[i];
111783     }
111784   }
111785   return TK_ID;
111786 }
111787 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
111788   return keywordCode((char*)z, n);
111789 }
111790 #define SQLITE_N_KEYWORD 121
111791
111792 /************** End of keywordhash.h *****************************************/
111793 /************** Continuing where we left off in tokenize.c *******************/
111794
111795
111796 /*
111797 ** If X is a character that can be used in an identifier then
111798 ** IdChar(X) will be true.  Otherwise it is false.
111799 **
111800 ** For ASCII, any character with the high-order bit set is
111801 ** allowed in an identifier.  For 7-bit characters, 
111802 ** sqlite3IsIdChar[X] must be 1.
111803 **
111804 ** For EBCDIC, the rules are more complex but have the same
111805 ** end result.
111806 **
111807 ** Ticket #1066.  the SQL standard does not allow '$' in the
111808 ** middle of identfiers.  But many SQL implementations do. 
111809 ** SQLite will allow '$' in identifiers for compatibility.
111810 ** But the feature is undocumented.
111811 */
111812 #ifdef SQLITE_ASCII
111813 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
111814 #endif
111815 #ifdef SQLITE_EBCDIC
111816 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
111817 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111818     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
111819     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
111820     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
111821     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
111822     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
111823     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
111824     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
111825     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
111826     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
111827     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
111828     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
111829     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
111830 };
111831 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
111832 #endif
111833
111834
111835 /*
111836 ** Return the length of the token that begins at z[0]. 
111837 ** Store the token type in *tokenType before returning.
111838 */
111839 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
111840   int i, c;
111841   switch( *z ){
111842     case ' ': case '\t': case '\n': case '\f': case '\r': {
111843       testcase( z[0]==' ' );
111844       testcase( z[0]=='\t' );
111845       testcase( z[0]=='\n' );
111846       testcase( z[0]=='\f' );
111847       testcase( z[0]=='\r' );
111848       for(i=1; sqlite3Isspace(z[i]); i++){}
111849       *tokenType = TK_SPACE;
111850       return i;
111851     }
111852     case '-': {
111853       if( z[1]=='-' ){
111854         /* IMP: R-50417-27976 -- syntax diagram for comments */
111855         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
111856         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111857         return i;
111858       }
111859       *tokenType = TK_MINUS;
111860       return 1;
111861     }
111862     case '(': {
111863       *tokenType = TK_LP;
111864       return 1;
111865     }
111866     case ')': {
111867       *tokenType = TK_RP;
111868       return 1;
111869     }
111870     case ';': {
111871       *tokenType = TK_SEMI;
111872       return 1;
111873     }
111874     case '+': {
111875       *tokenType = TK_PLUS;
111876       return 1;
111877     }
111878     case '*': {
111879       *tokenType = TK_STAR;
111880       return 1;
111881     }
111882     case '/': {
111883       if( z[1]!='*' || z[2]==0 ){
111884         *tokenType = TK_SLASH;
111885         return 1;
111886       }
111887       /* IMP: R-50417-27976 -- syntax diagram for comments */
111888       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
111889       if( c ) i++;
111890       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111891       return i;
111892     }
111893     case '%': {
111894       *tokenType = TK_REM;
111895       return 1;
111896     }
111897     case '=': {
111898       *tokenType = TK_EQ;
111899       return 1 + (z[1]=='=');
111900     }
111901     case '<': {
111902       if( (c=z[1])=='=' ){
111903         *tokenType = TK_LE;
111904         return 2;
111905       }else if( c=='>' ){
111906         *tokenType = TK_NE;
111907         return 2;
111908       }else if( c=='<' ){
111909         *tokenType = TK_LSHIFT;
111910         return 2;
111911       }else{
111912         *tokenType = TK_LT;
111913         return 1;
111914       }
111915     }
111916     case '>': {
111917       if( (c=z[1])=='=' ){
111918         *tokenType = TK_GE;
111919         return 2;
111920       }else if( c=='>' ){
111921         *tokenType = TK_RSHIFT;
111922         return 2;
111923       }else{
111924         *tokenType = TK_GT;
111925         return 1;
111926       }
111927     }
111928     case '!': {
111929       if( z[1]!='=' ){
111930         *tokenType = TK_ILLEGAL;
111931         return 2;
111932       }else{
111933         *tokenType = TK_NE;
111934         return 2;
111935       }
111936     }
111937     case '|': {
111938       if( z[1]!='|' ){
111939         *tokenType = TK_BITOR;
111940         return 1;
111941       }else{
111942         *tokenType = TK_CONCAT;
111943         return 2;
111944       }
111945     }
111946     case ',': {
111947       *tokenType = TK_COMMA;
111948       return 1;
111949     }
111950     case '&': {
111951       *tokenType = TK_BITAND;
111952       return 1;
111953     }
111954     case '~': {
111955       *tokenType = TK_BITNOT;
111956       return 1;
111957     }
111958     case '`':
111959     case '\'':
111960     case '"': {
111961       int delim = z[0];
111962       testcase( delim=='`' );
111963       testcase( delim=='\'' );
111964       testcase( delim=='"' );
111965       for(i=1; (c=z[i])!=0; i++){
111966         if( c==delim ){
111967           if( z[i+1]==delim ){
111968             i++;
111969           }else{
111970             break;
111971           }
111972         }
111973       }
111974       if( c=='\'' ){
111975         *tokenType = TK_STRING;
111976         return i+1;
111977       }else if( c!=0 ){
111978         *tokenType = TK_ID;
111979         return i+1;
111980       }else{
111981         *tokenType = TK_ILLEGAL;
111982         return i;
111983       }
111984     }
111985     case '.': {
111986 #ifndef SQLITE_OMIT_FLOATING_POINT
111987       if( !sqlite3Isdigit(z[1]) )
111988 #endif
111989       {
111990         *tokenType = TK_DOT;
111991         return 1;
111992       }
111993       /* If the next character is a digit, this is a floating point
111994       ** number that begins with ".".  Fall thru into the next case */
111995     }
111996     case '0': case '1': case '2': case '3': case '4':
111997     case '5': case '6': case '7': case '8': case '9': {
111998       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
111999       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
112000       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
112001       testcase( z[0]=='9' );
112002       *tokenType = TK_INTEGER;
112003       for(i=0; sqlite3Isdigit(z[i]); i++){}
112004 #ifndef SQLITE_OMIT_FLOATING_POINT
112005       if( z[i]=='.' ){
112006         i++;
112007         while( sqlite3Isdigit(z[i]) ){ i++; }
112008         *tokenType = TK_FLOAT;
112009       }
112010       if( (z[i]=='e' || z[i]=='E') &&
112011            ( sqlite3Isdigit(z[i+1]) 
112012             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
112013            )
112014       ){
112015         i += 2;
112016         while( sqlite3Isdigit(z[i]) ){ i++; }
112017         *tokenType = TK_FLOAT;
112018       }
112019 #endif
112020       while( IdChar(z[i]) ){
112021         *tokenType = TK_ILLEGAL;
112022         i++;
112023       }
112024       return i;
112025     }
112026     case '[': {
112027       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
112028       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
112029       return i;
112030     }
112031     case '?': {
112032       *tokenType = TK_VARIABLE;
112033       for(i=1; sqlite3Isdigit(z[i]); i++){}
112034       return i;
112035     }
112036     case '#': {
112037       for(i=1; sqlite3Isdigit(z[i]); i++){}
112038       if( i>1 ){
112039         /* Parameters of the form #NNN (where NNN is a number) are used
112040         ** internally by sqlite3NestedParse.  */
112041         *tokenType = TK_REGISTER;
112042         return i;
112043       }
112044       /* Fall through into the next case if the '#' is not followed by
112045       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
112046     }
112047 #ifndef SQLITE_OMIT_TCL_VARIABLE
112048     case '$':
112049 #endif
112050     case '@':  /* For compatibility with MS SQL Server */
112051     case ':': {
112052       int n = 0;
112053       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
112054       *tokenType = TK_VARIABLE;
112055       for(i=1; (c=z[i])!=0; i++){
112056         if( IdChar(c) ){
112057           n++;
112058 #ifndef SQLITE_OMIT_TCL_VARIABLE
112059         }else if( c=='(' && n>0 ){
112060           do{
112061             i++;
112062           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
112063           if( c==')' ){
112064             i++;
112065           }else{
112066             *tokenType = TK_ILLEGAL;
112067           }
112068           break;
112069         }else if( c==':' && z[i+1]==':' ){
112070           i++;
112071 #endif
112072         }else{
112073           break;
112074         }
112075       }
112076       if( n==0 ) *tokenType = TK_ILLEGAL;
112077       return i;
112078     }
112079 #ifndef SQLITE_OMIT_BLOB_LITERAL
112080     case 'x': case 'X': {
112081       testcase( z[0]=='x' ); testcase( z[0]=='X' );
112082       if( z[1]=='\'' ){
112083         *tokenType = TK_BLOB;
112084         for(i=2; sqlite3Isxdigit(z[i]); i++){}
112085         if( z[i]!='\'' || i%2 ){
112086           *tokenType = TK_ILLEGAL;
112087           while( z[i] && z[i]!='\'' ){ i++; }
112088         }
112089         if( z[i] ) i++;
112090         return i;
112091       }
112092       /* Otherwise fall through to the next case */
112093     }
112094 #endif
112095     default: {
112096       if( !IdChar(*z) ){
112097         break;
112098       }
112099       for(i=1; IdChar(z[i]); i++){}
112100       *tokenType = keywordCode((char*)z, i);
112101       return i;
112102     }
112103   }
112104   *tokenType = TK_ILLEGAL;
112105   return 1;
112106 }
112107
112108 /*
112109 ** Run the parser on the given SQL string.  The parser structure is
112110 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
112111 ** then an and attempt is made to write an error message into 
112112 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
112113 ** error message.
112114 */
112115 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
112116   int nErr = 0;                   /* Number of errors encountered */
112117   int i;                          /* Loop counter */
112118   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
112119   int tokenType;                  /* type of the next token */
112120   int lastTokenParsed = -1;       /* type of the previous token */
112121   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
112122   sqlite3 *db = pParse->db;       /* The database connection */
112123   int mxSqlLen;                   /* Max length of an SQL string */
112124
112125
112126   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
112127   if( db->activeVdbeCnt==0 ){
112128     db->u1.isInterrupted = 0;
112129   }
112130   pParse->rc = SQLITE_OK;
112131   pParse->zTail = zSql;
112132   i = 0;
112133   assert( pzErrMsg!=0 );
112134   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
112135   if( pEngine==0 ){
112136     db->mallocFailed = 1;
112137     return SQLITE_NOMEM;
112138   }
112139   assert( pParse->pNewTable==0 );
112140   assert( pParse->pNewTrigger==0 );
112141   assert( pParse->nVar==0 );
112142   assert( pParse->nzVar==0 );
112143   assert( pParse->azVar==0 );
112144   enableLookaside = db->lookaside.bEnabled;
112145   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
112146   while( !db->mallocFailed && zSql[i]!=0 ){
112147     assert( i>=0 );
112148     pParse->sLastToken.z = &zSql[i];
112149     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
112150     i += pParse->sLastToken.n;
112151     if( i>mxSqlLen ){
112152       pParse->rc = SQLITE_TOOBIG;
112153       break;
112154     }
112155     switch( tokenType ){
112156       case TK_SPACE: {
112157         if( db->u1.isInterrupted ){
112158           sqlite3ErrorMsg(pParse, "interrupt");
112159           pParse->rc = SQLITE_INTERRUPT;
112160           goto abort_parse;
112161         }
112162         break;
112163       }
112164       case TK_ILLEGAL: {
112165         sqlite3DbFree(db, *pzErrMsg);
112166         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
112167                         &pParse->sLastToken);
112168         nErr++;
112169         goto abort_parse;
112170       }
112171       case TK_SEMI: {
112172         pParse->zTail = &zSql[i];
112173         /* Fall thru into the default case */
112174       }
112175       default: {
112176         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
112177         lastTokenParsed = tokenType;
112178         if( pParse->rc!=SQLITE_OK ){
112179           goto abort_parse;
112180         }
112181         break;
112182       }
112183     }
112184   }
112185 abort_parse:
112186   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
112187     if( lastTokenParsed!=TK_SEMI ){
112188       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
112189       pParse->zTail = &zSql[i];
112190     }
112191     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
112192   }
112193 #ifdef YYTRACKMAXSTACKDEPTH
112194   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
112195       sqlite3ParserStackPeak(pEngine)
112196   );
112197 #endif /* YYDEBUG */
112198   sqlite3ParserFree(pEngine, sqlite3_free);
112199   db->lookaside.bEnabled = enableLookaside;
112200   if( db->mallocFailed ){
112201     pParse->rc = SQLITE_NOMEM;
112202   }
112203   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
112204     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
112205   }
112206   assert( pzErrMsg!=0 );
112207   if( pParse->zErrMsg ){
112208     *pzErrMsg = pParse->zErrMsg;
112209     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
112210     pParse->zErrMsg = 0;
112211     nErr++;
112212   }
112213   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
112214     sqlite3VdbeDelete(pParse->pVdbe);
112215     pParse->pVdbe = 0;
112216   }
112217 #ifndef SQLITE_OMIT_SHARED_CACHE
112218   if( pParse->nested==0 ){
112219     sqlite3DbFree(db, pParse->aTableLock);
112220     pParse->aTableLock = 0;
112221     pParse->nTableLock = 0;
112222   }
112223 #endif
112224 #ifndef SQLITE_OMIT_VIRTUALTABLE
112225   sqlite3_free(pParse->apVtabLock);
112226 #endif
112227
112228   if( !IN_DECLARE_VTAB ){
112229     /* If the pParse->declareVtab flag is set, do not delete any table 
112230     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
112231     ** will take responsibility for freeing the Table structure.
112232     */
112233     sqlite3DeleteTable(db, pParse->pNewTable);
112234   }
112235
112236   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
112237   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
112238   sqlite3DbFree(db, pParse->azVar);
112239   sqlite3DbFree(db, pParse->aAlias);
112240   while( pParse->pAinc ){
112241     AutoincInfo *p = pParse->pAinc;
112242     pParse->pAinc = p->pNext;
112243     sqlite3DbFree(db, p);
112244   }
112245   while( pParse->pZombieTab ){
112246     Table *p = pParse->pZombieTab;
112247     pParse->pZombieTab = p->pNextZombie;
112248     sqlite3DeleteTable(db, p);
112249   }
112250   if( nErr>0 && pParse->rc==SQLITE_OK ){
112251     pParse->rc = SQLITE_ERROR;
112252   }
112253   return nErr;
112254 }
112255
112256 /************** End of tokenize.c ********************************************/
112257 /************** Begin file complete.c ****************************************/
112258 /*
112259 ** 2001 September 15
112260 **
112261 ** The author disclaims copyright to this source code.  In place of
112262 ** a legal notice, here is a blessing:
112263 **
112264 **    May you do good and not evil.
112265 **    May you find forgiveness for yourself and forgive others.
112266 **    May you share freely, never taking more than you give.
112267 **
112268 *************************************************************************
112269 ** An tokenizer for SQL
112270 **
112271 ** This file contains C code that implements the sqlite3_complete() API.
112272 ** This code used to be part of the tokenizer.c source file.  But by
112273 ** separating it out, the code will be automatically omitted from
112274 ** static links that do not use it.
112275 */
112276 #ifndef SQLITE_OMIT_COMPLETE
112277
112278 /*
112279 ** This is defined in tokenize.c.  We just have to import the definition.
112280 */
112281 #ifndef SQLITE_AMALGAMATION
112282 #ifdef SQLITE_ASCII
112283 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112284 #endif
112285 #ifdef SQLITE_EBCDIC
112286 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
112287 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112288 #endif
112289 #endif /* SQLITE_AMALGAMATION */
112290
112291
112292 /*
112293 ** Token types used by the sqlite3_complete() routine.  See the header
112294 ** comments on that procedure for additional information.
112295 */
112296 #define tkSEMI    0
112297 #define tkWS      1
112298 #define tkOTHER   2
112299 #ifndef SQLITE_OMIT_TRIGGER
112300 #define tkEXPLAIN 3
112301 #define tkCREATE  4
112302 #define tkTEMP    5
112303 #define tkTRIGGER 6
112304 #define tkEND     7
112305 #endif
112306
112307 /*
112308 ** Return TRUE if the given SQL string ends in a semicolon.
112309 **
112310 ** Special handling is require for CREATE TRIGGER statements.
112311 ** Whenever the CREATE TRIGGER keywords are seen, the statement
112312 ** must end with ";END;".
112313 **
112314 ** This implementation uses a state machine with 8 states:
112315 **
112316 **   (0) INVALID   We have not yet seen a non-whitespace character.
112317 **
112318 **   (1) START     At the beginning or end of an SQL statement.  This routine
112319 **                 returns 1 if it ends in the START state and 0 if it ends
112320 **                 in any other state.
112321 **
112322 **   (2) NORMAL    We are in the middle of statement which ends with a single
112323 **                 semicolon.
112324 **
112325 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
112326 **                 a statement.
112327 **
112328 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
112329 **                 statement, possibly preceeded by EXPLAIN and/or followed by
112330 **                 TEMP or TEMPORARY
112331 **
112332 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
112333 **                 ended by a semicolon, the keyword END, and another semicolon.
112334 **
112335 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
112336 **                 the end of a trigger definition.
112337 **
112338 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
112339 **                 of a trigger difinition.
112340 **
112341 ** Transitions between states above are determined by tokens extracted
112342 ** from the input.  The following tokens are significant:
112343 **
112344 **   (0) tkSEMI      A semicolon.
112345 **   (1) tkWS        Whitespace.
112346 **   (2) tkOTHER     Any other SQL token.
112347 **   (3) tkEXPLAIN   The "explain" keyword.
112348 **   (4) tkCREATE    The "create" keyword.
112349 **   (5) tkTEMP      The "temp" or "temporary" keyword.
112350 **   (6) tkTRIGGER   The "trigger" keyword.
112351 **   (7) tkEND       The "end" keyword.
112352 **
112353 ** Whitespace never causes a state transition and is always ignored.
112354 ** This means that a SQL string of all whitespace is invalid.
112355 **
112356 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
112357 ** to recognize the end of a trigger can be omitted.  All we have to do
112358 ** is look for a semicolon that is not part of an string or comment.
112359 */
112360 SQLITE_API int sqlite3_complete(const char *zSql){
112361   u8 state = 0;   /* Current state, using numbers defined in header comment */
112362   u8 token;       /* Value of the next token */
112363
112364 #ifndef SQLITE_OMIT_TRIGGER
112365   /* A complex statement machine used to detect the end of a CREATE TRIGGER
112366   ** statement.  This is the normal case.
112367   */
112368   static const u8 trans[8][8] = {
112369                      /* Token:                                                */
112370      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
112371      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
112372      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
112373      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
112374      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
112375      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
112376      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
112377      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
112378      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
112379   };
112380 #else
112381   /* If triggers are not supported by this compile then the statement machine
112382   ** used to detect the end of a statement is much simplier
112383   */
112384   static const u8 trans[3][3] = {
112385                      /* Token:           */
112386      /* State:       **  SEMI  WS  OTHER */
112387      /* 0 INVALID: */ {    1,  0,     2, },
112388      /* 1   START: */ {    1,  1,     2, },
112389      /* 2  NORMAL: */ {    1,  2,     2, },
112390   };
112391 #endif /* SQLITE_OMIT_TRIGGER */
112392
112393   while( *zSql ){
112394     switch( *zSql ){
112395       case ';': {  /* A semicolon */
112396         token = tkSEMI;
112397         break;
112398       }
112399       case ' ':
112400       case '\r':
112401       case '\t':
112402       case '\n':
112403       case '\f': {  /* White space is ignored */
112404         token = tkWS;
112405         break;
112406       }
112407       case '/': {   /* C-style comments */
112408         if( zSql[1]!='*' ){
112409           token = tkOTHER;
112410           break;
112411         }
112412         zSql += 2;
112413         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
112414         if( zSql[0]==0 ) return 0;
112415         zSql++;
112416         token = tkWS;
112417         break;
112418       }
112419       case '-': {   /* SQL-style comments from "--" to end of line */
112420         if( zSql[1]!='-' ){
112421           token = tkOTHER;
112422           break;
112423         }
112424         while( *zSql && *zSql!='\n' ){ zSql++; }
112425         if( *zSql==0 ) return state==1;
112426         token = tkWS;
112427         break;
112428       }
112429       case '[': {   /* Microsoft-style identifiers in [...] */
112430         zSql++;
112431         while( *zSql && *zSql!=']' ){ zSql++; }
112432         if( *zSql==0 ) return 0;
112433         token = tkOTHER;
112434         break;
112435       }
112436       case '`':     /* Grave-accent quoted symbols used by MySQL */
112437       case '"':     /* single- and double-quoted strings */
112438       case '\'': {
112439         int c = *zSql;
112440         zSql++;
112441         while( *zSql && *zSql!=c ){ zSql++; }
112442         if( *zSql==0 ) return 0;
112443         token = tkOTHER;
112444         break;
112445       }
112446       default: {
112447 #ifdef SQLITE_EBCDIC
112448         unsigned char c;
112449 #endif
112450         if( IdChar((u8)*zSql) ){
112451           /* Keywords and unquoted identifiers */
112452           int nId;
112453           for(nId=1; IdChar(zSql[nId]); nId++){}
112454 #ifdef SQLITE_OMIT_TRIGGER
112455           token = tkOTHER;
112456 #else
112457           switch( *zSql ){
112458             case 'c': case 'C': {
112459               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
112460                 token = tkCREATE;
112461               }else{
112462                 token = tkOTHER;
112463               }
112464               break;
112465             }
112466             case 't': case 'T': {
112467               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
112468                 token = tkTRIGGER;
112469               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
112470                 token = tkTEMP;
112471               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
112472                 token = tkTEMP;
112473               }else{
112474                 token = tkOTHER;
112475               }
112476               break;
112477             }
112478             case 'e':  case 'E': {
112479               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
112480                 token = tkEND;
112481               }else
112482 #ifndef SQLITE_OMIT_EXPLAIN
112483               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
112484                 token = tkEXPLAIN;
112485               }else
112486 #endif
112487               {
112488                 token = tkOTHER;
112489               }
112490               break;
112491             }
112492             default: {
112493               token = tkOTHER;
112494               break;
112495             }
112496           }
112497 #endif /* SQLITE_OMIT_TRIGGER */
112498           zSql += nId-1;
112499         }else{
112500           /* Operators and special symbols */
112501           token = tkOTHER;
112502         }
112503         break;
112504       }
112505     }
112506     state = trans[state][token];
112507     zSql++;
112508   }
112509   return state==1;
112510 }
112511
112512 #ifndef SQLITE_OMIT_UTF16
112513 /*
112514 ** This routine is the same as the sqlite3_complete() routine described
112515 ** above, except that the parameter is required to be UTF-16 encoded, not
112516 ** UTF-8.
112517 */
112518 SQLITE_API int sqlite3_complete16(const void *zSql){
112519   sqlite3_value *pVal;
112520   char const *zSql8;
112521   int rc = SQLITE_NOMEM;
112522
112523 #ifndef SQLITE_OMIT_AUTOINIT
112524   rc = sqlite3_initialize();
112525   if( rc ) return rc;
112526 #endif
112527   pVal = sqlite3ValueNew(0);
112528   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
112529   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
112530   if( zSql8 ){
112531     rc = sqlite3_complete(zSql8);
112532   }else{
112533     rc = SQLITE_NOMEM;
112534   }
112535   sqlite3ValueFree(pVal);
112536   return sqlite3ApiExit(0, rc);
112537 }
112538 #endif /* SQLITE_OMIT_UTF16 */
112539 #endif /* SQLITE_OMIT_COMPLETE */
112540
112541 /************** End of complete.c ********************************************/
112542 /************** Begin file main.c ********************************************/
112543 /*
112544 ** 2001 September 15
112545 **
112546 ** The author disclaims copyright to this source code.  In place of
112547 ** a legal notice, here is a blessing:
112548 **
112549 **    May you do good and not evil.
112550 **    May you find forgiveness for yourself and forgive others.
112551 **    May you share freely, never taking more than you give.
112552 **
112553 *************************************************************************
112554 ** Main file for the SQLite library.  The routines in this file
112555 ** implement the programmer interface to the library.  Routines in
112556 ** other files are for internal use by SQLite and should not be
112557 ** accessed by users of the library.
112558 */
112559
112560 #ifdef SQLITE_ENABLE_FTS3
112561 /************** Include fts3.h in the middle of main.c ***********************/
112562 /************** Begin file fts3.h ********************************************/
112563 /*
112564 ** 2006 Oct 10
112565 **
112566 ** The author disclaims copyright to this source code.  In place of
112567 ** a legal notice, here is a blessing:
112568 **
112569 **    May you do good and not evil.
112570 **    May you find forgiveness for yourself and forgive others.
112571 **    May you share freely, never taking more than you give.
112572 **
112573 ******************************************************************************
112574 **
112575 ** This header file is used by programs that want to link against the
112576 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
112577 */
112578
112579 #if 0
112580 extern "C" {
112581 #endif  /* __cplusplus */
112582
112583 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
112584
112585 #if 0
112586 }  /* extern "C" */
112587 #endif  /* __cplusplus */
112588
112589 /************** End of fts3.h ************************************************/
112590 /************** Continuing where we left off in main.c ***********************/
112591 #endif
112592 #ifdef SQLITE_ENABLE_RTREE
112593 /************** Include rtree.h in the middle of main.c **********************/
112594 /************** Begin file rtree.h *******************************************/
112595 /*
112596 ** 2008 May 26
112597 **
112598 ** The author disclaims copyright to this source code.  In place of
112599 ** a legal notice, here is a blessing:
112600 **
112601 **    May you do good and not evil.
112602 **    May you find forgiveness for yourself and forgive others.
112603 **    May you share freely, never taking more than you give.
112604 **
112605 ******************************************************************************
112606 **
112607 ** This header file is used by programs that want to link against the
112608 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
112609 */
112610
112611 #if 0
112612 extern "C" {
112613 #endif  /* __cplusplus */
112614
112615 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
112616
112617 #if 0
112618 }  /* extern "C" */
112619 #endif  /* __cplusplus */
112620
112621 /************** End of rtree.h ***********************************************/
112622 /************** Continuing where we left off in main.c ***********************/
112623 #endif
112624 #ifdef SQLITE_ENABLE_ICU
112625 /************** Include sqliteicu.h in the middle of main.c ******************/
112626 /************** Begin file sqliteicu.h ***************************************/
112627 /*
112628 ** 2008 May 26
112629 **
112630 ** The author disclaims copyright to this source code.  In place of
112631 ** a legal notice, here is a blessing:
112632 **
112633 **    May you do good and not evil.
112634 **    May you find forgiveness for yourself and forgive others.
112635 **    May you share freely, never taking more than you give.
112636 **
112637 ******************************************************************************
112638 **
112639 ** This header file is used by programs that want to link against the
112640 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
112641 */
112642
112643 #if 0
112644 extern "C" {
112645 #endif  /* __cplusplus */
112646
112647 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
112648
112649 #if 0
112650 }  /* extern "C" */
112651 #endif  /* __cplusplus */
112652
112653
112654 /************** End of sqliteicu.h *******************************************/
112655 /************** Continuing where we left off in main.c ***********************/
112656 #endif
112657
112658 #ifndef SQLITE_AMALGAMATION
112659 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
112660 ** contains the text of SQLITE_VERSION macro. 
112661 */
112662 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
112663 #endif
112664
112665 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
112666 ** a pointer to the to the sqlite3_version[] string constant. 
112667 */
112668 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
112669
112670 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
112671 ** pointer to a string constant whose value is the same as the
112672 ** SQLITE_SOURCE_ID C preprocessor macro. 
112673 */
112674 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
112675
112676 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
112677 ** returns an integer equal to SQLITE_VERSION_NUMBER.
112678 */
112679 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
112680
112681 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
112682 ** zero if and only if SQLite was compiled with mutexing code omitted due to
112683 ** the SQLITE_THREADSAFE compile-time option being set to 0.
112684 */
112685 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
112686
112687 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
112688 /*
112689 ** If the following function pointer is not NULL and if
112690 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
112691 ** I/O active are written using this function.  These messages
112692 ** are intended for debugging activity only.
112693 */
112694 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
112695 #endif
112696
112697 /*
112698 ** If the following global variable points to a string which is the
112699 ** name of a directory, then that directory will be used to store
112700 ** temporary files.
112701 **
112702 ** See also the "PRAGMA temp_store_directory" SQL command.
112703 */
112704 SQLITE_API char *sqlite3_temp_directory = 0;
112705
112706 /*
112707 ** If the following global variable points to a string which is the
112708 ** name of a directory, then that directory will be used to store
112709 ** all database files specified with a relative pathname.
112710 **
112711 ** See also the "PRAGMA data_store_directory" SQL command.
112712 */
112713 SQLITE_API char *sqlite3_data_directory = 0;
112714
112715 /*
112716 ** Initialize SQLite.  
112717 **
112718 ** This routine must be called to initialize the memory allocation,
112719 ** VFS, and mutex subsystems prior to doing any serious work with
112720 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
112721 ** this routine will be called automatically by key routines such as
112722 ** sqlite3_open().  
112723 **
112724 ** This routine is a no-op except on its very first call for the process,
112725 ** or for the first call after a call to sqlite3_shutdown.
112726 **
112727 ** The first thread to call this routine runs the initialization to
112728 ** completion.  If subsequent threads call this routine before the first
112729 ** thread has finished the initialization process, then the subsequent
112730 ** threads must block until the first thread finishes with the initialization.
112731 **
112732 ** The first thread might call this routine recursively.  Recursive
112733 ** calls to this routine should not block, of course.  Otherwise the
112734 ** initialization process would never complete.
112735 **
112736 ** Let X be the first thread to enter this routine.  Let Y be some other
112737 ** thread.  Then while the initial invocation of this routine by X is
112738 ** incomplete, it is required that:
112739 **
112740 **    *  Calls to this routine from Y must block until the outer-most
112741 **       call by X completes.
112742 **
112743 **    *  Recursive calls to this routine from thread X return immediately
112744 **       without blocking.
112745 */
112746 SQLITE_API int sqlite3_initialize(void){
112747   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
112748   int rc;                                      /* Result code */
112749
112750 #ifdef SQLITE_OMIT_WSD
112751   rc = sqlite3_wsd_init(4096, 24);
112752   if( rc!=SQLITE_OK ){
112753     return rc;
112754   }
112755 #endif
112756
112757   /* If SQLite is already completely initialized, then this call
112758   ** to sqlite3_initialize() should be a no-op.  But the initialization
112759   ** must be complete.  So isInit must not be set until the very end
112760   ** of this routine.
112761   */
112762   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
112763
112764 #ifdef SQLITE_ENABLE_SQLLOG
112765   {
112766     extern void sqlite3_init_sqllog(void);
112767     sqlite3_init_sqllog();
112768   }
112769 #endif
112770
112771   /* Make sure the mutex subsystem is initialized.  If unable to 
112772   ** initialize the mutex subsystem, return early with the error.
112773   ** If the system is so sick that we are unable to allocate a mutex,
112774   ** there is not much SQLite is going to be able to do.
112775   **
112776   ** The mutex subsystem must take care of serializing its own
112777   ** initialization.
112778   */
112779   rc = sqlite3MutexInit();
112780   if( rc ) return rc;
112781
112782   /* Initialize the malloc() system and the recursive pInitMutex mutex.
112783   ** This operation is protected by the STATIC_MASTER mutex.  Note that
112784   ** MutexAlloc() is called for a static mutex prior to initializing the
112785   ** malloc subsystem - this implies that the allocation of a static
112786   ** mutex must not require support from the malloc subsystem.
112787   */
112788   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
112789   sqlite3_mutex_enter(pMaster);
112790   sqlite3GlobalConfig.isMutexInit = 1;
112791   if( !sqlite3GlobalConfig.isMallocInit ){
112792     rc = sqlite3MallocInit();
112793   }
112794   if( rc==SQLITE_OK ){
112795     sqlite3GlobalConfig.isMallocInit = 1;
112796     if( !sqlite3GlobalConfig.pInitMutex ){
112797       sqlite3GlobalConfig.pInitMutex =
112798            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
112799       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
112800         rc = SQLITE_NOMEM;
112801       }
112802     }
112803   }
112804   if( rc==SQLITE_OK ){
112805     sqlite3GlobalConfig.nRefInitMutex++;
112806   }
112807   sqlite3_mutex_leave(pMaster);
112808
112809   /* If rc is not SQLITE_OK at this point, then either the malloc
112810   ** subsystem could not be initialized or the system failed to allocate
112811   ** the pInitMutex mutex. Return an error in either case.  */
112812   if( rc!=SQLITE_OK ){
112813     return rc;
112814   }
112815
112816   /* Do the rest of the initialization under the recursive mutex so
112817   ** that we will be able to handle recursive calls into
112818   ** sqlite3_initialize().  The recursive calls normally come through
112819   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
112820   ** recursive calls might also be possible.
112821   **
112822   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
112823   ** to the xInit method, so the xInit method need not be threadsafe.
112824   **
112825   ** The following mutex is what serializes access to the appdef pcache xInit
112826   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
112827   ** call to sqlite3PcacheInitialize().
112828   */
112829   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
112830   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
112831     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
112832     sqlite3GlobalConfig.inProgress = 1;
112833     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
112834     sqlite3RegisterGlobalFunctions();
112835     if( sqlite3GlobalConfig.isPCacheInit==0 ){
112836       rc = sqlite3PcacheInitialize();
112837     }
112838     if( rc==SQLITE_OK ){
112839       sqlite3GlobalConfig.isPCacheInit = 1;
112840       rc = sqlite3OsInit();
112841     }
112842     if( rc==SQLITE_OK ){
112843       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
112844           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
112845       sqlite3GlobalConfig.isInit = 1;
112846     }
112847     sqlite3GlobalConfig.inProgress = 0;
112848   }
112849   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
112850
112851   /* Go back under the static mutex and clean up the recursive
112852   ** mutex to prevent a resource leak.
112853   */
112854   sqlite3_mutex_enter(pMaster);
112855   sqlite3GlobalConfig.nRefInitMutex--;
112856   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
112857     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
112858     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
112859     sqlite3GlobalConfig.pInitMutex = 0;
112860   }
112861   sqlite3_mutex_leave(pMaster);
112862
112863   /* The following is just a sanity check to make sure SQLite has
112864   ** been compiled correctly.  It is important to run this code, but
112865   ** we don't want to run it too often and soak up CPU cycles for no
112866   ** reason.  So we run it once during initialization.
112867   */
112868 #ifndef NDEBUG
112869 #ifndef SQLITE_OMIT_FLOATING_POINT
112870   /* This section of code's only "output" is via assert() statements. */
112871   if ( rc==SQLITE_OK ){
112872     u64 x = (((u64)1)<<63)-1;
112873     double y;
112874     assert(sizeof(x)==8);
112875     assert(sizeof(x)==sizeof(y));
112876     memcpy(&y, &x, 8);
112877     assert( sqlite3IsNaN(y) );
112878   }
112879 #endif
112880 #endif
112881
112882   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
112883   ** compile-time option.
112884   */
112885 #ifdef SQLITE_EXTRA_INIT
112886   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
112887     int SQLITE_EXTRA_INIT(const char*);
112888     rc = SQLITE_EXTRA_INIT(0);
112889   }
112890 #endif
112891
112892   return rc;
112893 }
112894
112895 /*
112896 ** Undo the effects of sqlite3_initialize().  Must not be called while
112897 ** there are outstanding database connections or memory allocations or
112898 ** while any part of SQLite is otherwise in use in any thread.  This
112899 ** routine is not threadsafe.  But it is safe to invoke this routine
112900 ** on when SQLite is already shut down.  If SQLite is already shut down
112901 ** when this routine is invoked, then this routine is a harmless no-op.
112902 */
112903 SQLITE_API int sqlite3_shutdown(void){
112904   if( sqlite3GlobalConfig.isInit ){
112905 #ifdef SQLITE_EXTRA_SHUTDOWN
112906     void SQLITE_EXTRA_SHUTDOWN(void);
112907     SQLITE_EXTRA_SHUTDOWN();
112908 #endif
112909     sqlite3_os_end();
112910     sqlite3_reset_auto_extension();
112911     sqlite3GlobalConfig.isInit = 0;
112912   }
112913   if( sqlite3GlobalConfig.isPCacheInit ){
112914     sqlite3PcacheShutdown();
112915     sqlite3GlobalConfig.isPCacheInit = 0;
112916   }
112917   if( sqlite3GlobalConfig.isMallocInit ){
112918     sqlite3MallocEnd();
112919     sqlite3GlobalConfig.isMallocInit = 0;
112920
112921 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
112922     /* The heap subsystem has now been shutdown and these values are supposed
112923     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
112924     ** which would rely on that heap subsystem; therefore, make sure these
112925     ** values cannot refer to heap memory that was just invalidated when the
112926     ** heap subsystem was shutdown.  This is only done if the current call to
112927     ** this function resulted in the heap subsystem actually being shutdown.
112928     */
112929     sqlite3_data_directory = 0;
112930     sqlite3_temp_directory = 0;
112931 #endif
112932   }
112933   if( sqlite3GlobalConfig.isMutexInit ){
112934     sqlite3MutexEnd();
112935     sqlite3GlobalConfig.isMutexInit = 0;
112936   }
112937
112938   return SQLITE_OK;
112939 }
112940
112941 /*
112942 ** This API allows applications to modify the global configuration of
112943 ** the SQLite library at run-time.
112944 **
112945 ** This routine should only be called when there are no outstanding
112946 ** database connections or memory allocations.  This routine is not
112947 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
112948 ** behavior.
112949 */
112950 SQLITE_API int sqlite3_config(int op, ...){
112951   va_list ap;
112952   int rc = SQLITE_OK;
112953
112954   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
112955   ** the SQLite library is in use. */
112956   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
112957
112958   va_start(ap, op);
112959   switch( op ){
112960
112961     /* Mutex configuration options are only available in a threadsafe
112962     ** compile. 
112963     */
112964 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
112965     case SQLITE_CONFIG_SINGLETHREAD: {
112966       /* Disable all mutexing */
112967       sqlite3GlobalConfig.bCoreMutex = 0;
112968       sqlite3GlobalConfig.bFullMutex = 0;
112969       break;
112970     }
112971     case SQLITE_CONFIG_MULTITHREAD: {
112972       /* Disable mutexing of database connections */
112973       /* Enable mutexing of core data structures */
112974       sqlite3GlobalConfig.bCoreMutex = 1;
112975       sqlite3GlobalConfig.bFullMutex = 0;
112976       break;
112977     }
112978     case SQLITE_CONFIG_SERIALIZED: {
112979       /* Enable all mutexing */
112980       sqlite3GlobalConfig.bCoreMutex = 1;
112981       sqlite3GlobalConfig.bFullMutex = 1;
112982       break;
112983     }
112984     case SQLITE_CONFIG_MUTEX: {
112985       /* Specify an alternative mutex implementation */
112986       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
112987       break;
112988     }
112989     case SQLITE_CONFIG_GETMUTEX: {
112990       /* Retrieve the current mutex implementation */
112991       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
112992       break;
112993     }
112994 #endif
112995
112996
112997     case SQLITE_CONFIG_MALLOC: {
112998       /* Specify an alternative malloc implementation */
112999       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
113000       break;
113001     }
113002     case SQLITE_CONFIG_GETMALLOC: {
113003       /* Retrieve the current malloc() implementation */
113004       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
113005       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
113006       break;
113007     }
113008     case SQLITE_CONFIG_MEMSTATUS: {
113009       /* Enable or disable the malloc status collection */
113010       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
113011       break;
113012     }
113013     case SQLITE_CONFIG_SCRATCH: {
113014       /* Designate a buffer for scratch memory space */
113015       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
113016       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
113017       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
113018       break;
113019     }
113020     case SQLITE_CONFIG_PAGECACHE: {
113021       /* Designate a buffer for page cache memory space */
113022       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
113023       sqlite3GlobalConfig.szPage = va_arg(ap, int);
113024       sqlite3GlobalConfig.nPage = va_arg(ap, int);
113025       break;
113026     }
113027
113028     case SQLITE_CONFIG_PCACHE: {
113029       /* no-op */
113030       break;
113031     }
113032     case SQLITE_CONFIG_GETPCACHE: {
113033       /* now an error */
113034       rc = SQLITE_ERROR;
113035       break;
113036     }
113037
113038     case SQLITE_CONFIG_PCACHE2: {
113039       /* Specify an alternative page cache implementation */
113040       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
113041       break;
113042     }
113043     case SQLITE_CONFIG_GETPCACHE2: {
113044       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
113045         sqlite3PCacheSetDefault();
113046       }
113047       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
113048       break;
113049     }
113050
113051 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
113052     case SQLITE_CONFIG_HEAP: {
113053       /* Designate a buffer for heap memory space */
113054       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
113055       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
113056       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
113057
113058       if( sqlite3GlobalConfig.mnReq<1 ){
113059         sqlite3GlobalConfig.mnReq = 1;
113060       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
113061         /* cap min request size at 2^12 */
113062         sqlite3GlobalConfig.mnReq = (1<<12);
113063       }
113064
113065       if( sqlite3GlobalConfig.pHeap==0 ){
113066         /* If the heap pointer is NULL, then restore the malloc implementation
113067         ** back to NULL pointers too.  This will cause the malloc to go
113068         ** back to its default implementation when sqlite3_initialize() is
113069         ** run.
113070         */
113071         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
113072       }else{
113073         /* The heap pointer is not NULL, then install one of the
113074         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
113075         ** ENABLE_MEMSYS5 is defined, return an error.
113076         */
113077 #ifdef SQLITE_ENABLE_MEMSYS3
113078         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
113079 #endif
113080 #ifdef SQLITE_ENABLE_MEMSYS5
113081         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
113082 #endif
113083       }
113084       break;
113085     }
113086 #endif
113087
113088     case SQLITE_CONFIG_LOOKASIDE: {
113089       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
113090       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
113091       break;
113092     }
113093     
113094     /* Record a pointer to the logger funcction and its first argument.
113095     ** The default is NULL.  Logging is disabled if the function pointer is
113096     ** NULL.
113097     */
113098     case SQLITE_CONFIG_LOG: {
113099       /* MSVC is picky about pulling func ptrs from va lists.
113100       ** http://support.microsoft.com/kb/47961
113101       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
113102       */
113103       typedef void(*LOGFUNC_t)(void*,int,const char*);
113104       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
113105       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
113106       break;
113107     }
113108
113109     case SQLITE_CONFIG_URI: {
113110       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
113111       break;
113112     }
113113
113114     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
113115       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
113116       break;
113117     }
113118
113119 #ifdef SQLITE_ENABLE_SQLLOG
113120     case SQLITE_CONFIG_SQLLOG: {
113121       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
113122       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
113123       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
113124       break;
113125     }
113126 #endif
113127
113128     default: {
113129       rc = SQLITE_ERROR;
113130       break;
113131     }
113132   }
113133   va_end(ap);
113134   return rc;
113135 }
113136
113137 /*
113138 ** Set up the lookaside buffers for a database connection.
113139 ** Return SQLITE_OK on success.  
113140 ** If lookaside is already active, return SQLITE_BUSY.
113141 **
113142 ** The sz parameter is the number of bytes in each lookaside slot.
113143 ** The cnt parameter is the number of slots.  If pStart is NULL the
113144 ** space for the lookaside memory is obtained from sqlite3_malloc().
113145 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
113146 ** the lookaside memory.
113147 */
113148 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
113149   void *pStart;
113150   if( db->lookaside.nOut ){
113151     return SQLITE_BUSY;
113152   }
113153   /* Free any existing lookaside buffer for this handle before
113154   ** allocating a new one so we don't have to have space for 
113155   ** both at the same time.
113156   */
113157   if( db->lookaside.bMalloced ){
113158     sqlite3_free(db->lookaside.pStart);
113159   }
113160   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
113161   ** than a pointer to be useful.
113162   */
113163   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
113164   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
113165   if( cnt<0 ) cnt = 0;
113166   if( sz==0 || cnt==0 ){
113167     sz = 0;
113168     pStart = 0;
113169   }else if( pBuf==0 ){
113170     sqlite3BeginBenignMalloc();
113171     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
113172     sqlite3EndBenignMalloc();
113173     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
113174   }else{
113175     pStart = pBuf;
113176   }
113177   db->lookaside.pStart = pStart;
113178   db->lookaside.pFree = 0;
113179   db->lookaside.sz = (u16)sz;
113180   if( pStart ){
113181     int i;
113182     LookasideSlot *p;
113183     assert( sz > (int)sizeof(LookasideSlot*) );
113184     p = (LookasideSlot*)pStart;
113185     for(i=cnt-1; i>=0; i--){
113186       p->pNext = db->lookaside.pFree;
113187       db->lookaside.pFree = p;
113188       p = (LookasideSlot*)&((u8*)p)[sz];
113189     }
113190     db->lookaside.pEnd = p;
113191     db->lookaside.bEnabled = 1;
113192     db->lookaside.bMalloced = pBuf==0 ?1:0;
113193   }else{
113194     db->lookaside.pEnd = 0;
113195     db->lookaside.bEnabled = 0;
113196     db->lookaside.bMalloced = 0;
113197   }
113198   return SQLITE_OK;
113199 }
113200
113201 /*
113202 ** Return the mutex associated with a database connection.
113203 */
113204 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
113205   return db->mutex;
113206 }
113207
113208 /*
113209 ** Free up as much memory as we can from the given database
113210 ** connection.
113211 */
113212 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
113213   int i;
113214   sqlite3_mutex_enter(db->mutex);
113215   sqlite3BtreeEnterAll(db);
113216   for(i=0; i<db->nDb; i++){
113217     Btree *pBt = db->aDb[i].pBt;
113218     if( pBt ){
113219       Pager *pPager = sqlite3BtreePager(pBt);
113220       sqlite3PagerShrink(pPager);
113221     }
113222   }
113223   sqlite3BtreeLeaveAll(db);
113224   sqlite3_mutex_leave(db->mutex);
113225   return SQLITE_OK;
113226 }
113227
113228 /*
113229 ** Configuration settings for an individual database connection
113230 */
113231 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
113232   va_list ap;
113233   int rc;
113234   va_start(ap, op);
113235   switch( op ){
113236     case SQLITE_DBCONFIG_LOOKASIDE: {
113237       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
113238       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
113239       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
113240       rc = setupLookaside(db, pBuf, sz, cnt);
113241       break;
113242     }
113243     default: {
113244       static const struct {
113245         int op;      /* The opcode */
113246         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
113247       } aFlagOp[] = {
113248         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
113249         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
113250       };
113251       unsigned int i;
113252       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
113253       for(i=0; i<ArraySize(aFlagOp); i++){
113254         if( aFlagOp[i].op==op ){
113255           int onoff = va_arg(ap, int);
113256           int *pRes = va_arg(ap, int*);
113257           int oldFlags = db->flags;
113258           if( onoff>0 ){
113259             db->flags |= aFlagOp[i].mask;
113260           }else if( onoff==0 ){
113261             db->flags &= ~aFlagOp[i].mask;
113262           }
113263           if( oldFlags!=db->flags ){
113264             sqlite3ExpirePreparedStatements(db);
113265           }
113266           if( pRes ){
113267             *pRes = (db->flags & aFlagOp[i].mask)!=0;
113268           }
113269           rc = SQLITE_OK;
113270           break;
113271         }
113272       }
113273       break;
113274     }
113275   }
113276   va_end(ap);
113277   return rc;
113278 }
113279
113280
113281 /*
113282 ** Return true if the buffer z[0..n-1] contains all spaces.
113283 */
113284 static int allSpaces(const char *z, int n){
113285   while( n>0 && z[n-1]==' ' ){ n--; }
113286   return n==0;
113287 }
113288
113289 /*
113290 ** This is the default collating function named "BINARY" which is always
113291 ** available.
113292 **
113293 ** If the padFlag argument is not NULL then space padding at the end
113294 ** of strings is ignored.  This implements the RTRIM collation.
113295 */
113296 static int binCollFunc(
113297   void *padFlag,
113298   int nKey1, const void *pKey1,
113299   int nKey2, const void *pKey2
113300 ){
113301   int rc, n;
113302   n = nKey1<nKey2 ? nKey1 : nKey2;
113303   rc = memcmp(pKey1, pKey2, n);
113304   if( rc==0 ){
113305     if( padFlag
113306      && allSpaces(((char*)pKey1)+n, nKey1-n)
113307      && allSpaces(((char*)pKey2)+n, nKey2-n)
113308     ){
113309       /* Leave rc unchanged at 0 */
113310     }else{
113311       rc = nKey1 - nKey2;
113312     }
113313   }
113314   return rc;
113315 }
113316
113317 /*
113318 ** Another built-in collating sequence: NOCASE. 
113319 **
113320 ** This collating sequence is intended to be used for "case independant
113321 ** comparison". SQLite's knowledge of upper and lower case equivalents
113322 ** extends only to the 26 characters used in the English language.
113323 **
113324 ** At the moment there is only a UTF-8 implementation.
113325 */
113326 static int nocaseCollatingFunc(
113327   void *NotUsed,
113328   int nKey1, const void *pKey1,
113329   int nKey2, const void *pKey2
113330 ){
113331   int r = sqlite3StrNICmp(
113332       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
113333   UNUSED_PARAMETER(NotUsed);
113334   if( 0==r ){
113335     r = nKey1-nKey2;
113336   }
113337   return r;
113338 }
113339
113340 /*
113341 ** Return the ROWID of the most recent insert
113342 */
113343 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
113344   return db->lastRowid;
113345 }
113346
113347 /*
113348 ** Return the number of changes in the most recent call to sqlite3_exec().
113349 */
113350 SQLITE_API int sqlite3_changes(sqlite3 *db){
113351   return db->nChange;
113352 }
113353
113354 /*
113355 ** Return the number of changes since the database handle was opened.
113356 */
113357 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
113358   return db->nTotalChange;
113359 }
113360
113361 /*
113362 ** Close all open savepoints. This function only manipulates fields of the
113363 ** database handle object, it does not close any savepoints that may be open
113364 ** at the b-tree/pager level.
113365 */
113366 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
113367   while( db->pSavepoint ){
113368     Savepoint *pTmp = db->pSavepoint;
113369     db->pSavepoint = pTmp->pNext;
113370     sqlite3DbFree(db, pTmp);
113371   }
113372   db->nSavepoint = 0;
113373   db->nStatement = 0;
113374   db->isTransactionSavepoint = 0;
113375 }
113376
113377 /*
113378 ** Invoke the destructor function associated with FuncDef p, if any. Except,
113379 ** if this is not the last copy of the function, do not invoke it. Multiple
113380 ** copies of a single function are created when create_function() is called
113381 ** with SQLITE_ANY as the encoding.
113382 */
113383 static void functionDestroy(sqlite3 *db, FuncDef *p){
113384   FuncDestructor *pDestructor = p->pDestructor;
113385   if( pDestructor ){
113386     pDestructor->nRef--;
113387     if( pDestructor->nRef==0 ){
113388       pDestructor->xDestroy(pDestructor->pUserData);
113389       sqlite3DbFree(db, pDestructor);
113390     }
113391   }
113392 }
113393
113394 /*
113395 ** Disconnect all sqlite3_vtab objects that belong to database connection
113396 ** db. This is called when db is being closed.
113397 */
113398 static void disconnectAllVtab(sqlite3 *db){
113399 #ifndef SQLITE_OMIT_VIRTUALTABLE
113400   int i;
113401   sqlite3BtreeEnterAll(db);
113402   for(i=0; i<db->nDb; i++){
113403     Schema *pSchema = db->aDb[i].pSchema;
113404     if( db->aDb[i].pSchema ){
113405       HashElem *p;
113406       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
113407         Table *pTab = (Table *)sqliteHashData(p);
113408         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
113409       }
113410     }
113411   }
113412   sqlite3BtreeLeaveAll(db);
113413 #else
113414   UNUSED_PARAMETER(db);
113415 #endif
113416 }
113417
113418 /*
113419 ** Return TRUE if database connection db has unfinalized prepared
113420 ** statements or unfinished sqlite3_backup objects.  
113421 */
113422 static int connectionIsBusy(sqlite3 *db){
113423   int j;
113424   assert( sqlite3_mutex_held(db->mutex) );
113425   if( db->pVdbe ) return 1;
113426   for(j=0; j<db->nDb; j++){
113427     Btree *pBt = db->aDb[j].pBt;
113428     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
113429   }
113430   return 0;
113431 }
113432
113433 /*
113434 ** Close an existing SQLite database
113435 */
113436 static int sqlite3Close(sqlite3 *db, int forceZombie){
113437   if( !db ){
113438     return SQLITE_OK;
113439   }
113440   if( !sqlite3SafetyCheckSickOrOk(db) ){
113441     return SQLITE_MISUSE_BKPT;
113442   }
113443   sqlite3_mutex_enter(db->mutex);
113444
113445   /* Force xDisconnect calls on all virtual tables */
113446   disconnectAllVtab(db);
113447
113448   /* If a transaction is open, the disconnectAllVtab() call above
113449   ** will not have called the xDisconnect() method on any virtual
113450   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
113451   ** call will do so. We need to do this before the check for active
113452   ** SQL statements below, as the v-table implementation may be storing
113453   ** some prepared statements internally.
113454   */
113455   sqlite3VtabRollback(db);
113456
113457   /* Legacy behavior (sqlite3_close() behavior) is to return
113458   ** SQLITE_BUSY if the connection can not be closed immediately.
113459   */
113460   if( !forceZombie && connectionIsBusy(db) ){
113461     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
113462        "statements or unfinished backups");
113463     sqlite3_mutex_leave(db->mutex);
113464     return SQLITE_BUSY;
113465   }
113466
113467 #ifdef SQLITE_ENABLE_SQLLOG
113468   if( sqlite3GlobalConfig.xSqllog ){
113469     /* Closing the handle. Fourth parameter is passed the value 2. */
113470     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
113471   }
113472 #endif
113473
113474   /* Convert the connection into a zombie and then close it.
113475   */
113476   db->magic = SQLITE_MAGIC_ZOMBIE;
113477   sqlite3LeaveMutexAndCloseZombie(db);
113478   return SQLITE_OK;
113479 }
113480
113481 /*
113482 ** Two variations on the public interface for closing a database
113483 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
113484 ** leaves the connection option if there are unfinalized prepared
113485 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
113486 ** version forces the connection to become a zombie if there are
113487 ** unclosed resources, and arranges for deallocation when the last
113488 ** prepare statement or sqlite3_backup closes.
113489 */
113490 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
113491 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
113492
113493
113494 /*
113495 ** Close the mutex on database connection db.
113496 **
113497 ** Furthermore, if database connection db is a zombie (meaning that there
113498 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
113499 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
113500 ** finished, then free all resources.
113501 */
113502 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
113503   HashElem *i;                    /* Hash table iterator */
113504   int j;
113505
113506   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
113507   ** or if the connection has not yet been closed by sqlite3_close_v2(),
113508   ** then just leave the mutex and return.
113509   */
113510   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
113511     sqlite3_mutex_leave(db->mutex);
113512     return;
113513   }
113514
113515   /* If we reach this point, it means that the database connection has
113516   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
113517   ** pased to sqlite3_close (meaning that it is a zombie).  Therefore,
113518   ** go ahead and free all resources.
113519   */
113520
113521   /* Free any outstanding Savepoint structures. */
113522   sqlite3CloseSavepoints(db);
113523
113524   /* Close all database connections */
113525   for(j=0; j<db->nDb; j++){
113526     struct Db *pDb = &db->aDb[j];
113527     if( pDb->pBt ){
113528       sqlite3BtreeClose(pDb->pBt);
113529       pDb->pBt = 0;
113530       if( j!=1 ){
113531         pDb->pSchema = 0;
113532       }
113533     }
113534   }
113535   /* Clear the TEMP schema separately and last */
113536   if( db->aDb[1].pSchema ){
113537     sqlite3SchemaClear(db->aDb[1].pSchema);
113538   }
113539   sqlite3VtabUnlockList(db);
113540
113541   /* Free up the array of auxiliary databases */
113542   sqlite3CollapseDatabaseArray(db);
113543   assert( db->nDb<=2 );
113544   assert( db->aDb==db->aDbStatic );
113545
113546   /* Tell the code in notify.c that the connection no longer holds any
113547   ** locks and does not require any further unlock-notify callbacks.
113548   */
113549   sqlite3ConnectionClosed(db);
113550
113551   for(j=0; j<ArraySize(db->aFunc.a); j++){
113552     FuncDef *pNext, *pHash, *p;
113553     for(p=db->aFunc.a[j]; p; p=pHash){
113554       pHash = p->pHash;
113555       while( p ){
113556         functionDestroy(db, p);
113557         pNext = p->pNext;
113558         sqlite3DbFree(db, p);
113559         p = pNext;
113560       }
113561     }
113562   }
113563   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
113564     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
113565     /* Invoke any destructors registered for collation sequence user data. */
113566     for(j=0; j<3; j++){
113567       if( pColl[j].xDel ){
113568         pColl[j].xDel(pColl[j].pUser);
113569       }
113570     }
113571     sqlite3DbFree(db, pColl);
113572   }
113573   sqlite3HashClear(&db->aCollSeq);
113574 #ifndef SQLITE_OMIT_VIRTUALTABLE
113575   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
113576     Module *pMod = (Module *)sqliteHashData(i);
113577     if( pMod->xDestroy ){
113578       pMod->xDestroy(pMod->pAux);
113579     }
113580     sqlite3DbFree(db, pMod);
113581   }
113582   sqlite3HashClear(&db->aModule);
113583 #endif
113584
113585   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
113586   if( db->pErr ){
113587     sqlite3ValueFree(db->pErr);
113588   }
113589   sqlite3CloseExtensions(db);
113590
113591   db->magic = SQLITE_MAGIC_ERROR;
113592
113593   /* The temp-database schema is allocated differently from the other schema
113594   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
113595   ** So it needs to be freed here. Todo: Why not roll the temp schema into
113596   ** the same sqliteMalloc() as the one that allocates the database 
113597   ** structure?
113598   */
113599   sqlite3DbFree(db, db->aDb[1].pSchema);
113600   sqlite3_mutex_leave(db->mutex);
113601   db->magic = SQLITE_MAGIC_CLOSED;
113602   sqlite3_mutex_free(db->mutex);
113603   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
113604   if( db->lookaside.bMalloced ){
113605     sqlite3_free(db->lookaside.pStart);
113606   }
113607   sqlite3_free(db);
113608 }
113609
113610 /*
113611 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
113612 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
113613 ** breaker") and made to return tripCode if there are any further
113614 ** attempts to use that cursor.
113615 */
113616 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
113617   int i;
113618   int inTrans = 0;
113619   assert( sqlite3_mutex_held(db->mutex) );
113620   sqlite3BeginBenignMalloc();
113621   for(i=0; i<db->nDb; i++){
113622     Btree *p = db->aDb[i].pBt;
113623     if( p ){
113624       if( sqlite3BtreeIsInTrans(p) ){
113625         inTrans = 1;
113626       }
113627       sqlite3BtreeRollback(p, tripCode);
113628       db->aDb[i].inTrans = 0;
113629     }
113630   }
113631   sqlite3VtabRollback(db);
113632   sqlite3EndBenignMalloc();
113633
113634   if( db->flags&SQLITE_InternChanges ){
113635     sqlite3ExpirePreparedStatements(db);
113636     sqlite3ResetAllSchemasOfConnection(db);
113637   }
113638
113639   /* Any deferred constraint violations have now been resolved. */
113640   db->nDeferredCons = 0;
113641
113642   /* If one has been configured, invoke the rollback-hook callback */
113643   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
113644     db->xRollbackCallback(db->pRollbackArg);
113645   }
113646 }
113647
113648 /*
113649 ** Return a static string that describes the kind of error specified in the
113650 ** argument.
113651 */
113652 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
113653   static const char* const aMsg[] = {
113654     /* SQLITE_OK          */ "not an error",
113655     /* SQLITE_ERROR       */ "SQL logic error or missing database",
113656     /* SQLITE_INTERNAL    */ 0,
113657     /* SQLITE_PERM        */ "access permission denied",
113658     /* SQLITE_ABORT       */ "callback requested query abort",
113659     /* SQLITE_BUSY        */ "database is locked",
113660     /* SQLITE_LOCKED      */ "database table is locked",
113661     /* SQLITE_NOMEM       */ "out of memory",
113662     /* SQLITE_READONLY    */ "attempt to write a readonly database",
113663     /* SQLITE_INTERRUPT   */ "interrupted",
113664     /* SQLITE_IOERR       */ "disk I/O error",
113665     /* SQLITE_CORRUPT     */ "database disk image is malformed",
113666     /* SQLITE_NOTFOUND    */ "unknown operation",
113667     /* SQLITE_FULL        */ "database or disk is full",
113668     /* SQLITE_CANTOPEN    */ "unable to open database file",
113669     /* SQLITE_PROTOCOL    */ "locking protocol",
113670     /* SQLITE_EMPTY       */ "table contains no data",
113671     /* SQLITE_SCHEMA      */ "database schema has changed",
113672     /* SQLITE_TOOBIG      */ "string or blob too big",
113673     /* SQLITE_CONSTRAINT  */ "constraint failed",
113674     /* SQLITE_MISMATCH    */ "datatype mismatch",
113675     /* SQLITE_MISUSE      */ "library routine called out of sequence",
113676     /* SQLITE_NOLFS       */ "large file support is disabled",
113677     /* SQLITE_AUTH        */ "authorization denied",
113678     /* SQLITE_FORMAT      */ "auxiliary database format error",
113679     /* SQLITE_RANGE       */ "bind or column index out of range",
113680     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
113681   };
113682   const char *zErr = "unknown error";
113683   switch( rc ){
113684     case SQLITE_ABORT_ROLLBACK: {
113685       zErr = "abort due to ROLLBACK";
113686       break;
113687     }
113688     default: {
113689       rc &= 0xff;
113690       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
113691         zErr = aMsg[rc];
113692       }
113693       break;
113694     }
113695   }
113696   return zErr;
113697 }
113698
113699 /*
113700 ** This routine implements a busy callback that sleeps and tries
113701 ** again until a timeout value is reached.  The timeout value is
113702 ** an integer number of milliseconds passed in as the first
113703 ** argument.
113704 */
113705 static int sqliteDefaultBusyCallback(
113706  void *ptr,               /* Database connection */
113707  int count                /* Number of times table has been busy */
113708 ){
113709 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
113710   static const u8 delays[] =
113711      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
113712   static const u8 totals[] =
113713      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
113714 # define NDELAY ArraySize(delays)
113715   sqlite3 *db = (sqlite3 *)ptr;
113716   int timeout = db->busyTimeout;
113717   int delay, prior;
113718
113719   assert( count>=0 );
113720   if( count < NDELAY ){
113721     delay = delays[count];
113722     prior = totals[count];
113723   }else{
113724     delay = delays[NDELAY-1];
113725     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
113726   }
113727   if( prior + delay > timeout ){
113728     delay = timeout - prior;
113729     if( delay<=0 ) return 0;
113730   }
113731   sqlite3OsSleep(db->pVfs, delay*1000);
113732   return 1;
113733 #else
113734   sqlite3 *db = (sqlite3 *)ptr;
113735   int timeout = ((sqlite3 *)ptr)->busyTimeout;
113736   if( (count+1)*1000 > timeout ){
113737     return 0;
113738   }
113739   sqlite3OsSleep(db->pVfs, 1000000);
113740   return 1;
113741 #endif
113742 }
113743
113744 /*
113745 ** Invoke the given busy handler.
113746 **
113747 ** This routine is called when an operation failed with a lock.
113748 ** If this routine returns non-zero, the lock is retried.  If it
113749 ** returns 0, the operation aborts with an SQLITE_BUSY error.
113750 */
113751 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
113752   int rc;
113753   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
113754   rc = p->xFunc(p->pArg, p->nBusy);
113755   if( rc==0 ){
113756     p->nBusy = -1;
113757   }else{
113758     p->nBusy++;
113759   }
113760   return rc; 
113761 }
113762
113763 /*
113764 ** This routine sets the busy callback for an Sqlite database to the
113765 ** given callback function with the given argument.
113766 */
113767 SQLITE_API int sqlite3_busy_handler(
113768   sqlite3 *db,
113769   int (*xBusy)(void*,int),
113770   void *pArg
113771 ){
113772   sqlite3_mutex_enter(db->mutex);
113773   db->busyHandler.xFunc = xBusy;
113774   db->busyHandler.pArg = pArg;
113775   db->busyHandler.nBusy = 0;
113776   db->busyTimeout = 0;
113777   sqlite3_mutex_leave(db->mutex);
113778   return SQLITE_OK;
113779 }
113780
113781 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
113782 /*
113783 ** This routine sets the progress callback for an Sqlite database to the
113784 ** given callback function with the given argument. The progress callback will
113785 ** be invoked every nOps opcodes.
113786 */
113787 SQLITE_API void sqlite3_progress_handler(
113788   sqlite3 *db, 
113789   int nOps,
113790   int (*xProgress)(void*), 
113791   void *pArg
113792 ){
113793   sqlite3_mutex_enter(db->mutex);
113794   if( nOps>0 ){
113795     db->xProgress = xProgress;
113796     db->nProgressOps = nOps;
113797     db->pProgressArg = pArg;
113798   }else{
113799     db->xProgress = 0;
113800     db->nProgressOps = 0;
113801     db->pProgressArg = 0;
113802   }
113803   sqlite3_mutex_leave(db->mutex);
113804 }
113805 #endif
113806
113807
113808 /*
113809 ** This routine installs a default busy handler that waits for the
113810 ** specified number of milliseconds before returning 0.
113811 */
113812 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
113813   if( ms>0 ){
113814     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
113815     db->busyTimeout = ms;
113816   }else{
113817     sqlite3_busy_handler(db, 0, 0);
113818   }
113819   return SQLITE_OK;
113820 }
113821
113822 /*
113823 ** Cause any pending operation to stop at its earliest opportunity.
113824 */
113825 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
113826   db->u1.isInterrupted = 1;
113827 }
113828
113829
113830 /*
113831 ** This function is exactly the same as sqlite3_create_function(), except
113832 ** that it is designed to be called by internal code. The difference is
113833 ** that if a malloc() fails in sqlite3_create_function(), an error code
113834 ** is returned and the mallocFailed flag cleared. 
113835 */
113836 SQLITE_PRIVATE int sqlite3CreateFunc(
113837   sqlite3 *db,
113838   const char *zFunctionName,
113839   int nArg,
113840   int enc,
113841   void *pUserData,
113842   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113843   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113844   void (*xFinal)(sqlite3_context*),
113845   FuncDestructor *pDestructor
113846 ){
113847   FuncDef *p;
113848   int nName;
113849
113850   assert( sqlite3_mutex_held(db->mutex) );
113851   if( zFunctionName==0 ||
113852       (xFunc && (xFinal || xStep)) || 
113853       (!xFunc && (xFinal && !xStep)) ||
113854       (!xFunc && (!xFinal && xStep)) ||
113855       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
113856       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
113857     return SQLITE_MISUSE_BKPT;
113858   }
113859   
113860 #ifndef SQLITE_OMIT_UTF16
113861   /* If SQLITE_UTF16 is specified as the encoding type, transform this
113862   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
113863   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
113864   **
113865   ** If SQLITE_ANY is specified, add three versions of the function
113866   ** to the hash table.
113867   */
113868   if( enc==SQLITE_UTF16 ){
113869     enc = SQLITE_UTF16NATIVE;
113870   }else if( enc==SQLITE_ANY ){
113871     int rc;
113872     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
113873          pUserData, xFunc, xStep, xFinal, pDestructor);
113874     if( rc==SQLITE_OK ){
113875       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
113876           pUserData, xFunc, xStep, xFinal, pDestructor);
113877     }
113878     if( rc!=SQLITE_OK ){
113879       return rc;
113880     }
113881     enc = SQLITE_UTF16BE;
113882   }
113883 #else
113884   enc = SQLITE_UTF8;
113885 #endif
113886   
113887   /* Check if an existing function is being overridden or deleted. If so,
113888   ** and there are active VMs, then return SQLITE_BUSY. If a function
113889   ** is being overridden/deleted but there are no active VMs, allow the
113890   ** operation to continue but invalidate all precompiled statements.
113891   */
113892   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
113893   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
113894     if( db->activeVdbeCnt ){
113895       sqlite3Error(db, SQLITE_BUSY, 
113896         "unable to delete/modify user-function due to active statements");
113897       assert( !db->mallocFailed );
113898       return SQLITE_BUSY;
113899     }else{
113900       sqlite3ExpirePreparedStatements(db);
113901     }
113902   }
113903
113904   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
113905   assert(p || db->mallocFailed);
113906   if( !p ){
113907     return SQLITE_NOMEM;
113908   }
113909
113910   /* If an older version of the function with a configured destructor is
113911   ** being replaced invoke the destructor function here. */
113912   functionDestroy(db, p);
113913
113914   if( pDestructor ){
113915     pDestructor->nRef++;
113916   }
113917   p->pDestructor = pDestructor;
113918   p->flags = 0;
113919   p->xFunc = xFunc;
113920   p->xStep = xStep;
113921   p->xFinalize = xFinal;
113922   p->pUserData = pUserData;
113923   p->nArg = (u16)nArg;
113924   return SQLITE_OK;
113925 }
113926
113927 /*
113928 ** Create new user functions.
113929 */
113930 SQLITE_API int sqlite3_create_function(
113931   sqlite3 *db,
113932   const char *zFunc,
113933   int nArg,
113934   int enc,
113935   void *p,
113936   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113937   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113938   void (*xFinal)(sqlite3_context*)
113939 ){
113940   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
113941                                     xFinal, 0);
113942 }
113943
113944 SQLITE_API int sqlite3_create_function_v2(
113945   sqlite3 *db,
113946   const char *zFunc,
113947   int nArg,
113948   int enc,
113949   void *p,
113950   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113951   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113952   void (*xFinal)(sqlite3_context*),
113953   void (*xDestroy)(void *)
113954 ){
113955   int rc = SQLITE_ERROR;
113956   FuncDestructor *pArg = 0;
113957   sqlite3_mutex_enter(db->mutex);
113958   if( xDestroy ){
113959     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
113960     if( !pArg ){
113961       xDestroy(p);
113962       goto out;
113963     }
113964     pArg->xDestroy = xDestroy;
113965     pArg->pUserData = p;
113966   }
113967   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
113968   if( pArg && pArg->nRef==0 ){
113969     assert( rc!=SQLITE_OK );
113970     xDestroy(p);
113971     sqlite3DbFree(db, pArg);
113972   }
113973
113974  out:
113975   rc = sqlite3ApiExit(db, rc);
113976   sqlite3_mutex_leave(db->mutex);
113977   return rc;
113978 }
113979
113980 #ifndef SQLITE_OMIT_UTF16
113981 SQLITE_API int sqlite3_create_function16(
113982   sqlite3 *db,
113983   const void *zFunctionName,
113984   int nArg,
113985   int eTextRep,
113986   void *p,
113987   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
113988   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
113989   void (*xFinal)(sqlite3_context*)
113990 ){
113991   int rc;
113992   char *zFunc8;
113993   sqlite3_mutex_enter(db->mutex);
113994   assert( !db->mallocFailed );
113995   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
113996   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
113997   sqlite3DbFree(db, zFunc8);
113998   rc = sqlite3ApiExit(db, rc);
113999   sqlite3_mutex_leave(db->mutex);
114000   return rc;
114001 }
114002 #endif
114003
114004
114005 /*
114006 ** Declare that a function has been overloaded by a virtual table.
114007 **
114008 ** If the function already exists as a regular global function, then
114009 ** this routine is a no-op.  If the function does not exist, then create
114010 ** a new one that always throws a run-time error.  
114011 **
114012 ** When virtual tables intend to provide an overloaded function, they
114013 ** should call this routine to make sure the global function exists.
114014 ** A global function must exist in order for name resolution to work
114015 ** properly.
114016 */
114017 SQLITE_API int sqlite3_overload_function(
114018   sqlite3 *db,
114019   const char *zName,
114020   int nArg
114021 ){
114022   int nName = sqlite3Strlen30(zName);
114023   int rc = SQLITE_OK;
114024   sqlite3_mutex_enter(db->mutex);
114025   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
114026     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
114027                            0, sqlite3InvalidFunction, 0, 0, 0);
114028   }
114029   rc = sqlite3ApiExit(db, rc);
114030   sqlite3_mutex_leave(db->mutex);
114031   return rc;
114032 }
114033
114034 #ifndef SQLITE_OMIT_TRACE
114035 /*
114036 ** Register a trace function.  The pArg from the previously registered trace
114037 ** is returned.  
114038 **
114039 ** A NULL trace function means that no tracing is executes.  A non-NULL
114040 ** trace is a pointer to a function that is invoked at the start of each
114041 ** SQL statement.
114042 */
114043 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
114044   void *pOld;
114045   sqlite3_mutex_enter(db->mutex);
114046   pOld = db->pTraceArg;
114047   db->xTrace = xTrace;
114048   db->pTraceArg = pArg;
114049   sqlite3_mutex_leave(db->mutex);
114050   return pOld;
114051 }
114052 /*
114053 ** Register a profile function.  The pArg from the previously registered 
114054 ** profile function is returned.  
114055 **
114056 ** A NULL profile function means that no profiling is executes.  A non-NULL
114057 ** profile is a pointer to a function that is invoked at the conclusion of
114058 ** each SQL statement that is run.
114059 */
114060 SQLITE_API void *sqlite3_profile(
114061   sqlite3 *db,
114062   void (*xProfile)(void*,const char*,sqlite_uint64),
114063   void *pArg
114064 ){
114065   void *pOld;
114066   sqlite3_mutex_enter(db->mutex);
114067   pOld = db->pProfileArg;
114068   db->xProfile = xProfile;
114069   db->pProfileArg = pArg;
114070   sqlite3_mutex_leave(db->mutex);
114071   return pOld;
114072 }
114073 #endif /* SQLITE_OMIT_TRACE */
114074
114075 /*
114076 ** Register a function to be invoked when a transaction commits.
114077 ** If the invoked function returns non-zero, then the commit becomes a
114078 ** rollback.
114079 */
114080 SQLITE_API void *sqlite3_commit_hook(
114081   sqlite3 *db,              /* Attach the hook to this database */
114082   int (*xCallback)(void*),  /* Function to invoke on each commit */
114083   void *pArg                /* Argument to the function */
114084 ){
114085   void *pOld;
114086   sqlite3_mutex_enter(db->mutex);
114087   pOld = db->pCommitArg;
114088   db->xCommitCallback = xCallback;
114089   db->pCommitArg = pArg;
114090   sqlite3_mutex_leave(db->mutex);
114091   return pOld;
114092 }
114093
114094 /*
114095 ** Register a callback to be invoked each time a row is updated,
114096 ** inserted or deleted using this database connection.
114097 */
114098 SQLITE_API void *sqlite3_update_hook(
114099   sqlite3 *db,              /* Attach the hook to this database */
114100   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
114101   void *pArg                /* Argument to the function */
114102 ){
114103   void *pRet;
114104   sqlite3_mutex_enter(db->mutex);
114105   pRet = db->pUpdateArg;
114106   db->xUpdateCallback = xCallback;
114107   db->pUpdateArg = pArg;
114108   sqlite3_mutex_leave(db->mutex);
114109   return pRet;
114110 }
114111
114112 /*
114113 ** Register a callback to be invoked each time a transaction is rolled
114114 ** back by this database connection.
114115 */
114116 SQLITE_API void *sqlite3_rollback_hook(
114117   sqlite3 *db,              /* Attach the hook to this database */
114118   void (*xCallback)(void*), /* Callback function */
114119   void *pArg                /* Argument to the function */
114120 ){
114121   void *pRet;
114122   sqlite3_mutex_enter(db->mutex);
114123   pRet = db->pRollbackArg;
114124   db->xRollbackCallback = xCallback;
114125   db->pRollbackArg = pArg;
114126   sqlite3_mutex_leave(db->mutex);
114127   return pRet;
114128 }
114129
114130 #ifndef SQLITE_OMIT_WAL
114131 /*
114132 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
114133 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
114134 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
114135 ** wal_autocheckpoint()).
114136 */ 
114137 SQLITE_PRIVATE int sqlite3WalDefaultHook(
114138   void *pClientData,     /* Argument */
114139   sqlite3 *db,           /* Connection */
114140   const char *zDb,       /* Database */
114141   int nFrame             /* Size of WAL */
114142 ){
114143   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
114144     sqlite3BeginBenignMalloc();
114145     sqlite3_wal_checkpoint(db, zDb);
114146     sqlite3EndBenignMalloc();
114147   }
114148   return SQLITE_OK;
114149 }
114150 #endif /* SQLITE_OMIT_WAL */
114151
114152 /*
114153 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
114154 ** a database after committing a transaction if there are nFrame or
114155 ** more frames in the log file. Passing zero or a negative value as the
114156 ** nFrame parameter disables automatic checkpoints entirely.
114157 **
114158 ** The callback registered by this function replaces any existing callback
114159 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
114160 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
114161 ** configured by this function.
114162 */
114163 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
114164 #ifdef SQLITE_OMIT_WAL
114165   UNUSED_PARAMETER(db);
114166   UNUSED_PARAMETER(nFrame);
114167 #else
114168   if( nFrame>0 ){
114169     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
114170   }else{
114171     sqlite3_wal_hook(db, 0, 0);
114172   }
114173 #endif
114174   return SQLITE_OK;
114175 }
114176
114177 /*
114178 ** Register a callback to be invoked each time a transaction is written
114179 ** into the write-ahead-log by this database connection.
114180 */
114181 SQLITE_API void *sqlite3_wal_hook(
114182   sqlite3 *db,                    /* Attach the hook to this db handle */
114183   int(*xCallback)(void *, sqlite3*, const char*, int),
114184   void *pArg                      /* First argument passed to xCallback() */
114185 ){
114186 #ifndef SQLITE_OMIT_WAL
114187   void *pRet;
114188   sqlite3_mutex_enter(db->mutex);
114189   pRet = db->pWalArg;
114190   db->xWalCallback = xCallback;
114191   db->pWalArg = pArg;
114192   sqlite3_mutex_leave(db->mutex);
114193   return pRet;
114194 #else
114195   return 0;
114196 #endif
114197 }
114198
114199 /*
114200 ** Checkpoint database zDb.
114201 */
114202 SQLITE_API int sqlite3_wal_checkpoint_v2(
114203   sqlite3 *db,                    /* Database handle */
114204   const char *zDb,                /* Name of attached database (or NULL) */
114205   int eMode,                      /* SQLITE_CHECKPOINT_* value */
114206   int *pnLog,                     /* OUT: Size of WAL log in frames */
114207   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
114208 ){
114209 #ifdef SQLITE_OMIT_WAL
114210   return SQLITE_OK;
114211 #else
114212   int rc;                         /* Return code */
114213   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
114214
114215   /* Initialize the output variables to -1 in case an error occurs. */
114216   if( pnLog ) *pnLog = -1;
114217   if( pnCkpt ) *pnCkpt = -1;
114218
114219   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
114220   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
114221   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
114222   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
114223     return SQLITE_MISUSE;
114224   }
114225
114226   sqlite3_mutex_enter(db->mutex);
114227   if( zDb && zDb[0] ){
114228     iDb = sqlite3FindDbName(db, zDb);
114229   }
114230   if( iDb<0 ){
114231     rc = SQLITE_ERROR;
114232     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
114233   }else{
114234     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
114235     sqlite3Error(db, rc, 0);
114236   }
114237   rc = sqlite3ApiExit(db, rc);
114238   sqlite3_mutex_leave(db->mutex);
114239   return rc;
114240 #endif
114241 }
114242
114243
114244 /*
114245 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
114246 ** to contains a zero-length string, all attached databases are 
114247 ** checkpointed.
114248 */
114249 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
114250   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
114251 }
114252
114253 #ifndef SQLITE_OMIT_WAL
114254 /*
114255 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
114256 ** not currently open in WAL mode.
114257 **
114258 ** If a transaction is open on the database being checkpointed, this 
114259 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
114260 ** an error occurs while running the checkpoint, an SQLite error code is 
114261 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
114262 **
114263 ** The mutex on database handle db should be held by the caller. The mutex
114264 ** associated with the specific b-tree being checkpointed is taken by
114265 ** this function while the checkpoint is running.
114266 **
114267 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
114268 ** checkpointed. If an error is encountered it is returned immediately -
114269 ** no attempt is made to checkpoint any remaining databases.
114270 **
114271 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
114272 */
114273 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
114274   int rc = SQLITE_OK;             /* Return code */
114275   int i;                          /* Used to iterate through attached dbs */
114276   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
114277
114278   assert( sqlite3_mutex_held(db->mutex) );
114279   assert( !pnLog || *pnLog==-1 );
114280   assert( !pnCkpt || *pnCkpt==-1 );
114281
114282   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
114283     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
114284       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
114285       pnLog = 0;
114286       pnCkpt = 0;
114287       if( rc==SQLITE_BUSY ){
114288         bBusy = 1;
114289         rc = SQLITE_OK;
114290       }
114291     }
114292   }
114293
114294   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
114295 }
114296 #endif /* SQLITE_OMIT_WAL */
114297
114298 /*
114299 ** This function returns true if main-memory should be used instead of
114300 ** a temporary file for transient pager files and statement journals.
114301 ** The value returned depends on the value of db->temp_store (runtime
114302 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
114303 ** following table describes the relationship between these two values
114304 ** and this functions return value.
114305 **
114306 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
114307 **   -----------------     --------------     ------------------------------
114308 **   0                     any                file      (return 0)
114309 **   1                     1                  file      (return 0)
114310 **   1                     2                  memory    (return 1)
114311 **   1                     0                  file      (return 0)
114312 **   2                     1                  file      (return 0)
114313 **   2                     2                  memory    (return 1)
114314 **   2                     0                  memory    (return 1)
114315 **   3                     any                memory    (return 1)
114316 */
114317 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
114318 #if SQLITE_TEMP_STORE==1
114319   return ( db->temp_store==2 );
114320 #endif
114321 #if SQLITE_TEMP_STORE==2
114322   return ( db->temp_store!=1 );
114323 #endif
114324 #if SQLITE_TEMP_STORE==3
114325   return 1;
114326 #endif
114327 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
114328   return 0;
114329 #endif
114330 }
114331
114332 /*
114333 ** Return UTF-8 encoded English language explanation of the most recent
114334 ** error.
114335 */
114336 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
114337   const char *z;
114338   if( !db ){
114339     return sqlite3ErrStr(SQLITE_NOMEM);
114340   }
114341   if( !sqlite3SafetyCheckSickOrOk(db) ){
114342     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
114343   }
114344   sqlite3_mutex_enter(db->mutex);
114345   if( db->mallocFailed ){
114346     z = sqlite3ErrStr(SQLITE_NOMEM);
114347   }else{
114348     z = (char*)sqlite3_value_text(db->pErr);
114349     assert( !db->mallocFailed );
114350     if( z==0 ){
114351       z = sqlite3ErrStr(db->errCode);
114352     }
114353   }
114354   sqlite3_mutex_leave(db->mutex);
114355   return z;
114356 }
114357
114358 #ifndef SQLITE_OMIT_UTF16
114359 /*
114360 ** Return UTF-16 encoded English language explanation of the most recent
114361 ** error.
114362 */
114363 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
114364   static const u16 outOfMem[] = {
114365     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
114366   };
114367   static const u16 misuse[] = {
114368     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
114369     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
114370     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
114371     'o', 'u', 't', ' ', 
114372     'o', 'f', ' ', 
114373     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
114374   };
114375
114376   const void *z;
114377   if( !db ){
114378     return (void *)outOfMem;
114379   }
114380   if( !sqlite3SafetyCheckSickOrOk(db) ){
114381     return (void *)misuse;
114382   }
114383   sqlite3_mutex_enter(db->mutex);
114384   if( db->mallocFailed ){
114385     z = (void *)outOfMem;
114386   }else{
114387     z = sqlite3_value_text16(db->pErr);
114388     if( z==0 ){
114389       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
114390            SQLITE_UTF8, SQLITE_STATIC);
114391       z = sqlite3_value_text16(db->pErr);
114392     }
114393     /* A malloc() may have failed within the call to sqlite3_value_text16()
114394     ** above. If this is the case, then the db->mallocFailed flag needs to
114395     ** be cleared before returning. Do this directly, instead of via
114396     ** sqlite3ApiExit(), to avoid setting the database handle error message.
114397     */
114398     db->mallocFailed = 0;
114399   }
114400   sqlite3_mutex_leave(db->mutex);
114401   return z;
114402 }
114403 #endif /* SQLITE_OMIT_UTF16 */
114404
114405 /*
114406 ** Return the most recent error code generated by an SQLite routine. If NULL is
114407 ** passed to this function, we assume a malloc() failed during sqlite3_open().
114408 */
114409 SQLITE_API int sqlite3_errcode(sqlite3 *db){
114410   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114411     return SQLITE_MISUSE_BKPT;
114412   }
114413   if( !db || db->mallocFailed ){
114414     return SQLITE_NOMEM;
114415   }
114416   return db->errCode & db->errMask;
114417 }
114418 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
114419   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114420     return SQLITE_MISUSE_BKPT;
114421   }
114422   if( !db || db->mallocFailed ){
114423     return SQLITE_NOMEM;
114424   }
114425   return db->errCode;
114426 }
114427
114428 /*
114429 ** Return a string that describes the kind of error specified in the
114430 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
114431 ** function.
114432 */
114433 SQLITE_API const char *sqlite3_errstr(int rc){
114434   return sqlite3ErrStr(rc);
114435 }
114436
114437 /*
114438 ** Create a new collating function for database "db".  The name is zName
114439 ** and the encoding is enc.
114440 */
114441 static int createCollation(
114442   sqlite3* db,
114443   const char *zName, 
114444   u8 enc,
114445   void* pCtx,
114446   int(*xCompare)(void*,int,const void*,int,const void*),
114447   void(*xDel)(void*)
114448 ){
114449   CollSeq *pColl;
114450   int enc2;
114451   int nName = sqlite3Strlen30(zName);
114452   
114453   assert( sqlite3_mutex_held(db->mutex) );
114454
114455   /* If SQLITE_UTF16 is specified as the encoding type, transform this
114456   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114457   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114458   */
114459   enc2 = enc;
114460   testcase( enc2==SQLITE_UTF16 );
114461   testcase( enc2==SQLITE_UTF16_ALIGNED );
114462   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
114463     enc2 = SQLITE_UTF16NATIVE;
114464   }
114465   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
114466     return SQLITE_MISUSE_BKPT;
114467   }
114468
114469   /* Check if this call is removing or replacing an existing collation 
114470   ** sequence. If so, and there are active VMs, return busy. If there
114471   ** are no active VMs, invalidate any pre-compiled statements.
114472   */
114473   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
114474   if( pColl && pColl->xCmp ){
114475     if( db->activeVdbeCnt ){
114476       sqlite3Error(db, SQLITE_BUSY, 
114477         "unable to delete/modify collation sequence due to active statements");
114478       return SQLITE_BUSY;
114479     }
114480     sqlite3ExpirePreparedStatements(db);
114481
114482     /* If collation sequence pColl was created directly by a call to
114483     ** sqlite3_create_collation, and not generated by synthCollSeq(),
114484     ** then any copies made by synthCollSeq() need to be invalidated.
114485     ** Also, collation destructor - CollSeq.xDel() - function may need
114486     ** to be called.
114487     */ 
114488     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
114489       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
114490       int j;
114491       for(j=0; j<3; j++){
114492         CollSeq *p = &aColl[j];
114493         if( p->enc==pColl->enc ){
114494           if( p->xDel ){
114495             p->xDel(p->pUser);
114496           }
114497           p->xCmp = 0;
114498         }
114499       }
114500     }
114501   }
114502
114503   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
114504   if( pColl==0 ) return SQLITE_NOMEM;
114505   pColl->xCmp = xCompare;
114506   pColl->pUser = pCtx;
114507   pColl->xDel = xDel;
114508   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
114509   sqlite3Error(db, SQLITE_OK, 0);
114510   return SQLITE_OK;
114511 }
114512
114513
114514 /*
114515 ** This array defines hard upper bounds on limit values.  The
114516 ** initializer must be kept in sync with the SQLITE_LIMIT_*
114517 ** #defines in sqlite3.h.
114518 */
114519 static const int aHardLimit[] = {
114520   SQLITE_MAX_LENGTH,
114521   SQLITE_MAX_SQL_LENGTH,
114522   SQLITE_MAX_COLUMN,
114523   SQLITE_MAX_EXPR_DEPTH,
114524   SQLITE_MAX_COMPOUND_SELECT,
114525   SQLITE_MAX_VDBE_OP,
114526   SQLITE_MAX_FUNCTION_ARG,
114527   SQLITE_MAX_ATTACHED,
114528   SQLITE_MAX_LIKE_PATTERN_LENGTH,
114529   SQLITE_MAX_VARIABLE_NUMBER,
114530   SQLITE_MAX_TRIGGER_DEPTH,
114531 };
114532
114533 /*
114534 ** Make sure the hard limits are set to reasonable values
114535 */
114536 #if SQLITE_MAX_LENGTH<100
114537 # error SQLITE_MAX_LENGTH must be at least 100
114538 #endif
114539 #if SQLITE_MAX_SQL_LENGTH<100
114540 # error SQLITE_MAX_SQL_LENGTH must be at least 100
114541 #endif
114542 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
114543 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
114544 #endif
114545 #if SQLITE_MAX_COMPOUND_SELECT<2
114546 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
114547 #endif
114548 #if SQLITE_MAX_VDBE_OP<40
114549 # error SQLITE_MAX_VDBE_OP must be at least 40
114550 #endif
114551 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
114552 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
114553 #endif
114554 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
114555 # error SQLITE_MAX_ATTACHED must be between 0 and 62
114556 #endif
114557 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
114558 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
114559 #endif
114560 #if SQLITE_MAX_COLUMN>32767
114561 # error SQLITE_MAX_COLUMN must not exceed 32767
114562 #endif
114563 #if SQLITE_MAX_TRIGGER_DEPTH<1
114564 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
114565 #endif
114566
114567
114568 /*
114569 ** Change the value of a limit.  Report the old value.
114570 ** If an invalid limit index is supplied, report -1.
114571 ** Make no changes but still report the old value if the
114572 ** new limit is negative.
114573 **
114574 ** A new lower limit does not shrink existing constructs.
114575 ** It merely prevents new constructs that exceed the limit
114576 ** from forming.
114577 */
114578 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
114579   int oldLimit;
114580
114581
114582   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
114583   ** there is a hard upper bound set at compile-time by a C preprocessor
114584   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
114585   ** "_MAX_".)
114586   */
114587   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
114588   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
114589   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
114590   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
114591   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
114592   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
114593   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
114594   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
114595   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
114596                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
114597   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
114598   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
114599   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
114600
114601
114602   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
114603     return -1;
114604   }
114605   oldLimit = db->aLimit[limitId];
114606   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
114607     if( newLimit>aHardLimit[limitId] ){
114608       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
114609     }
114610     db->aLimit[limitId] = newLimit;
114611   }
114612   return oldLimit;                     /* IMP: R-53341-35419 */
114613 }
114614
114615 /*
114616 ** This function is used to parse both URIs and non-URI filenames passed by the
114617 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
114618 ** URIs specified as part of ATTACH statements.
114619 **
114620 ** The first argument to this function is the name of the VFS to use (or
114621 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
114622 ** query parameter. The second argument contains the URI (or non-URI filename)
114623 ** itself. When this function is called the *pFlags variable should contain
114624 ** the default flags to open the database handle with. The value stored in
114625 ** *pFlags may be updated before returning if the URI filename contains 
114626 ** "cache=xxx" or "mode=xxx" query parameters.
114627 **
114628 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
114629 ** the VFS that should be used to open the database file. *pzFile is set to
114630 ** point to a buffer containing the name of the file to open. It is the 
114631 ** responsibility of the caller to eventually call sqlite3_free() to release
114632 ** this buffer.
114633 **
114634 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
114635 ** may be set to point to a buffer containing an English language error 
114636 ** message. It is the responsibility of the caller to eventually release
114637 ** this buffer by calling sqlite3_free().
114638 */
114639 SQLITE_PRIVATE int sqlite3ParseUri(
114640   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
114641   const char *zUri,               /* Nul-terminated URI to parse */
114642   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
114643   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
114644   char **pzFile,                  /* OUT: Filename component of URI */
114645   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
114646 ){
114647   int rc = SQLITE_OK;
114648   unsigned int flags = *pFlags;
114649   const char *zVfs = zDefaultVfs;
114650   char *zFile;
114651   char c;
114652   int nUri = sqlite3Strlen30(zUri);
114653
114654   assert( *pzErrMsg==0 );
114655
114656   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
114657    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
114658   ){
114659     char *zOpt;
114660     int eState;                   /* Parser state when parsing URI */
114661     int iIn;                      /* Input character index */
114662     int iOut = 0;                 /* Output character index */
114663     int nByte = nUri+2;           /* Bytes of space to allocate */
114664
114665     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
114666     ** method that there may be extra parameters following the file-name.  */
114667     flags |= SQLITE_OPEN_URI;
114668
114669     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
114670     zFile = sqlite3_malloc(nByte);
114671     if( !zFile ) return SQLITE_NOMEM;
114672
114673     /* Discard the scheme and authority segments of the URI. */
114674     if( zUri[5]=='/' && zUri[6]=='/' ){
114675       iIn = 7;
114676       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
114677
114678       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
114679         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
114680             iIn-7, &zUri[7]);
114681         rc = SQLITE_ERROR;
114682         goto parse_uri_out;
114683       }
114684     }else{
114685       iIn = 5;
114686     }
114687
114688     /* Copy the filename and any query parameters into the zFile buffer. 
114689     ** Decode %HH escape codes along the way. 
114690     **
114691     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
114692     ** on the parsing context. As follows:
114693     **
114694     **   0: Parsing file-name.
114695     **   1: Parsing name section of a name=value query parameter.
114696     **   2: Parsing value section of a name=value query parameter.
114697     */
114698     eState = 0;
114699     while( (c = zUri[iIn])!=0 && c!='#' ){
114700       iIn++;
114701       if( c=='%' 
114702        && sqlite3Isxdigit(zUri[iIn]) 
114703        && sqlite3Isxdigit(zUri[iIn+1]) 
114704       ){
114705         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
114706         octet += sqlite3HexToInt(zUri[iIn++]);
114707
114708         assert( octet>=0 && octet<256 );
114709         if( octet==0 ){
114710           /* This branch is taken when "%00" appears within the URI. In this
114711           ** case we ignore all text in the remainder of the path, name or
114712           ** value currently being parsed. So ignore the current character
114713           ** and skip to the next "?", "=" or "&", as appropriate. */
114714           while( (c = zUri[iIn])!=0 && c!='#' 
114715               && (eState!=0 || c!='?')
114716               && (eState!=1 || (c!='=' && c!='&'))
114717               && (eState!=2 || c!='&')
114718           ){
114719             iIn++;
114720           }
114721           continue;
114722         }
114723         c = octet;
114724       }else if( eState==1 && (c=='&' || c=='=') ){
114725         if( zFile[iOut-1]==0 ){
114726           /* An empty option name. Ignore this option altogether. */
114727           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
114728           continue;
114729         }
114730         if( c=='&' ){
114731           zFile[iOut++] = '\0';
114732         }else{
114733           eState = 2;
114734         }
114735         c = 0;
114736       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
114737         c = 0;
114738         eState = 1;
114739       }
114740       zFile[iOut++] = c;
114741     }
114742     if( eState==1 ) zFile[iOut++] = '\0';
114743     zFile[iOut++] = '\0';
114744     zFile[iOut++] = '\0';
114745
114746     /* Check if there were any options specified that should be interpreted 
114747     ** here. Options that are interpreted here include "vfs" and those that
114748     ** correspond to flags that may be passed to the sqlite3_open_v2()
114749     ** method. */
114750     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
114751     while( zOpt[0] ){
114752       int nOpt = sqlite3Strlen30(zOpt);
114753       char *zVal = &zOpt[nOpt+1];
114754       int nVal = sqlite3Strlen30(zVal);
114755
114756       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
114757         zVfs = zVal;
114758       }else{
114759         struct OpenMode {
114760           const char *z;
114761           int mode;
114762         } *aMode = 0;
114763         char *zModeType = 0;
114764         int mask = 0;
114765         int limit = 0;
114766
114767         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
114768           static struct OpenMode aCacheMode[] = {
114769             { "shared",  SQLITE_OPEN_SHAREDCACHE },
114770             { "private", SQLITE_OPEN_PRIVATECACHE },
114771             { 0, 0 }
114772           };
114773
114774           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
114775           aMode = aCacheMode;
114776           limit = mask;
114777           zModeType = "cache";
114778         }
114779         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
114780           static struct OpenMode aOpenMode[] = {
114781             { "ro",  SQLITE_OPEN_READONLY },
114782             { "rw",  SQLITE_OPEN_READWRITE }, 
114783             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
114784             { "memory", SQLITE_OPEN_MEMORY },
114785             { 0, 0 }
114786           };
114787
114788           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
114789                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
114790           aMode = aOpenMode;
114791           limit = mask & flags;
114792           zModeType = "access";
114793         }
114794
114795         if( aMode ){
114796           int i;
114797           int mode = 0;
114798           for(i=0; aMode[i].z; i++){
114799             const char *z = aMode[i].z;
114800             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
114801               mode = aMode[i].mode;
114802               break;
114803             }
114804           }
114805           if( mode==0 ){
114806             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
114807             rc = SQLITE_ERROR;
114808             goto parse_uri_out;
114809           }
114810           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
114811             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
114812                                         zModeType, zVal);
114813             rc = SQLITE_PERM;
114814             goto parse_uri_out;
114815           }
114816           flags = (flags & ~mask) | mode;
114817         }
114818       }
114819
114820       zOpt = &zVal[nVal+1];
114821     }
114822
114823   }else{
114824     zFile = sqlite3_malloc(nUri+2);
114825     if( !zFile ) return SQLITE_NOMEM;
114826     memcpy(zFile, zUri, nUri);
114827     zFile[nUri] = '\0';
114828     zFile[nUri+1] = '\0';
114829     flags &= ~SQLITE_OPEN_URI;
114830   }
114831
114832   *ppVfs = sqlite3_vfs_find(zVfs);
114833   if( *ppVfs==0 ){
114834     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
114835     rc = SQLITE_ERROR;
114836   }
114837  parse_uri_out:
114838   if( rc!=SQLITE_OK ){
114839     sqlite3_free(zFile);
114840     zFile = 0;
114841   }
114842   *pFlags = flags;
114843   *pzFile = zFile;
114844   return rc;
114845 }
114846
114847
114848 /*
114849 ** This routine does the work of opening a database on behalf of
114850 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
114851 ** is UTF-8 encoded.
114852 */
114853 static int openDatabase(
114854   const char *zFilename, /* Database filename UTF-8 encoded */
114855   sqlite3 **ppDb,        /* OUT: Returned database handle */
114856   unsigned int flags,    /* Operational flags */
114857   const char *zVfs       /* Name of the VFS to use */
114858 ){
114859   sqlite3 *db;                    /* Store allocated handle here */
114860   int rc;                         /* Return code */
114861   int isThreadsafe;               /* True for threadsafe connections */
114862   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
114863   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
114864
114865   *ppDb = 0;
114866 #ifndef SQLITE_OMIT_AUTOINIT
114867   rc = sqlite3_initialize();
114868   if( rc ) return rc;
114869 #endif
114870
114871   /* Only allow sensible combinations of bits in the flags argument.  
114872   ** Throw an error if any non-sense combination is used.  If we
114873   ** do not block illegal combinations here, it could trigger
114874   ** assert() statements in deeper layers.  Sensible combinations
114875   ** are:
114876   **
114877   **  1:  SQLITE_OPEN_READONLY
114878   **  2:  SQLITE_OPEN_READWRITE
114879   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
114880   */
114881   assert( SQLITE_OPEN_READONLY  == 0x01 );
114882   assert( SQLITE_OPEN_READWRITE == 0x02 );
114883   assert( SQLITE_OPEN_CREATE    == 0x04 );
114884   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
114885   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
114886   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
114887   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
114888
114889   if( sqlite3GlobalConfig.bCoreMutex==0 ){
114890     isThreadsafe = 0;
114891   }else if( flags & SQLITE_OPEN_NOMUTEX ){
114892     isThreadsafe = 0;
114893   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
114894     isThreadsafe = 1;
114895   }else{
114896     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
114897   }
114898   if( flags & SQLITE_OPEN_PRIVATECACHE ){
114899     flags &= ~SQLITE_OPEN_SHAREDCACHE;
114900   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
114901     flags |= SQLITE_OPEN_SHAREDCACHE;
114902   }
114903
114904   /* Remove harmful bits from the flags parameter
114905   **
114906   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
114907   ** dealt with in the previous code block.  Besides these, the only
114908   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
114909   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
114910   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
114911   ** off all other flags.
114912   */
114913   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
114914                SQLITE_OPEN_EXCLUSIVE |
114915                SQLITE_OPEN_MAIN_DB |
114916                SQLITE_OPEN_TEMP_DB | 
114917                SQLITE_OPEN_TRANSIENT_DB | 
114918                SQLITE_OPEN_MAIN_JOURNAL | 
114919                SQLITE_OPEN_TEMP_JOURNAL | 
114920                SQLITE_OPEN_SUBJOURNAL | 
114921                SQLITE_OPEN_MASTER_JOURNAL |
114922                SQLITE_OPEN_NOMUTEX |
114923                SQLITE_OPEN_FULLMUTEX |
114924                SQLITE_OPEN_WAL
114925              );
114926
114927   /* Allocate the sqlite data structure */
114928   db = sqlite3MallocZero( sizeof(sqlite3) );
114929   if( db==0 ) goto opendb_out;
114930   if( isThreadsafe ){
114931     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114932     if( db->mutex==0 ){
114933       sqlite3_free(db);
114934       db = 0;
114935       goto opendb_out;
114936     }
114937   }
114938   sqlite3_mutex_enter(db->mutex);
114939   db->errMask = 0xff;
114940   db->nDb = 2;
114941   db->magic = SQLITE_MAGIC_BUSY;
114942   db->aDb = db->aDbStatic;
114943
114944   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
114945   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
114946   db->autoCommit = 1;
114947   db->nextAutovac = -1;
114948   db->nextPagesize = 0;
114949   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
114950 #if SQLITE_DEFAULT_FILE_FORMAT<4
114951                  | SQLITE_LegacyFileFmt
114952 #endif
114953 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
114954                  | SQLITE_LoadExtension
114955 #endif
114956 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
114957                  | SQLITE_RecTriggers
114958 #endif
114959 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
114960                  | SQLITE_ForeignKeys
114961 #endif
114962       ;
114963   sqlite3HashInit(&db->aCollSeq);
114964 #ifndef SQLITE_OMIT_VIRTUALTABLE
114965   sqlite3HashInit(&db->aModule);
114966 #endif
114967
114968   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
114969   ** and UTF-16, so add a version for each to avoid any unnecessary
114970   ** conversions. The only error that can occur here is a malloc() failure.
114971   */
114972   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
114973   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
114974   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
114975   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
114976   if( db->mallocFailed ){
114977     goto opendb_out;
114978   }
114979   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
114980   assert( db->pDfltColl!=0 );
114981
114982   /* Also add a UTF-8 case-insensitive collation sequence. */
114983   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
114984
114985   /* Parse the filename/URI argument. */
114986   db->openFlags = flags;
114987   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
114988   if( rc!=SQLITE_OK ){
114989     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
114990     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
114991     sqlite3_free(zErrMsg);
114992     goto opendb_out;
114993   }
114994
114995   /* Open the backend database driver */
114996   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
114997                         flags | SQLITE_OPEN_MAIN_DB);
114998   if( rc!=SQLITE_OK ){
114999     if( rc==SQLITE_IOERR_NOMEM ){
115000       rc = SQLITE_NOMEM;
115001     }
115002     sqlite3Error(db, rc, 0);
115003     goto opendb_out;
115004   }
115005   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
115006   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
115007
115008
115009   /* The default safety_level for the main database is 'full'; for the temp
115010   ** database it is 'NONE'. This matches the pager layer defaults.  
115011   */
115012   db->aDb[0].zName = "main";
115013   db->aDb[0].safety_level = 3;
115014   db->aDb[1].zName = "temp";
115015   db->aDb[1].safety_level = 1;
115016
115017   db->magic = SQLITE_MAGIC_OPEN;
115018   if( db->mallocFailed ){
115019     goto opendb_out;
115020   }
115021
115022   /* Register all built-in functions, but do not attempt to read the
115023   ** database schema yet. This is delayed until the first time the database
115024   ** is accessed.
115025   */
115026   sqlite3Error(db, SQLITE_OK, 0);
115027   sqlite3RegisterBuiltinFunctions(db);
115028
115029   /* Load automatic extensions - extensions that have been registered
115030   ** using the sqlite3_automatic_extension() API.
115031   */
115032   rc = sqlite3_errcode(db);
115033   if( rc==SQLITE_OK ){
115034     sqlite3AutoLoadExtensions(db);
115035     rc = sqlite3_errcode(db);
115036     if( rc!=SQLITE_OK ){
115037       goto opendb_out;
115038     }
115039   }
115040
115041 #ifdef SQLITE_ENABLE_FTS1
115042   if( !db->mallocFailed ){
115043     extern int sqlite3Fts1Init(sqlite3*);
115044     rc = sqlite3Fts1Init(db);
115045   }
115046 #endif
115047
115048 #ifdef SQLITE_ENABLE_FTS2
115049   if( !db->mallocFailed && rc==SQLITE_OK ){
115050     extern int sqlite3Fts2Init(sqlite3*);
115051     rc = sqlite3Fts2Init(db);
115052   }
115053 #endif
115054
115055 #ifdef SQLITE_ENABLE_FTS3
115056   if( !db->mallocFailed && rc==SQLITE_OK ){
115057     rc = sqlite3Fts3Init(db);
115058   }
115059 #endif
115060
115061 #ifdef SQLITE_ENABLE_ICU
115062   if( !db->mallocFailed && rc==SQLITE_OK ){
115063     rc = sqlite3IcuInit(db);
115064   }
115065 #endif
115066
115067 #ifdef SQLITE_ENABLE_RTREE
115068   if( !db->mallocFailed && rc==SQLITE_OK){
115069     rc = sqlite3RtreeInit(db);
115070   }
115071 #endif
115072
115073   sqlite3Error(db, rc, 0);
115074
115075   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
115076   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
115077   ** mode.  Doing nothing at all also makes NORMAL the default.
115078   */
115079 #ifdef SQLITE_DEFAULT_LOCKING_MODE
115080   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
115081   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
115082                           SQLITE_DEFAULT_LOCKING_MODE);
115083 #endif
115084
115085   /* Enable the lookaside-malloc subsystem */
115086   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
115087                         sqlite3GlobalConfig.nLookaside);
115088
115089   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
115090
115091 opendb_out:
115092   sqlite3_free(zOpen);
115093   if( db ){
115094     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
115095     sqlite3_mutex_leave(db->mutex);
115096   }
115097   rc = sqlite3_errcode(db);
115098   assert( db!=0 || rc==SQLITE_NOMEM );
115099   if( rc==SQLITE_NOMEM ){
115100     sqlite3_close(db);
115101     db = 0;
115102   }else if( rc!=SQLITE_OK ){
115103     db->magic = SQLITE_MAGIC_SICK;
115104   }
115105   *ppDb = db;
115106 #ifdef SQLITE_ENABLE_SQLLOG
115107   if( sqlite3GlobalConfig.xSqllog ){
115108     /* Opening a db handle. Fourth parameter is passed 0. */
115109     void *pArg = sqlite3GlobalConfig.pSqllogArg;
115110     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
115111   }
115112 #endif
115113   return sqlite3ApiExit(0, rc);
115114 }
115115
115116 /*
115117 ** Open a new database handle.
115118 */
115119 SQLITE_API int sqlite3_open(
115120   const char *zFilename, 
115121   sqlite3 **ppDb 
115122 ){
115123   return openDatabase(zFilename, ppDb,
115124                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115125 }
115126 SQLITE_API int sqlite3_open_v2(
115127   const char *filename,   /* Database filename (UTF-8) */
115128   sqlite3 **ppDb,         /* OUT: SQLite db handle */
115129   int flags,              /* Flags */
115130   const char *zVfs        /* Name of VFS module to use */
115131 ){
115132   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
115133 }
115134
115135 #ifndef SQLITE_OMIT_UTF16
115136 /*
115137 ** Open a new database handle.
115138 */
115139 SQLITE_API int sqlite3_open16(
115140   const void *zFilename, 
115141   sqlite3 **ppDb
115142 ){
115143   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
115144   sqlite3_value *pVal;
115145   int rc;
115146
115147   assert( zFilename );
115148   assert( ppDb );
115149   *ppDb = 0;
115150 #ifndef SQLITE_OMIT_AUTOINIT
115151   rc = sqlite3_initialize();
115152   if( rc ) return rc;
115153 #endif
115154   pVal = sqlite3ValueNew(0);
115155   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
115156   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
115157   if( zFilename8 ){
115158     rc = openDatabase(zFilename8, ppDb,
115159                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115160     assert( *ppDb || rc==SQLITE_NOMEM );
115161     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
115162       ENC(*ppDb) = SQLITE_UTF16NATIVE;
115163     }
115164   }else{
115165     rc = SQLITE_NOMEM;
115166   }
115167   sqlite3ValueFree(pVal);
115168
115169   return sqlite3ApiExit(0, rc);
115170 }
115171 #endif /* SQLITE_OMIT_UTF16 */
115172
115173 /*
115174 ** Register a new collation sequence with the database handle db.
115175 */
115176 SQLITE_API int sqlite3_create_collation(
115177   sqlite3* db, 
115178   const char *zName, 
115179   int enc, 
115180   void* pCtx,
115181   int(*xCompare)(void*,int,const void*,int,const void*)
115182 ){
115183   int rc;
115184   sqlite3_mutex_enter(db->mutex);
115185   assert( !db->mallocFailed );
115186   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
115187   rc = sqlite3ApiExit(db, rc);
115188   sqlite3_mutex_leave(db->mutex);
115189   return rc;
115190 }
115191
115192 /*
115193 ** Register a new collation sequence with the database handle db.
115194 */
115195 SQLITE_API int sqlite3_create_collation_v2(
115196   sqlite3* db, 
115197   const char *zName, 
115198   int enc, 
115199   void* pCtx,
115200   int(*xCompare)(void*,int,const void*,int,const void*),
115201   void(*xDel)(void*)
115202 ){
115203   int rc;
115204   sqlite3_mutex_enter(db->mutex);
115205   assert( !db->mallocFailed );
115206   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
115207   rc = sqlite3ApiExit(db, rc);
115208   sqlite3_mutex_leave(db->mutex);
115209   return rc;
115210 }
115211
115212 #ifndef SQLITE_OMIT_UTF16
115213 /*
115214 ** Register a new collation sequence with the database handle db.
115215 */
115216 SQLITE_API int sqlite3_create_collation16(
115217   sqlite3* db, 
115218   const void *zName,
115219   int enc, 
115220   void* pCtx,
115221   int(*xCompare)(void*,int,const void*,int,const void*)
115222 ){
115223   int rc = SQLITE_OK;
115224   char *zName8;
115225   sqlite3_mutex_enter(db->mutex);
115226   assert( !db->mallocFailed );
115227   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
115228   if( zName8 ){
115229     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
115230     sqlite3DbFree(db, zName8);
115231   }
115232   rc = sqlite3ApiExit(db, rc);
115233   sqlite3_mutex_leave(db->mutex);
115234   return rc;
115235 }
115236 #endif /* SQLITE_OMIT_UTF16 */
115237
115238 /*
115239 ** Register a collation sequence factory callback with the database handle
115240 ** db. Replace any previously installed collation sequence factory.
115241 */
115242 SQLITE_API int sqlite3_collation_needed(
115243   sqlite3 *db, 
115244   void *pCollNeededArg, 
115245   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
115246 ){
115247   sqlite3_mutex_enter(db->mutex);
115248   db->xCollNeeded = xCollNeeded;
115249   db->xCollNeeded16 = 0;
115250   db->pCollNeededArg = pCollNeededArg;
115251   sqlite3_mutex_leave(db->mutex);
115252   return SQLITE_OK;
115253 }
115254
115255 #ifndef SQLITE_OMIT_UTF16
115256 /*
115257 ** Register a collation sequence factory callback with the database handle
115258 ** db. Replace any previously installed collation sequence factory.
115259 */
115260 SQLITE_API int sqlite3_collation_needed16(
115261   sqlite3 *db, 
115262   void *pCollNeededArg, 
115263   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
115264 ){
115265   sqlite3_mutex_enter(db->mutex);
115266   db->xCollNeeded = 0;
115267   db->xCollNeeded16 = xCollNeeded16;
115268   db->pCollNeededArg = pCollNeededArg;
115269   sqlite3_mutex_leave(db->mutex);
115270   return SQLITE_OK;
115271 }
115272 #endif /* SQLITE_OMIT_UTF16 */
115273
115274 #ifndef SQLITE_OMIT_DEPRECATED
115275 /*
115276 ** This function is now an anachronism. It used to be used to recover from a
115277 ** malloc() failure, but SQLite now does this automatically.
115278 */
115279 SQLITE_API int sqlite3_global_recover(void){
115280   return SQLITE_OK;
115281 }
115282 #endif
115283
115284 /*
115285 ** Test to see whether or not the database connection is in autocommit
115286 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
115287 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
115288 ** by the next COMMIT or ROLLBACK.
115289 **
115290 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
115291 */
115292 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
115293   return db->autoCommit;
115294 }
115295
115296 /*
115297 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
115298 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
115299 ** constants.  They server two purposes:
115300 **
115301 **   1.  Serve as a convenient place to set a breakpoint in a debugger
115302 **       to detect when version error conditions occurs.
115303 **
115304 **   2.  Invoke sqlite3_log() to provide the source code location where
115305 **       a low-level error is first detected.
115306 */
115307 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
115308   testcase( sqlite3GlobalConfig.xLog!=0 );
115309   sqlite3_log(SQLITE_CORRUPT,
115310               "database corruption at line %d of [%.10s]",
115311               lineno, 20+sqlite3_sourceid());
115312   return SQLITE_CORRUPT;
115313 }
115314 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
115315   testcase( sqlite3GlobalConfig.xLog!=0 );
115316   sqlite3_log(SQLITE_MISUSE, 
115317               "misuse at line %d of [%.10s]",
115318               lineno, 20+sqlite3_sourceid());
115319   return SQLITE_MISUSE;
115320 }
115321 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
115322   testcase( sqlite3GlobalConfig.xLog!=0 );
115323   sqlite3_log(SQLITE_CANTOPEN, 
115324               "cannot open file at line %d of [%.10s]",
115325               lineno, 20+sqlite3_sourceid());
115326   return SQLITE_CANTOPEN;
115327 }
115328
115329
115330 #ifndef SQLITE_OMIT_DEPRECATED
115331 /*
115332 ** This is a convenience routine that makes sure that all thread-specific
115333 ** data for this thread has been deallocated.
115334 **
115335 ** SQLite no longer uses thread-specific data so this routine is now a
115336 ** no-op.  It is retained for historical compatibility.
115337 */
115338 SQLITE_API void sqlite3_thread_cleanup(void){
115339 }
115340 #endif
115341
115342 /*
115343 ** Return meta information about a specific column of a database table.
115344 ** See comment in sqlite3.h (sqlite.h.in) for details.
115345 */
115346 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115347 SQLITE_API int sqlite3_table_column_metadata(
115348   sqlite3 *db,                /* Connection handle */
115349   const char *zDbName,        /* Database name or NULL */
115350   const char *zTableName,     /* Table name */
115351   const char *zColumnName,    /* Column name */
115352   char const **pzDataType,    /* OUTPUT: Declared data type */
115353   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
115354   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
115355   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
115356   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
115357 ){
115358   int rc;
115359   char *zErrMsg = 0;
115360   Table *pTab = 0;
115361   Column *pCol = 0;
115362   int iCol;
115363
115364   char const *zDataType = 0;
115365   char const *zCollSeq = 0;
115366   int notnull = 0;
115367   int primarykey = 0;
115368   int autoinc = 0;
115369
115370   /* Ensure the database schema has been loaded */
115371   sqlite3_mutex_enter(db->mutex);
115372   sqlite3BtreeEnterAll(db);
115373   rc = sqlite3Init(db, &zErrMsg);
115374   if( SQLITE_OK!=rc ){
115375     goto error_out;
115376   }
115377
115378   /* Locate the table in question */
115379   pTab = sqlite3FindTable(db, zTableName, zDbName);
115380   if( !pTab || pTab->pSelect ){
115381     pTab = 0;
115382     goto error_out;
115383   }
115384
115385   /* Find the column for which info is requested */
115386   if( sqlite3IsRowid(zColumnName) ){
115387     iCol = pTab->iPKey;
115388     if( iCol>=0 ){
115389       pCol = &pTab->aCol[iCol];
115390     }
115391   }else{
115392     for(iCol=0; iCol<pTab->nCol; iCol++){
115393       pCol = &pTab->aCol[iCol];
115394       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
115395         break;
115396       }
115397     }
115398     if( iCol==pTab->nCol ){
115399       pTab = 0;
115400       goto error_out;
115401     }
115402   }
115403
115404   /* The following block stores the meta information that will be returned
115405   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
115406   ** and autoinc. At this point there are two possibilities:
115407   ** 
115408   **     1. The specified column name was rowid", "oid" or "_rowid_" 
115409   **        and there is no explicitly declared IPK column. 
115410   **
115411   **     2. The table is not a view and the column name identified an 
115412   **        explicitly declared column. Copy meta information from *pCol.
115413   */ 
115414   if( pCol ){
115415     zDataType = pCol->zType;
115416     zCollSeq = pCol->zColl;
115417     notnull = pCol->notNull!=0;
115418     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
115419     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
115420   }else{
115421     zDataType = "INTEGER";
115422     primarykey = 1;
115423   }
115424   if( !zCollSeq ){
115425     zCollSeq = "BINARY";
115426   }
115427
115428 error_out:
115429   sqlite3BtreeLeaveAll(db);
115430
115431   /* Whether the function call succeeded or failed, set the output parameters
115432   ** to whatever their local counterparts contain. If an error did occur,
115433   ** this has the effect of zeroing all output parameters.
115434   */
115435   if( pzDataType ) *pzDataType = zDataType;
115436   if( pzCollSeq ) *pzCollSeq = zCollSeq;
115437   if( pNotNull ) *pNotNull = notnull;
115438   if( pPrimaryKey ) *pPrimaryKey = primarykey;
115439   if( pAutoinc ) *pAutoinc = autoinc;
115440
115441   if( SQLITE_OK==rc && !pTab ){
115442     sqlite3DbFree(db, zErrMsg);
115443     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
115444         zColumnName);
115445     rc = SQLITE_ERROR;
115446   }
115447   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
115448   sqlite3DbFree(db, zErrMsg);
115449   rc = sqlite3ApiExit(db, rc);
115450   sqlite3_mutex_leave(db->mutex);
115451   return rc;
115452 }
115453 #endif
115454
115455 /*
115456 ** Sleep for a little while.  Return the amount of time slept.
115457 */
115458 SQLITE_API int sqlite3_sleep(int ms){
115459   sqlite3_vfs *pVfs;
115460   int rc;
115461   pVfs = sqlite3_vfs_find(0);
115462   if( pVfs==0 ) return 0;
115463
115464   /* This function works in milliseconds, but the underlying OsSleep() 
115465   ** API uses microseconds. Hence the 1000's.
115466   */
115467   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
115468   return rc;
115469 }
115470
115471 /*
115472 ** Enable or disable the extended result codes.
115473 */
115474 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
115475   sqlite3_mutex_enter(db->mutex);
115476   db->errMask = onoff ? 0xffffffff : 0xff;
115477   sqlite3_mutex_leave(db->mutex);
115478   return SQLITE_OK;
115479 }
115480
115481 /*
115482 ** Invoke the xFileControl method on a particular database.
115483 */
115484 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
115485   int rc = SQLITE_ERROR;
115486   Btree *pBtree;
115487
115488   sqlite3_mutex_enter(db->mutex);
115489   pBtree = sqlite3DbNameToBtree(db, zDbName);
115490   if( pBtree ){
115491     Pager *pPager;
115492     sqlite3_file *fd;
115493     sqlite3BtreeEnter(pBtree);
115494     pPager = sqlite3BtreePager(pBtree);
115495     assert( pPager!=0 );
115496     fd = sqlite3PagerFile(pPager);
115497     assert( fd!=0 );
115498     if( op==SQLITE_FCNTL_FILE_POINTER ){
115499       *(sqlite3_file**)pArg = fd;
115500       rc = SQLITE_OK;
115501     }else if( fd->pMethods ){
115502       rc = sqlite3OsFileControl(fd, op, pArg);
115503     }else{
115504       rc = SQLITE_NOTFOUND;
115505     }
115506     sqlite3BtreeLeave(pBtree);
115507   }
115508   sqlite3_mutex_leave(db->mutex);
115509   return rc;   
115510 }
115511
115512 /*
115513 ** Interface to the testing logic.
115514 */
115515 SQLITE_API int sqlite3_test_control(int op, ...){
115516   int rc = 0;
115517 #ifndef SQLITE_OMIT_BUILTIN_TEST
115518   va_list ap;
115519   va_start(ap, op);
115520   switch( op ){
115521
115522     /*
115523     ** Save the current state of the PRNG.
115524     */
115525     case SQLITE_TESTCTRL_PRNG_SAVE: {
115526       sqlite3PrngSaveState();
115527       break;
115528     }
115529
115530     /*
115531     ** Restore the state of the PRNG to the last state saved using
115532     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
115533     ** this verb acts like PRNG_RESET.
115534     */
115535     case SQLITE_TESTCTRL_PRNG_RESTORE: {
115536       sqlite3PrngRestoreState();
115537       break;
115538     }
115539
115540     /*
115541     ** Reset the PRNG back to its uninitialized state.  The next call
115542     ** to sqlite3_randomness() will reseed the PRNG using a single call
115543     ** to the xRandomness method of the default VFS.
115544     */
115545     case SQLITE_TESTCTRL_PRNG_RESET: {
115546       sqlite3PrngResetState();
115547       break;
115548     }
115549
115550     /*
115551     **  sqlite3_test_control(BITVEC_TEST, size, program)
115552     **
115553     ** Run a test against a Bitvec object of size.  The program argument
115554     ** is an array of integers that defines the test.  Return -1 on a
115555     ** memory allocation error, 0 on success, or non-zero for an error.
115556     ** See the sqlite3BitvecBuiltinTest() for additional information.
115557     */
115558     case SQLITE_TESTCTRL_BITVEC_TEST: {
115559       int sz = va_arg(ap, int);
115560       int *aProg = va_arg(ap, int*);
115561       rc = sqlite3BitvecBuiltinTest(sz, aProg);
115562       break;
115563     }
115564
115565     /*
115566     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
115567     **
115568     ** Register hooks to call to indicate which malloc() failures 
115569     ** are benign.
115570     */
115571     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
115572       typedef void (*void_function)(void);
115573       void_function xBenignBegin;
115574       void_function xBenignEnd;
115575       xBenignBegin = va_arg(ap, void_function);
115576       xBenignEnd = va_arg(ap, void_function);
115577       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
115578       break;
115579     }
115580
115581     /*
115582     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
115583     **
115584     ** Set the PENDING byte to the value in the argument, if X>0.
115585     ** Make no changes if X==0.  Return the value of the pending byte
115586     ** as it existing before this routine was called.
115587     **
115588     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
115589     ** an incompatible database file format.  Changing the PENDING byte
115590     ** while any database connection is open results in undefined and
115591     ** dileterious behavior.
115592     */
115593     case SQLITE_TESTCTRL_PENDING_BYTE: {
115594       rc = PENDING_BYTE;
115595 #ifndef SQLITE_OMIT_WSD
115596       {
115597         unsigned int newVal = va_arg(ap, unsigned int);
115598         if( newVal ) sqlite3PendingByte = newVal;
115599       }
115600 #endif
115601       break;
115602     }
115603
115604     /*
115605     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
115606     **
115607     ** This action provides a run-time test to see whether or not
115608     ** assert() was enabled at compile-time.  If X is true and assert()
115609     ** is enabled, then the return value is true.  If X is true and
115610     ** assert() is disabled, then the return value is zero.  If X is
115611     ** false and assert() is enabled, then the assertion fires and the
115612     ** process aborts.  If X is false and assert() is disabled, then the
115613     ** return value is zero.
115614     */
115615     case SQLITE_TESTCTRL_ASSERT: {
115616       volatile int x = 0;
115617       assert( (x = va_arg(ap,int))!=0 );
115618       rc = x;
115619       break;
115620     }
115621
115622
115623     /*
115624     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
115625     **
115626     ** This action provides a run-time test to see how the ALWAYS and
115627     ** NEVER macros were defined at compile-time.
115628     **
115629     ** The return value is ALWAYS(X).  
115630     **
115631     ** The recommended test is X==2.  If the return value is 2, that means
115632     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
115633     ** default setting.  If the return value is 1, then ALWAYS() is either
115634     ** hard-coded to true or else it asserts if its argument is false.
115635     ** The first behavior (hard-coded to true) is the case if
115636     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
115637     ** behavior (assert if the argument to ALWAYS() is false) is the case if
115638     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
115639     **
115640     ** The run-time test procedure might look something like this:
115641     **
115642     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
115643     **      // ALWAYS() and NEVER() are no-op pass-through macros
115644     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
115645     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
115646     **    }else{
115647     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
115648     **    }
115649     */
115650     case SQLITE_TESTCTRL_ALWAYS: {
115651       int x = va_arg(ap,int);
115652       rc = ALWAYS(x);
115653       break;
115654     }
115655
115656     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
115657     **
115658     ** Set the nReserve size to N for the main database on the database
115659     ** connection db.
115660     */
115661     case SQLITE_TESTCTRL_RESERVE: {
115662       sqlite3 *db = va_arg(ap, sqlite3*);
115663       int x = va_arg(ap,int);
115664       sqlite3_mutex_enter(db->mutex);
115665       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
115666       sqlite3_mutex_leave(db->mutex);
115667       break;
115668     }
115669
115670     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
115671     **
115672     ** Enable or disable various optimizations for testing purposes.  The 
115673     ** argument N is a bitmask of optimizations to be disabled.  For normal
115674     ** operation N should be 0.  The idea is that a test program (like the
115675     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
115676     ** with various optimizations disabled to verify that the same answer
115677     ** is obtained in every case.
115678     */
115679     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
115680       sqlite3 *db = va_arg(ap, sqlite3*);
115681       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
115682       break;
115683     }
115684
115685 #ifdef SQLITE_N_KEYWORD
115686     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
115687     **
115688     ** If zWord is a keyword recognized by the parser, then return the
115689     ** number of keywords.  Or if zWord is not a keyword, return 0.
115690     ** 
115691     ** This test feature is only available in the amalgamation since
115692     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
115693     ** is built using separate source files.
115694     */
115695     case SQLITE_TESTCTRL_ISKEYWORD: {
115696       const char *zWord = va_arg(ap, const char*);
115697       int n = sqlite3Strlen30(zWord);
115698       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
115699       break;
115700     }
115701 #endif 
115702
115703     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
115704     **
115705     ** Pass pFree into sqlite3ScratchFree(). 
115706     ** If sz>0 then allocate a scratch buffer into pNew.  
115707     */
115708     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
115709       void *pFree, **ppNew;
115710       int sz;
115711       sz = va_arg(ap, int);
115712       ppNew = va_arg(ap, void**);
115713       pFree = va_arg(ap, void*);
115714       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
115715       sqlite3ScratchFree(pFree);
115716       break;
115717     }
115718
115719     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
115720     **
115721     ** If parameter onoff is non-zero, configure the wrappers so that all
115722     ** subsequent calls to localtime() and variants fail. If onoff is zero,
115723     ** undo this setting.
115724     */
115725     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
115726       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
115727       break;
115728     }
115729
115730 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
115731     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
115732     **                        sqlite3_stmt*,const char**);
115733     **
115734     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
115735     ** a string that describes the optimized parse tree.  This test-control
115736     ** returns a pointer to that string.
115737     */
115738     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
115739       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
115740       const char **pzRet = va_arg(ap, const char**);
115741       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
115742       break;
115743     }
115744 #endif
115745
115746   }
115747   va_end(ap);
115748 #endif /* SQLITE_OMIT_BUILTIN_TEST */
115749   return rc;
115750 }
115751
115752 /*
115753 ** This is a utility routine, useful to VFS implementations, that checks
115754 ** to see if a database file was a URI that contained a specific query 
115755 ** parameter, and if so obtains the value of the query parameter.
115756 **
115757 ** The zFilename argument is the filename pointer passed into the xOpen()
115758 ** method of a VFS implementation.  The zParam argument is the name of the
115759 ** query parameter we seek.  This routine returns the value of the zParam
115760 ** parameter if it exists.  If the parameter does not exist, this routine
115761 ** returns a NULL pointer.
115762 */
115763 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
115764   if( zFilename==0 ) return 0;
115765   zFilename += sqlite3Strlen30(zFilename) + 1;
115766   while( zFilename[0] ){
115767     int x = strcmp(zFilename, zParam);
115768     zFilename += sqlite3Strlen30(zFilename) + 1;
115769     if( x==0 ) return zFilename;
115770     zFilename += sqlite3Strlen30(zFilename) + 1;
115771   }
115772   return 0;
115773 }
115774
115775 /*
115776 ** Return a boolean value for a query parameter.
115777 */
115778 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
115779   const char *z = sqlite3_uri_parameter(zFilename, zParam);
115780   bDflt = bDflt!=0;
115781   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
115782 }
115783
115784 /*
115785 ** Return a 64-bit integer value for a query parameter.
115786 */
115787 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
115788   const char *zFilename,    /* Filename as passed to xOpen */
115789   const char *zParam,       /* URI parameter sought */
115790   sqlite3_int64 bDflt       /* return if parameter is missing */
115791 ){
115792   const char *z = sqlite3_uri_parameter(zFilename, zParam);
115793   sqlite3_int64 v;
115794   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
115795     bDflt = v;
115796   }
115797   return bDflt;
115798 }
115799
115800 /*
115801 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
115802 */
115803 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
115804   int i;
115805   for(i=0; i<db->nDb; i++){
115806     if( db->aDb[i].pBt
115807      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
115808     ){
115809       return db->aDb[i].pBt;
115810     }
115811   }
115812   return 0;
115813 }
115814
115815 /*
115816 ** Return the filename of the database associated with a database
115817 ** connection.
115818 */
115819 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
115820   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115821   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
115822 }
115823
115824 /*
115825 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
115826 ** no such database exists.
115827 */
115828 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
115829   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115830   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
115831 }
115832
115833 /************** End of main.c ************************************************/
115834 /************** Begin file notify.c ******************************************/
115835 /*
115836 ** 2009 March 3
115837 **
115838 ** The author disclaims copyright to this source code.  In place of
115839 ** a legal notice, here is a blessing:
115840 **
115841 **    May you do good and not evil.
115842 **    May you find forgiveness for yourself and forgive others.
115843 **    May you share freely, never taking more than you give.
115844 **
115845 *************************************************************************
115846 **
115847 ** This file contains the implementation of the sqlite3_unlock_notify()
115848 ** API method and its associated functionality.
115849 */
115850
115851 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
115852 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
115853
115854 /*
115855 ** Public interfaces:
115856 **
115857 **   sqlite3ConnectionBlocked()
115858 **   sqlite3ConnectionUnlocked()
115859 **   sqlite3ConnectionClosed()
115860 **   sqlite3_unlock_notify()
115861 */
115862
115863 #define assertMutexHeld() \
115864   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
115865
115866 /*
115867 ** Head of a linked list of all sqlite3 objects created by this process
115868 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
115869 ** is not NULL. This variable may only accessed while the STATIC_MASTER
115870 ** mutex is held.
115871 */
115872 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
115873
115874 #ifndef NDEBUG
115875 /*
115876 ** This function is a complex assert() that verifies the following 
115877 ** properties of the blocked connections list:
115878 **
115879 **   1) Each entry in the list has a non-NULL value for either 
115880 **      pUnlockConnection or pBlockingConnection, or both.
115881 **
115882 **   2) All entries in the list that share a common value for 
115883 **      xUnlockNotify are grouped together.
115884 **
115885 **   3) If the argument db is not NULL, then none of the entries in the
115886 **      blocked connections list have pUnlockConnection or pBlockingConnection
115887 **      set to db. This is used when closing connection db.
115888 */
115889 static void checkListProperties(sqlite3 *db){
115890   sqlite3 *p;
115891   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
115892     int seen = 0;
115893     sqlite3 *p2;
115894
115895     /* Verify property (1) */
115896     assert( p->pUnlockConnection || p->pBlockingConnection );
115897
115898     /* Verify property (2) */
115899     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
115900       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
115901       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
115902       assert( db==0 || p->pUnlockConnection!=db );
115903       assert( db==0 || p->pBlockingConnection!=db );
115904     }
115905   }
115906 }
115907 #else
115908 # define checkListProperties(x)
115909 #endif
115910
115911 /*
115912 ** Remove connection db from the blocked connections list. If connection
115913 ** db is not currently a part of the list, this function is a no-op.
115914 */
115915 static void removeFromBlockedList(sqlite3 *db){
115916   sqlite3 **pp;
115917   assertMutexHeld();
115918   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
115919     if( *pp==db ){
115920       *pp = (*pp)->pNextBlocked;
115921       break;
115922     }
115923   }
115924 }
115925
115926 /*
115927 ** Add connection db to the blocked connections list. It is assumed
115928 ** that it is not already a part of the list.
115929 */
115930 static void addToBlockedList(sqlite3 *db){
115931   sqlite3 **pp;
115932   assertMutexHeld();
115933   for(
115934     pp=&sqlite3BlockedList; 
115935     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
115936     pp=&(*pp)->pNextBlocked
115937   );
115938   db->pNextBlocked = *pp;
115939   *pp = db;
115940 }
115941
115942 /*
115943 ** Obtain the STATIC_MASTER mutex.
115944 */
115945 static void enterMutex(void){
115946   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115947   checkListProperties(0);
115948 }
115949
115950 /*
115951 ** Release the STATIC_MASTER mutex.
115952 */
115953 static void leaveMutex(void){
115954   assertMutexHeld();
115955   checkListProperties(0);
115956   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115957 }
115958
115959 /*
115960 ** Register an unlock-notify callback.
115961 **
115962 ** This is called after connection "db" has attempted some operation
115963 ** but has received an SQLITE_LOCKED error because another connection
115964 ** (call it pOther) in the same process was busy using the same shared
115965 ** cache.  pOther is found by looking at db->pBlockingConnection.
115966 **
115967 ** If there is no blocking connection, the callback is invoked immediately,
115968 ** before this routine returns.
115969 **
115970 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
115971 ** a deadlock.
115972 **
115973 ** Otherwise, make arrangements to invoke xNotify when pOther drops
115974 ** its locks.
115975 **
115976 ** Each call to this routine overrides any prior callbacks registered
115977 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
115978 ** cancelled.
115979 */
115980 SQLITE_API int sqlite3_unlock_notify(
115981   sqlite3 *db,
115982   void (*xNotify)(void **, int),
115983   void *pArg
115984 ){
115985   int rc = SQLITE_OK;
115986
115987   sqlite3_mutex_enter(db->mutex);
115988   enterMutex();
115989
115990   if( xNotify==0 ){
115991     removeFromBlockedList(db);
115992     db->pBlockingConnection = 0;
115993     db->pUnlockConnection = 0;
115994     db->xUnlockNotify = 0;
115995     db->pUnlockArg = 0;
115996   }else if( 0==db->pBlockingConnection ){
115997     /* The blocking transaction has been concluded. Or there never was a 
115998     ** blocking transaction. In either case, invoke the notify callback
115999     ** immediately. 
116000     */
116001     xNotify(&pArg, 1);
116002   }else{
116003     sqlite3 *p;
116004
116005     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
116006     if( p ){
116007       rc = SQLITE_LOCKED;              /* Deadlock detected. */
116008     }else{
116009       db->pUnlockConnection = db->pBlockingConnection;
116010       db->xUnlockNotify = xNotify;
116011       db->pUnlockArg = pArg;
116012       removeFromBlockedList(db);
116013       addToBlockedList(db);
116014     }
116015   }
116016
116017   leaveMutex();
116018   assert( !db->mallocFailed );
116019   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
116020   sqlite3_mutex_leave(db->mutex);
116021   return rc;
116022 }
116023
116024 /*
116025 ** This function is called while stepping or preparing a statement 
116026 ** associated with connection db. The operation will return SQLITE_LOCKED
116027 ** to the user because it requires a lock that will not be available
116028 ** until connection pBlocker concludes its current transaction.
116029 */
116030 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
116031   enterMutex();
116032   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
116033     addToBlockedList(db);
116034   }
116035   db->pBlockingConnection = pBlocker;
116036   leaveMutex();
116037 }
116038
116039 /*
116040 ** This function is called when
116041 ** the transaction opened by database db has just finished. Locks held 
116042 ** by database connection db have been released.
116043 **
116044 ** This function loops through each entry in the blocked connections
116045 ** list and does the following:
116046 **
116047 **   1) If the sqlite3.pBlockingConnection member of a list entry is
116048 **      set to db, then set pBlockingConnection=0.
116049 **
116050 **   2) If the sqlite3.pUnlockConnection member of a list entry is
116051 **      set to db, then invoke the configured unlock-notify callback and
116052 **      set pUnlockConnection=0.
116053 **
116054 **   3) If the two steps above mean that pBlockingConnection==0 and
116055 **      pUnlockConnection==0, remove the entry from the blocked connections
116056 **      list.
116057 */
116058 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
116059   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
116060   int nArg = 0;                            /* Number of entries in aArg[] */
116061   sqlite3 **pp;                            /* Iterator variable */
116062   void **aArg;               /* Arguments to the unlock callback */
116063   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
116064   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
116065
116066   aArg = aStatic;
116067   enterMutex();         /* Enter STATIC_MASTER mutex */
116068
116069   /* This loop runs once for each entry in the blocked-connections list. */
116070   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
116071     sqlite3 *p = *pp;
116072
116073     /* Step 1. */
116074     if( p->pBlockingConnection==db ){
116075       p->pBlockingConnection = 0;
116076     }
116077
116078     /* Step 2. */
116079     if( p->pUnlockConnection==db ){
116080       assert( p->xUnlockNotify );
116081       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
116082         xUnlockNotify(aArg, nArg);
116083         nArg = 0;
116084       }
116085
116086       sqlite3BeginBenignMalloc();
116087       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
116088       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
116089       if( (!aDyn && nArg==(int)ArraySize(aStatic))
116090        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
116091       ){
116092         /* The aArg[] array needs to grow. */
116093         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
116094         if( pNew ){
116095           memcpy(pNew, aArg, nArg*sizeof(void *));
116096           sqlite3_free(aDyn);
116097           aDyn = aArg = pNew;
116098         }else{
116099           /* This occurs when the array of context pointers that need to
116100           ** be passed to the unlock-notify callback is larger than the
116101           ** aStatic[] array allocated on the stack and the attempt to 
116102           ** allocate a larger array from the heap has failed.
116103           **
116104           ** This is a difficult situation to handle. Returning an error
116105           ** code to the caller is insufficient, as even if an error code
116106           ** is returned the transaction on connection db will still be
116107           ** closed and the unlock-notify callbacks on blocked connections
116108           ** will go unissued. This might cause the application to wait
116109           ** indefinitely for an unlock-notify callback that will never 
116110           ** arrive.
116111           **
116112           ** Instead, invoke the unlock-notify callback with the context
116113           ** array already accumulated. We can then clear the array and
116114           ** begin accumulating any further context pointers without 
116115           ** requiring any dynamic allocation. This is sub-optimal because
116116           ** it means that instead of one callback with a large array of
116117           ** context pointers the application will receive two or more
116118           ** callbacks with smaller arrays of context pointers, which will
116119           ** reduce the applications ability to prioritize multiple 
116120           ** connections. But it is the best that can be done under the
116121           ** circumstances.
116122           */
116123           xUnlockNotify(aArg, nArg);
116124           nArg = 0;
116125         }
116126       }
116127       sqlite3EndBenignMalloc();
116128
116129       aArg[nArg++] = p->pUnlockArg;
116130       xUnlockNotify = p->xUnlockNotify;
116131       p->pUnlockConnection = 0;
116132       p->xUnlockNotify = 0;
116133       p->pUnlockArg = 0;
116134     }
116135
116136     /* Step 3. */
116137     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
116138       /* Remove connection p from the blocked connections list. */
116139       *pp = p->pNextBlocked;
116140       p->pNextBlocked = 0;
116141     }else{
116142       pp = &p->pNextBlocked;
116143     }
116144   }
116145
116146   if( nArg!=0 ){
116147     xUnlockNotify(aArg, nArg);
116148   }
116149   sqlite3_free(aDyn);
116150   leaveMutex();         /* Leave STATIC_MASTER mutex */
116151 }
116152
116153 /*
116154 ** This is called when the database connection passed as an argument is 
116155 ** being closed. The connection is removed from the blocked list.
116156 */
116157 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
116158   sqlite3ConnectionUnlocked(db);
116159   enterMutex();
116160   removeFromBlockedList(db);
116161   checkListProperties(db);
116162   leaveMutex();
116163 }
116164 #endif
116165
116166 /************** End of notify.c **********************************************/
116167 /************** Begin file fts3.c ********************************************/
116168 /*
116169 ** 2006 Oct 10
116170 **
116171 ** The author disclaims copyright to this source code.  In place of
116172 ** a legal notice, here is a blessing:
116173 **
116174 **    May you do good and not evil.
116175 **    May you find forgiveness for yourself and forgive others.
116176 **    May you share freely, never taking more than you give.
116177 **
116178 ******************************************************************************
116179 **
116180 ** This is an SQLite module implementing full-text search.
116181 */
116182
116183 /*
116184 ** The code in this file is only compiled if:
116185 **
116186 **     * The FTS3 module is being built as an extension
116187 **       (in which case SQLITE_CORE is not defined), or
116188 **
116189 **     * The FTS3 module is being built into the core of
116190 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116191 */
116192
116193 /* The full-text index is stored in a series of b+tree (-like)
116194 ** structures called segments which map terms to doclists.  The
116195 ** structures are like b+trees in layout, but are constructed from the
116196 ** bottom up in optimal fashion and are not updatable.  Since trees
116197 ** are built from the bottom up, things will be described from the
116198 ** bottom up.
116199 **
116200 **
116201 **** Varints ****
116202 ** The basic unit of encoding is a variable-length integer called a
116203 ** varint.  We encode variable-length integers in little-endian order
116204 ** using seven bits * per byte as follows:
116205 **
116206 ** KEY:
116207 **         A = 0xxxxxxx    7 bits of data and one flag bit
116208 **         B = 1xxxxxxx    7 bits of data and one flag bit
116209 **
116210 **  7 bits - A
116211 ** 14 bits - BA
116212 ** 21 bits - BBA
116213 ** and so on.
116214 **
116215 ** This is similar in concept to how sqlite encodes "varints" but
116216 ** the encoding is not the same.  SQLite varints are big-endian
116217 ** are are limited to 9 bytes in length whereas FTS3 varints are
116218 ** little-endian and can be up to 10 bytes in length (in theory).
116219 **
116220 ** Example encodings:
116221 **
116222 **     1:    0x01
116223 **   127:    0x7f
116224 **   128:    0x81 0x00
116225 **
116226 **
116227 **** Document lists ****
116228 ** A doclist (document list) holds a docid-sorted list of hits for a
116229 ** given term.  Doclists hold docids and associated token positions.
116230 ** A docid is the unique integer identifier for a single document.
116231 ** A position is the index of a word within the document.  The first 
116232 ** word of the document has a position of 0.
116233 **
116234 ** FTS3 used to optionally store character offsets using a compile-time
116235 ** option.  But that functionality is no longer supported.
116236 **
116237 ** A doclist is stored like this:
116238 **
116239 ** array {
116240 **   varint docid;          (delta from previous doclist)
116241 **   array {                (position list for column 0)
116242 **     varint position;     (2 more than the delta from previous position)
116243 **   }
116244 **   array {
116245 **     varint POS_COLUMN;   (marks start of position list for new column)
116246 **     varint column;       (index of new column)
116247 **     array {
116248 **       varint position;   (2 more than the delta from previous position)
116249 **     }
116250 **   }
116251 **   varint POS_END;        (marks end of positions for this document.
116252 ** }
116253 **
116254 ** Here, array { X } means zero or more occurrences of X, adjacent in
116255 ** memory.  A "position" is an index of a token in the token stream
116256 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
116257 ** in the same logical place as the position element, and act as sentinals
116258 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
116259 ** The positions numbers are not stored literally but rather as two more
116260 ** than the difference from the prior position, or the just the position plus
116261 ** 2 for the first position.  Example:
116262 **
116263 **   label:       A B C D E  F  G H   I  J K
116264 **   value:     123 5 9 1 1 14 35 0 234 72 0
116265 **
116266 ** The 123 value is the first docid.  For column zero in this document
116267 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
116268 ** at D signals the start of a new column; the 1 at E indicates that the
116269 ** new column is column number 1.  There are two positions at 12 and 45
116270 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
116271 ** 234 at I is the delta to next docid (357).  It has one position 70
116272 ** (72-2) and then terminates with the 0 at K.
116273 **
116274 ** A "position-list" is the list of positions for multiple columns for
116275 ** a single docid.  A "column-list" is the set of positions for a single
116276 ** column.  Hence, a position-list consists of one or more column-lists,
116277 ** a document record consists of a docid followed by a position-list and
116278 ** a doclist consists of one or more document records.
116279 **
116280 ** A bare doclist omits the position information, becoming an 
116281 ** array of varint-encoded docids.
116282 **
116283 **** Segment leaf nodes ****
116284 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
116285 ** nodes are written using LeafWriter, and read using LeafReader (to
116286 ** iterate through a single leaf node's data) and LeavesReader (to
116287 ** iterate through a segment's entire leaf layer).  Leaf nodes have
116288 ** the format:
116289 **
116290 ** varint iHeight;             (height from leaf level, always 0)
116291 ** varint nTerm;               (length of first term)
116292 ** char pTerm[nTerm];          (content of first term)
116293 ** varint nDoclist;            (length of term's associated doclist)
116294 ** char pDoclist[nDoclist];    (content of doclist)
116295 ** array {
116296 **                             (further terms are delta-encoded)
116297 **   varint nPrefix;           (length of prefix shared with previous term)
116298 **   varint nSuffix;           (length of unshared suffix)
116299 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
116300 **   varint nDoclist;          (length of term's associated doclist)
116301 **   char pDoclist[nDoclist];  (content of doclist)
116302 ** }
116303 **
116304 ** Here, array { X } means zero or more occurrences of X, adjacent in
116305 ** memory.
116306 **
116307 ** Leaf nodes are broken into blocks which are stored contiguously in
116308 ** the %_segments table in sorted order.  This means that when the end
116309 ** of a node is reached, the next term is in the node with the next
116310 ** greater node id.
116311 **
116312 ** New data is spilled to a new leaf node when the current node
116313 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
116314 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
116315 ** node (a leaf node with a single term and doclist).  The goal of
116316 ** these settings is to pack together groups of small doclists while
116317 ** making it efficient to directly access large doclists.  The
116318 ** assumption is that large doclists represent terms which are more
116319 ** likely to be query targets.
116320 **
116321 ** TODO(shess) It may be useful for blocking decisions to be more
116322 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
116323 ** node rather than splitting into 2k and .5k nodes.  My intuition is
116324 ** that this might extend through 2x or 4x the pagesize.
116325 **
116326 **
116327 **** Segment interior nodes ****
116328 ** Segment interior nodes store blockids for subtree nodes and terms
116329 ** to describe what data is stored by the each subtree.  Interior
116330 ** nodes are written using InteriorWriter, and read using
116331 ** InteriorReader.  InteriorWriters are created as needed when
116332 ** SegmentWriter creates new leaf nodes, or when an interior node
116333 ** itself grows too big and must be split.  The format of interior
116334 ** nodes:
116335 **
116336 ** varint iHeight;           (height from leaf level, always >0)
116337 ** varint iBlockid;          (block id of node's leftmost subtree)
116338 ** optional {
116339 **   varint nTerm;           (length of first term)
116340 **   char pTerm[nTerm];      (content of first term)
116341 **   array {
116342 **                                (further terms are delta-encoded)
116343 **     varint nPrefix;            (length of shared prefix with previous term)
116344 **     varint nSuffix;            (length of unshared suffix)
116345 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
116346 **   }
116347 ** }
116348 **
116349 ** Here, optional { X } means an optional element, while array { X }
116350 ** means zero or more occurrences of X, adjacent in memory.
116351 **
116352 ** An interior node encodes n terms separating n+1 subtrees.  The
116353 ** subtree blocks are contiguous, so only the first subtree's blockid
116354 ** is encoded.  The subtree at iBlockid will contain all terms less
116355 ** than the first term encoded (or all terms if no term is encoded).
116356 ** Otherwise, for terms greater than or equal to pTerm[i] but less
116357 ** than pTerm[i+1], the subtree for that term will be rooted at
116358 ** iBlockid+i.  Interior nodes only store enough term data to
116359 ** distinguish adjacent children (if the rightmost term of the left
116360 ** child is "something", and the leftmost term of the right child is
116361 ** "wicked", only "w" is stored).
116362 **
116363 ** New data is spilled to a new interior node at the same height when
116364 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
116365 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
116366 ** interior nodes and making the tree too skinny.  The interior nodes
116367 ** at a given height are naturally tracked by interior nodes at
116368 ** height+1, and so on.
116369 **
116370 **
116371 **** Segment directory ****
116372 ** The segment directory in table %_segdir stores meta-information for
116373 ** merging and deleting segments, and also the root node of the
116374 ** segment's tree.
116375 **
116376 ** The root node is the top node of the segment's tree after encoding
116377 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
116378 ** This could be either a leaf node or an interior node.  If the top
116379 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
116380 ** and a new root interior node is generated (which should always fit
116381 ** within ROOT_MAX because it only needs space for 2 varints, the
116382 ** height and the blockid of the previous root).
116383 **
116384 ** The meta-information in the segment directory is:
116385 **   level               - segment level (see below)
116386 **   idx                 - index within level
116387 **                       - (level,idx uniquely identify a segment)
116388 **   start_block         - first leaf node
116389 **   leaves_end_block    - last leaf node
116390 **   end_block           - last block (including interior nodes)
116391 **   root                - contents of root node
116392 **
116393 ** If the root node is a leaf node, then start_block,
116394 ** leaves_end_block, and end_block are all 0.
116395 **
116396 **
116397 **** Segment merging ****
116398 ** To amortize update costs, segments are grouped into levels and
116399 ** merged in batches.  Each increase in level represents exponentially
116400 ** more documents.
116401 **
116402 ** New documents (actually, document updates) are tokenized and
116403 ** written individually (using LeafWriter) to a level 0 segment, with
116404 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
116405 ** level 0 segments are merged into a single level 1 segment.  Level 1
116406 ** is populated like level 0, and eventually MERGE_COUNT level 1
116407 ** segments are merged to a single level 2 segment (representing
116408 ** MERGE_COUNT^2 updates), and so on.
116409 **
116410 ** A segment merge traverses all segments at a given level in
116411 ** parallel, performing a straightforward sorted merge.  Since segment
116412 ** leaf nodes are written in to the %_segments table in order, this
116413 ** merge traverses the underlying sqlite disk structures efficiently.
116414 ** After the merge, all segment blocks from the merged level are
116415 ** deleted.
116416 **
116417 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
116418 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
116419 ** very similar performance numbers to 16 on insertion, though they're
116420 ** a tiny bit slower (perhaps due to more overhead in merge-time
116421 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
116422 ** 16, 2 about 66% slower than 16.
116423 **
116424 ** At query time, high MERGE_COUNT increases the number of segments
116425 ** which need to be scanned and merged.  For instance, with 100k docs
116426 ** inserted:
116427 **
116428 **    MERGE_COUNT   segments
116429 **       16           25
116430 **        8           12
116431 **        4           10
116432 **        2            6
116433 **
116434 ** This appears to have only a moderate impact on queries for very
116435 ** frequent terms (which are somewhat dominated by segment merge
116436 ** costs), and infrequent and non-existent terms still seem to be fast
116437 ** even with many segments.
116438 **
116439 ** TODO(shess) That said, it would be nice to have a better query-side
116440 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
116441 ** optimizations to things like doclist merging will swing the sweet
116442 ** spot around.
116443 **
116444 **
116445 **
116446 **** Handling of deletions and updates ****
116447 ** Since we're using a segmented structure, with no docid-oriented
116448 ** index into the term index, we clearly cannot simply update the term
116449 ** index when a document is deleted or updated.  For deletions, we
116450 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
116451 ** we simply write the new doclist.  Segment merges overwrite older
116452 ** data for a particular docid with newer data, so deletes or updates
116453 ** will eventually overtake the earlier data and knock it out.  The
116454 ** query logic likewise merges doclists so that newer data knocks out
116455 ** older data.
116456 */
116457
116458 /************** Include fts3Int.h in the middle of fts3.c ********************/
116459 /************** Begin file fts3Int.h *****************************************/
116460 /*
116461 ** 2009 Nov 12
116462 **
116463 ** The author disclaims copyright to this source code.  In place of
116464 ** a legal notice, here is a blessing:
116465 **
116466 **    May you do good and not evil.
116467 **    May you find forgiveness for yourself and forgive others.
116468 **    May you share freely, never taking more than you give.
116469 **
116470 ******************************************************************************
116471 **
116472 */
116473 #ifndef _FTSINT_H
116474 #define _FTSINT_H
116475
116476 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
116477 # define NDEBUG 1
116478 #endif
116479
116480 /*
116481 ** FTS4 is really an extension for FTS3.  It is enabled using the
116482 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
116483 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
116484 */
116485 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
116486 # define SQLITE_ENABLE_FTS3
116487 #endif
116488
116489 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116490
116491 /* If not building as part of the core, include sqlite3ext.h. */
116492 #ifndef SQLITE_CORE
116493 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
116494 #endif
116495
116496 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
116497 /************** Begin file fts3_tokenizer.h **********************************/
116498 /*
116499 ** 2006 July 10
116500 **
116501 ** The author disclaims copyright to this source code.
116502 **
116503 *************************************************************************
116504 ** Defines the interface to tokenizers used by fulltext-search.  There
116505 ** are three basic components:
116506 **
116507 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
116508 ** interface functions.  This is essentially the class structure for
116509 ** tokenizers.
116510 **
116511 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
116512 ** including customization information defined at creation time.
116513 **
116514 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
116515 ** tokens from a particular input.
116516 */
116517 #ifndef _FTS3_TOKENIZER_H_
116518 #define _FTS3_TOKENIZER_H_
116519
116520 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
116521 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
116522 ** we will need a way to register the API consistently.
116523 */
116524
116525 /*
116526 ** Structures used by the tokenizer interface. When a new tokenizer
116527 ** implementation is registered, the caller provides a pointer to
116528 ** an sqlite3_tokenizer_module containing pointers to the callback
116529 ** functions that make up an implementation.
116530 **
116531 ** When an fts3 table is created, it passes any arguments passed to
116532 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
116533 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
116534 ** implementation. The xCreate() function in turn returns an 
116535 ** sqlite3_tokenizer structure representing the specific tokenizer to
116536 ** be used for the fts3 table (customized by the tokenizer clause arguments).
116537 **
116538 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
116539 ** method is called. It returns an sqlite3_tokenizer_cursor object
116540 ** that may be used to tokenize a specific input buffer based on
116541 ** the tokenization rules supplied by a specific sqlite3_tokenizer
116542 ** object.
116543 */
116544 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
116545 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
116546 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
116547
116548 struct sqlite3_tokenizer_module {
116549
116550   /*
116551   ** Structure version. Should always be set to 0 or 1.
116552   */
116553   int iVersion;
116554
116555   /*
116556   ** Create a new tokenizer. The values in the argv[] array are the
116557   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
116558   ** TABLE statement that created the fts3 table. For example, if
116559   ** the following SQL is executed:
116560   **
116561   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
116562   **
116563   ** then argc is set to 2, and the argv[] array contains pointers
116564   ** to the strings "arg1" and "arg2".
116565   **
116566   ** This method should return either SQLITE_OK (0), or an SQLite error 
116567   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
116568   ** to point at the newly created tokenizer structure. The generic
116569   ** sqlite3_tokenizer.pModule variable should not be initialised by
116570   ** this callback. The caller will do so.
116571   */
116572   int (*xCreate)(
116573     int argc,                           /* Size of argv array */
116574     const char *const*argv,             /* Tokenizer argument strings */
116575     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
116576   );
116577
116578   /*
116579   ** Destroy an existing tokenizer. The fts3 module calls this method
116580   ** exactly once for each successful call to xCreate().
116581   */
116582   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
116583
116584   /*
116585   ** Create a tokenizer cursor to tokenize an input buffer. The caller
116586   ** is responsible for ensuring that the input buffer remains valid
116587   ** until the cursor is closed (using the xClose() method). 
116588   */
116589   int (*xOpen)(
116590     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
116591     const char *pInput, int nBytes,      /* Input buffer */
116592     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
116593   );
116594
116595   /*
116596   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
116597   ** method exactly once for each successful call to xOpen().
116598   */
116599   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
116600
116601   /*
116602   ** Retrieve the next token from the tokenizer cursor pCursor. This
116603   ** method should either return SQLITE_OK and set the values of the
116604   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
116605   ** the end of the buffer has been reached, or an SQLite error code.
116606   **
116607   ** *ppToken should be set to point at a buffer containing the 
116608   ** normalized version of the token (i.e. after any case-folding and/or
116609   ** stemming has been performed). *pnBytes should be set to the length
116610   ** of this buffer in bytes. The input text that generated the token is
116611   ** identified by the byte offsets returned in *piStartOffset and
116612   ** *piEndOffset. *piStartOffset should be set to the index of the first
116613   ** byte of the token in the input buffer. *piEndOffset should be set
116614   ** to the index of the first byte just past the end of the token in
116615   ** the input buffer.
116616   **
116617   ** The buffer *ppToken is set to point at is managed by the tokenizer
116618   ** implementation. It is only required to be valid until the next call
116619   ** to xNext() or xClose(). 
116620   */
116621   /* TODO(shess) current implementation requires pInput to be
116622   ** nul-terminated.  This should either be fixed, or pInput/nBytes
116623   ** should be converted to zInput.
116624   */
116625   int (*xNext)(
116626     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
116627     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
116628     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
116629     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
116630     int *piPosition      /* OUT: Number of tokens returned before this one */
116631   );
116632
116633   /***********************************************************************
116634   ** Methods below this point are only available if iVersion>=1.
116635   */
116636
116637   /* 
116638   ** Configure the language id of a tokenizer cursor.
116639   */
116640   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
116641 };
116642
116643 struct sqlite3_tokenizer {
116644   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
116645   /* Tokenizer implementations will typically add additional fields */
116646 };
116647
116648 struct sqlite3_tokenizer_cursor {
116649   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
116650   /* Tokenizer implementations will typically add additional fields */
116651 };
116652
116653 int fts3_global_term_cnt(int iTerm, int iCol);
116654 int fts3_term_cnt(int iTerm, int iCol);
116655
116656
116657 #endif /* _FTS3_TOKENIZER_H_ */
116658
116659 /************** End of fts3_tokenizer.h **************************************/
116660 /************** Continuing where we left off in fts3Int.h ********************/
116661 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
116662 /************** Begin file fts3_hash.h ***************************************/
116663 /*
116664 ** 2001 September 22
116665 **
116666 ** The author disclaims copyright to this source code.  In place of
116667 ** a legal notice, here is a blessing:
116668 **
116669 **    May you do good and not evil.
116670 **    May you find forgiveness for yourself and forgive others.
116671 **    May you share freely, never taking more than you give.
116672 **
116673 *************************************************************************
116674 ** This is the header file for the generic hash-table implemenation
116675 ** used in SQLite.  We've modified it slightly to serve as a standalone
116676 ** hash table implementation for the full-text indexing module.
116677 **
116678 */
116679 #ifndef _FTS3_HASH_H_
116680 #define _FTS3_HASH_H_
116681
116682 /* Forward declarations of structures. */
116683 typedef struct Fts3Hash Fts3Hash;
116684 typedef struct Fts3HashElem Fts3HashElem;
116685
116686 /* A complete hash table is an instance of the following structure.
116687 ** The internals of this structure are intended to be opaque -- client
116688 ** code should not attempt to access or modify the fields of this structure
116689 ** directly.  Change this structure only by using the routines below.
116690 ** However, many of the "procedures" and "functions" for modifying and
116691 ** accessing this structure are really macros, so we can't really make
116692 ** this structure opaque.
116693 */
116694 struct Fts3Hash {
116695   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
116696   char copyKey;           /* True if copy of key made on insert */
116697   int count;              /* Number of entries in this table */
116698   Fts3HashElem *first;    /* The first element of the array */
116699   int htsize;             /* Number of buckets in the hash table */
116700   struct _fts3ht {        /* the hash table */
116701     int count;               /* Number of entries with this hash */
116702     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
116703   } *ht;
116704 };
116705
116706 /* Each element in the hash table is an instance of the following 
116707 ** structure.  All elements are stored on a single doubly-linked list.
116708 **
116709 ** Again, this structure is intended to be opaque, but it can't really
116710 ** be opaque because it is used by macros.
116711 */
116712 struct Fts3HashElem {
116713   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
116714   void *data;                /* Data associated with this element */
116715   void *pKey; int nKey;      /* Key associated with this element */
116716 };
116717
116718 /*
116719 ** There are 2 different modes of operation for a hash table:
116720 **
116721 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
116722 **                           (including the null-terminator, if any).  Case
116723 **                           is respected in comparisons.
116724 **
116725 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
116726 **                           memcmp() is used to compare keys.
116727 **
116728 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
116729 */
116730 #define FTS3_HASH_STRING    1
116731 #define FTS3_HASH_BINARY    2
116732
116733 /*
116734 ** Access routines.  To delete, insert a NULL pointer.
116735 */
116736 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
116737 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
116738 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
116739 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
116740 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
116741
116742 /*
116743 ** Shorthand for the functions above
116744 */
116745 #define fts3HashInit     sqlite3Fts3HashInit
116746 #define fts3HashInsert   sqlite3Fts3HashInsert
116747 #define fts3HashFind     sqlite3Fts3HashFind
116748 #define fts3HashClear    sqlite3Fts3HashClear
116749 #define fts3HashFindElem sqlite3Fts3HashFindElem
116750
116751 /*
116752 ** Macros for looping over all elements of a hash table.  The idiom is
116753 ** like this:
116754 **
116755 **   Fts3Hash h;
116756 **   Fts3HashElem *p;
116757 **   ...
116758 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
116759 **     SomeStructure *pData = fts3HashData(p);
116760 **     // do something with pData
116761 **   }
116762 */
116763 #define fts3HashFirst(H)  ((H)->first)
116764 #define fts3HashNext(E)   ((E)->next)
116765 #define fts3HashData(E)   ((E)->data)
116766 #define fts3HashKey(E)    ((E)->pKey)
116767 #define fts3HashKeysize(E) ((E)->nKey)
116768
116769 /*
116770 ** Number of entries in a hash table
116771 */
116772 #define fts3HashCount(H)  ((H)->count)
116773
116774 #endif /* _FTS3_HASH_H_ */
116775
116776 /************** End of fts3_hash.h *******************************************/
116777 /************** Continuing where we left off in fts3Int.h ********************/
116778
116779 /*
116780 ** This constant controls how often segments are merged. Once there are
116781 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
116782 ** segment of level N+1.
116783 */
116784 #define FTS3_MERGE_COUNT 16
116785
116786 /*
116787 ** This is the maximum amount of data (in bytes) to store in the 
116788 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
116789 ** populated as documents are inserted/updated/deleted in a transaction
116790 ** and used to create a new segment when the transaction is committed.
116791 ** However if this limit is reached midway through a transaction, a new 
116792 ** segment is created and the hash table cleared immediately.
116793 */
116794 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
116795
116796 /*
116797 ** Macro to return the number of elements in an array. SQLite has a
116798 ** similar macro called ArraySize(). Use a different name to avoid
116799 ** a collision when building an amalgamation with built-in FTS3.
116800 */
116801 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
116802
116803
116804 #ifndef MIN
116805 # define MIN(x,y) ((x)<(y)?(x):(y))
116806 #endif
116807 #ifndef MAX
116808 # define MAX(x,y) ((x)>(y)?(x):(y))
116809 #endif
116810
116811 /*
116812 ** Maximum length of a varint encoded integer. The varint format is different
116813 ** from that used by SQLite, so the maximum length is 10, not 9.
116814 */
116815 #define FTS3_VARINT_MAX 10
116816
116817 /*
116818 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
116819 ** in the document set and zero or more prefix indexes. All indexes are stored
116820 ** as one or more b+-trees in the %_segments and %_segdir tables. 
116821 **
116822 ** It is possible to determine which index a b+-tree belongs to based on the
116823 ** value stored in the "%_segdir.level" column. Given this value L, the index
116824 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
116825 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
116826 ** between 1024 and 2047 to index 1, and so on.
116827 **
116828 ** It is considered impossible for an index to use more than 1024 levels. In 
116829 ** theory though this may happen, but only after at least 
116830 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
116831 */
116832 #define FTS3_SEGDIR_MAXLEVEL      1024
116833 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
116834
116835 /*
116836 ** The testcase() macro is only used by the amalgamation.  If undefined,
116837 ** make it a no-op.
116838 */
116839 #ifndef testcase
116840 # define testcase(X)
116841 #endif
116842
116843 /*
116844 ** Terminator values for position-lists and column-lists.
116845 */
116846 #define POS_COLUMN  (1)     /* Column-list terminator */
116847 #define POS_END     (0)     /* Position-list terminator */ 
116848
116849 /*
116850 ** This section provides definitions to allow the
116851 ** FTS3 extension to be compiled outside of the 
116852 ** amalgamation.
116853 */
116854 #ifndef SQLITE_AMALGAMATION
116855 /*
116856 ** Macros indicating that conditional expressions are always true or
116857 ** false.
116858 */
116859 #ifdef SQLITE_COVERAGE_TEST
116860 # define ALWAYS(x) (1)
116861 # define NEVER(X)  (0)
116862 #else
116863 # define ALWAYS(x) (x)
116864 # define NEVER(x)  (x)
116865 #endif
116866
116867 /*
116868 ** Internal types used by SQLite.
116869 */
116870 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
116871 typedef short int i16;            /* 2-byte (or larger) signed integer */
116872 typedef unsigned int u32;         /* 4-byte unsigned integer */
116873 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
116874 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
116875
116876 /*
116877 ** Macro used to suppress compiler warnings for unused parameters.
116878 */
116879 #define UNUSED_PARAMETER(x) (void)(x)
116880
116881 /*
116882 ** Activate assert() only if SQLITE_TEST is enabled.
116883 */
116884 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
116885 # define NDEBUG 1
116886 #endif
116887
116888 /*
116889 ** The TESTONLY macro is used to enclose variable declarations or
116890 ** other bits of code that are needed to support the arguments
116891 ** within testcase() and assert() macros.
116892 */
116893 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116894 # define TESTONLY(X)  X
116895 #else
116896 # define TESTONLY(X)
116897 #endif
116898
116899 #endif /* SQLITE_AMALGAMATION */
116900
116901 #ifdef SQLITE_DEBUG
116902 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
116903 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
116904 #else
116905 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
116906 #endif
116907
116908 typedef struct Fts3Table Fts3Table;
116909 typedef struct Fts3Cursor Fts3Cursor;
116910 typedef struct Fts3Expr Fts3Expr;
116911 typedef struct Fts3Phrase Fts3Phrase;
116912 typedef struct Fts3PhraseToken Fts3PhraseToken;
116913
116914 typedef struct Fts3Doclist Fts3Doclist;
116915 typedef struct Fts3SegFilter Fts3SegFilter;
116916 typedef struct Fts3DeferredToken Fts3DeferredToken;
116917 typedef struct Fts3SegReader Fts3SegReader;
116918 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
116919
116920 /*
116921 ** A connection to a fulltext index is an instance of the following
116922 ** structure. The xCreate and xConnect methods create an instance
116923 ** of this structure and xDestroy and xDisconnect free that instance.
116924 ** All other methods receive a pointer to the structure as one of their
116925 ** arguments.
116926 */
116927 struct Fts3Table {
116928   sqlite3_vtab base;              /* Base class used by SQLite core */
116929   sqlite3 *db;                    /* The database connection */
116930   const char *zDb;                /* logical database name */
116931   const char *zName;              /* virtual table name */
116932   int nColumn;                    /* number of named columns in virtual table */
116933   char **azColumn;                /* column names.  malloced */
116934   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
116935   char *zContentTbl;              /* content=xxx option, or NULL */
116936   char *zLanguageid;              /* languageid=xxx option, or NULL */
116937   u8 bAutoincrmerge;              /* True if automerge=1 */
116938   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
116939
116940   /* Precompiled statements used by the implementation. Each of these 
116941   ** statements is run and reset within a single virtual table API call. 
116942   */
116943   sqlite3_stmt *aStmt[37];
116944
116945   char *zReadExprlist;
116946   char *zWriteExprlist;
116947
116948   int nNodeSize;                  /* Soft limit for node size */
116949   u8 bFts4;                       /* True for FTS4, false for FTS3 */
116950   u8 bHasStat;                    /* True if %_stat table exists */
116951   u8 bHasDocsize;                 /* True if %_docsize table exists */
116952   u8 bDescIdx;                    /* True if doclists are in reverse order */
116953   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
116954   int nPgsz;                      /* Page size for host database */
116955   char *zSegmentsTbl;             /* Name of %_segments table */
116956   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
116957
116958   /* 
116959   ** The following array of hash tables is used to buffer pending index 
116960   ** updates during transactions. All pending updates buffered at any one
116961   ** time must share a common language-id (see the FTS4 langid= feature).
116962   ** The current language id is stored in variable iPrevLangid.
116963   **
116964   ** A single FTS4 table may have multiple full-text indexes. For each index
116965   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
116966   ** terms that appear in the document set. Each subsequent index in aIndex[]
116967   ** is an index of prefixes of a specific length.
116968   **
116969   ** Variable nPendingData contains an estimate the memory consumed by the 
116970   ** pending data structures, including hash table overhead, but not including
116971   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
116972   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
116973   ** recently inserted record.
116974   */
116975   int nIndex;                     /* Size of aIndex[] */
116976   struct Fts3Index {
116977     int nPrefix;                  /* Prefix length (0 for main terms index) */
116978     Fts3Hash hPending;            /* Pending terms table for this index */
116979   } *aIndex;
116980   int nMaxPendingData;            /* Max pending data before flush to disk */
116981   int nPendingData;               /* Current bytes of pending data */
116982   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
116983   int iPrevLangid;                /* Langid of recently inserted document */
116984
116985 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116986   /* State variables used for validating that the transaction control
116987   ** methods of the virtual table are called at appropriate times.  These
116988   ** values do not contribute to FTS functionality; they are used for
116989   ** verifying the operation of the SQLite core.
116990   */
116991   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
116992   int mxSavepoint;       /* Largest valid xSavepoint integer */
116993 #endif
116994 };
116995
116996 /*
116997 ** When the core wants to read from the virtual table, it creates a
116998 ** virtual table cursor (an instance of the following structure) using
116999 ** the xOpen method. Cursors are destroyed using the xClose method.
117000 */
117001 struct Fts3Cursor {
117002   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
117003   i16 eSearch;                    /* Search strategy (see below) */
117004   u8 isEof;                       /* True if at End Of Results */
117005   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
117006   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
117007   Fts3Expr *pExpr;                /* Parsed MATCH query string */
117008   int iLangid;                    /* Language being queried for */
117009   int nPhrase;                    /* Number of matchable phrases in query */
117010   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
117011   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
117012   char *pNextId;                  /* Pointer into the body of aDoclist */
117013   char *aDoclist;                 /* List of docids for full-text queries */
117014   int nDoclist;                   /* Size of buffer at aDoclist */
117015   u8 bDesc;                       /* True to sort in descending order */
117016   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
117017   int nRowAvg;                    /* Average size of database rows, in pages */
117018   sqlite3_int64 nDoc;             /* Documents in table */
117019
117020   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
117021   u32 *aMatchinfo;                /* Information about most recent match */
117022   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
117023   char *zMatchinfo;               /* Matchinfo specification */
117024 };
117025
117026 #define FTS3_EVAL_FILTER    0
117027 #define FTS3_EVAL_NEXT      1
117028 #define FTS3_EVAL_MATCHINFO 2
117029
117030 /*
117031 ** The Fts3Cursor.eSearch member is always set to one of the following.
117032 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
117033 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
117034 ** of the column to be searched.  For example, in
117035 **
117036 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
117037 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
117038 ** 
117039 ** Because the LHS of the MATCH operator is 2nd column "b",
117040 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
117041 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
117042 ** indicating that all columns should be searched,
117043 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
117044 */
117045 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
117046 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
117047 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
117048
117049
117050 struct Fts3Doclist {
117051   char *aAll;                    /* Array containing doclist (or NULL) */
117052   int nAll;                      /* Size of a[] in bytes */
117053   char *pNextDocid;              /* Pointer to next docid */
117054
117055   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
117056   int bFreeList;                 /* True if pList should be sqlite3_free()d */
117057   char *pList;                   /* Pointer to position list following iDocid */
117058   int nList;                     /* Length of position list */
117059 };
117060
117061 /*
117062 ** A "phrase" is a sequence of one or more tokens that must match in
117063 ** sequence.  A single token is the base case and the most common case.
117064 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
117065 ** nToken will be the number of tokens in the string.
117066 */
117067 struct Fts3PhraseToken {
117068   char *z;                        /* Text of the token */
117069   int n;                          /* Number of bytes in buffer z */
117070   int isPrefix;                   /* True if token ends with a "*" character */
117071   int bFirst;                     /* True if token must appear at position 0 */
117072
117073   /* Variables above this point are populated when the expression is
117074   ** parsed (by code in fts3_expr.c). Below this point the variables are
117075   ** used when evaluating the expression. */
117076   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
117077   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
117078 };
117079
117080 struct Fts3Phrase {
117081   /* Cache of doclist for this phrase. */
117082   Fts3Doclist doclist;
117083   int bIncr;                 /* True if doclist is loaded incrementally */
117084   int iDoclistToken;
117085
117086   /* Variables below this point are populated by fts3_expr.c when parsing 
117087   ** a MATCH expression. Everything above is part of the evaluation phase. 
117088   */
117089   int nToken;                /* Number of tokens in the phrase */
117090   int iColumn;               /* Index of column this phrase must match */
117091   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
117092 };
117093
117094 /*
117095 ** A tree of these objects forms the RHS of a MATCH operator.
117096 **
117097 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
117098 ** points to a malloced buffer, size nDoclist bytes, containing the results 
117099 ** of this phrase query in FTS3 doclist format. As usual, the initial 
117100 ** "Length" field found in doclists stored on disk is omitted from this 
117101 ** buffer.
117102 **
117103 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
117104 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
117105 ** where nCol is the number of columns in the queried FTS table. The array
117106 ** is populated as follows:
117107 **
117108 **   aMI[iCol*3 + 0] = Undefined
117109 **   aMI[iCol*3 + 1] = Number of occurrences
117110 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
117111 **
117112 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
117113 ** when the expression node is.
117114 */
117115 struct Fts3Expr {
117116   int eType;                 /* One of the FTSQUERY_XXX values defined below */
117117   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
117118   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
117119   Fts3Expr *pLeft;           /* Left operand */
117120   Fts3Expr *pRight;          /* Right operand */
117121   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
117122
117123   /* The following are used by the fts3_eval.c module. */
117124   sqlite3_int64 iDocid;      /* Current docid */
117125   u8 bEof;                   /* True this expression is at EOF already */
117126   u8 bStart;                 /* True if iDocid is valid */
117127   u8 bDeferred;              /* True if this expression is entirely deferred */
117128
117129   u32 *aMI;
117130 };
117131
117132 /*
117133 ** Candidate values for Fts3Query.eType. Note that the order of the first
117134 ** four values is in order of precedence when parsing expressions. For 
117135 ** example, the following:
117136 **
117137 **   "a OR b AND c NOT d NEAR e"
117138 **
117139 ** is equivalent to:
117140 **
117141 **   "a OR (b AND (c NOT (d NEAR e)))"
117142 */
117143 #define FTSQUERY_NEAR   1
117144 #define FTSQUERY_NOT    2
117145 #define FTSQUERY_AND    3
117146 #define FTSQUERY_OR     4
117147 #define FTSQUERY_PHRASE 5
117148
117149
117150 /* fts3_write.c */
117151 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
117152 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
117153 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
117154 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
117155 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
117156   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
117157 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
117158   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
117159 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
117160 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
117161 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
117162 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
117163
117164 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
117165 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
117166
117167 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
117168 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
117169 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
117170 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
117171 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
117172 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
117173 #else
117174 # define sqlite3Fts3FreeDeferredTokens(x)
117175 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
117176 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
117177 # define sqlite3Fts3FreeDeferredDoclists(x)
117178 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
117179 #endif
117180
117181 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
117182 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
117183
117184 /* Special values interpreted by sqlite3SegReaderCursor() */
117185 #define FTS3_SEGCURSOR_PENDING        -1
117186 #define FTS3_SEGCURSOR_ALL            -2
117187
117188 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
117189 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
117190 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
117191
117192 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
117193     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
117194
117195 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
117196 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
117197 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
117198 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
117199 #define FTS3_SEGMENT_PREFIX        0x00000008
117200 #define FTS3_SEGMENT_SCAN          0x00000010
117201 #define FTS3_SEGMENT_FIRST         0x00000020
117202
117203 /* Type passed as 4th argument to SegmentReaderIterate() */
117204 struct Fts3SegFilter {
117205   const char *zTerm;
117206   int nTerm;
117207   int iCol;
117208   int flags;
117209 };
117210
117211 struct Fts3MultiSegReader {
117212   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
117213   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
117214   int nSegment;                   /* Size of apSegment array */
117215   int nAdvance;                   /* How many seg-readers to advance */
117216   Fts3SegFilter *pFilter;         /* Pointer to filter object */
117217   char *aBuffer;                  /* Buffer to merge doclists in */
117218   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
117219
117220   int iColFilter;                 /* If >=0, filter for this column */
117221   int bRestart;
117222
117223   /* Used by fts3.c only. */
117224   int nCost;                      /* Cost of running iterator */
117225   int bLookup;                    /* True if a lookup of a single entry. */
117226
117227   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
117228   char *zTerm;                    /* Pointer to term buffer */
117229   int nTerm;                      /* Size of zTerm in bytes */
117230   char *aDoclist;                 /* Pointer to doclist buffer */
117231   int nDoclist;                   /* Size of aDoclist[] in bytes */
117232 };
117233
117234 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
117235
117236 /* fts3.c */
117237 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
117238 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
117239 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
117240 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
117241 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
117242 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
117243 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
117244 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
117245 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
117246
117247 /* fts3_tokenizer.c */
117248 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
117249 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
117250 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
117251     sqlite3_tokenizer **, char **
117252 );
117253 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
117254
117255 /* fts3_snippet.c */
117256 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
117257 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
117258   const char *, const char *, int, int
117259 );
117260 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
117261
117262 /* fts3_expr.c */
117263 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
117264   char **, int, int, int, const char *, int, Fts3Expr **
117265 );
117266 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
117267 #ifdef SQLITE_TEST
117268 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
117269 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
117270 #endif
117271
117272 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
117273   sqlite3_tokenizer_cursor **
117274 );
117275
117276 /* fts3_aux.c */
117277 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
117278
117279 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
117280
117281 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
117282     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
117283 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
117284     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
117285 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
117286 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
117287 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
117288
117289 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
117290 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
117291 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
117292 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
117293 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
117294 #endif
117295
117296 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
117297 #endif /* _FTSINT_H */
117298
117299 /************** End of fts3Int.h *********************************************/
117300 /************** Continuing where we left off in fts3.c ***********************/
117301 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117302
117303 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
117304 # define SQLITE_CORE 1
117305 #endif
117306
117307 /* #include <assert.h> */
117308 /* #include <stdlib.h> */
117309 /* #include <stddef.h> */
117310 /* #include <stdio.h> */
117311 /* #include <string.h> */
117312 /* #include <stdarg.h> */
117313
117314 #ifndef SQLITE_CORE 
117315   SQLITE_EXTENSION_INIT1
117316 #endif
117317
117318 static int fts3EvalNext(Fts3Cursor *pCsr);
117319 static int fts3EvalStart(Fts3Cursor *pCsr);
117320 static int fts3TermSegReaderCursor(
117321     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
117322
117323 /* 
117324 ** Write a 64-bit variable-length integer to memory starting at p[0].
117325 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
117326 ** The number of bytes written is returned.
117327 */
117328 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
117329   unsigned char *q = (unsigned char *) p;
117330   sqlite_uint64 vu = v;
117331   do{
117332     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
117333     vu >>= 7;
117334   }while( vu!=0 );
117335   q[-1] &= 0x7f;  /* turn off high bit in final byte */
117336   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
117337   return (int) (q - (unsigned char *)p);
117338 }
117339
117340 /* 
117341 ** Read a 64-bit variable-length integer from memory starting at p[0].
117342 ** Return the number of bytes read, or 0 on error.
117343 ** The value is stored in *v.
117344 */
117345 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
117346   const unsigned char *q = (const unsigned char *) p;
117347   sqlite_uint64 x = 0, y = 1;
117348   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
117349     x += y * (*q++ & 0x7f);
117350     y <<= 7;
117351   }
117352   x += y * (*q++);
117353   *v = (sqlite_int64) x;
117354   return (int) (q - (unsigned char *)p);
117355 }
117356
117357 /*
117358 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
117359 ** 32-bit integer before it is returned.
117360 */
117361 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
117362  sqlite_int64 i;
117363  int ret = sqlite3Fts3GetVarint(p, &i);
117364  *pi = (int) i;
117365  return ret;
117366 }
117367
117368 /*
117369 ** Return the number of bytes required to encode v as a varint
117370 */
117371 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
117372   int i = 0;
117373   do{
117374     i++;
117375     v >>= 7;
117376   }while( v!=0 );
117377   return i;
117378 }
117379
117380 /*
117381 ** Convert an SQL-style quoted string into a normal string by removing
117382 ** the quote characters.  The conversion is done in-place.  If the
117383 ** input does not begin with a quote character, then this routine
117384 ** is a no-op.
117385 **
117386 ** Examples:
117387 **
117388 **     "abc"   becomes   abc
117389 **     'xyz'   becomes   xyz
117390 **     [pqr]   becomes   pqr
117391 **     `mno`   becomes   mno
117392 **
117393 */
117394 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
117395   char quote;                     /* Quote character (if any ) */
117396
117397   quote = z[0];
117398   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
117399     int iIn = 1;                  /* Index of next byte to read from input */
117400     int iOut = 0;                 /* Index of next byte to write to output */
117401
117402     /* If the first byte was a '[', then the close-quote character is a ']' */
117403     if( quote=='[' ) quote = ']';  
117404
117405     while( ALWAYS(z[iIn]) ){
117406       if( z[iIn]==quote ){
117407         if( z[iIn+1]!=quote ) break;
117408         z[iOut++] = quote;
117409         iIn += 2;
117410       }else{
117411         z[iOut++] = z[iIn++];
117412       }
117413     }
117414     z[iOut] = '\0';
117415   }
117416 }
117417
117418 /*
117419 ** Read a single varint from the doclist at *pp and advance *pp to point
117420 ** to the first byte past the end of the varint.  Add the value of the varint
117421 ** to *pVal.
117422 */
117423 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
117424   sqlite3_int64 iVal;
117425   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
117426   *pVal += iVal;
117427 }
117428
117429 /*
117430 ** When this function is called, *pp points to the first byte following a
117431 ** varint that is part of a doclist (or position-list, or any other list
117432 ** of varints). This function moves *pp to point to the start of that varint,
117433 ** and sets *pVal by the varint value.
117434 **
117435 ** Argument pStart points to the first byte of the doclist that the
117436 ** varint is part of.
117437 */
117438 static void fts3GetReverseVarint(
117439   char **pp, 
117440   char *pStart, 
117441   sqlite3_int64 *pVal
117442 ){
117443   sqlite3_int64 iVal;
117444   char *p;
117445
117446   /* Pointer p now points at the first byte past the varint we are 
117447   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
117448   ** clear on character p[-1]. */
117449   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
117450   p++;
117451   *pp = p;
117452
117453   sqlite3Fts3GetVarint(p, &iVal);
117454   *pVal = iVal;
117455 }
117456
117457 /*
117458 ** The xDisconnect() virtual table method.
117459 */
117460 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
117461   Fts3Table *p = (Fts3Table *)pVtab;
117462   int i;
117463
117464   assert( p->nPendingData==0 );
117465   assert( p->pSegments==0 );
117466
117467   /* Free any prepared statements held */
117468   for(i=0; i<SizeofArray(p->aStmt); i++){
117469     sqlite3_finalize(p->aStmt[i]);
117470   }
117471   sqlite3_free(p->zSegmentsTbl);
117472   sqlite3_free(p->zReadExprlist);
117473   sqlite3_free(p->zWriteExprlist);
117474   sqlite3_free(p->zContentTbl);
117475   sqlite3_free(p->zLanguageid);
117476
117477   /* Invoke the tokenizer destructor to free the tokenizer. */
117478   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
117479
117480   sqlite3_free(p);
117481   return SQLITE_OK;
117482 }
117483
117484 /*
117485 ** Construct one or more SQL statements from the format string given
117486 ** and then evaluate those statements. The success code is written
117487 ** into *pRc.
117488 **
117489 ** If *pRc is initially non-zero then this routine is a no-op.
117490 */
117491 static void fts3DbExec(
117492   int *pRc,              /* Success code */
117493   sqlite3 *db,           /* Database in which to run SQL */
117494   const char *zFormat,   /* Format string for SQL */
117495   ...                    /* Arguments to the format string */
117496 ){
117497   va_list ap;
117498   char *zSql;
117499   if( *pRc ) return;
117500   va_start(ap, zFormat);
117501   zSql = sqlite3_vmprintf(zFormat, ap);
117502   va_end(ap);
117503   if( zSql==0 ){
117504     *pRc = SQLITE_NOMEM;
117505   }else{
117506     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
117507     sqlite3_free(zSql);
117508   }
117509 }
117510
117511 /*
117512 ** The xDestroy() virtual table method.
117513 */
117514 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
117515   Fts3Table *p = (Fts3Table *)pVtab;
117516   int rc = SQLITE_OK;              /* Return code */
117517   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
117518   sqlite3 *db = p->db;             /* Database handle */
117519
117520   /* Drop the shadow tables */
117521   if( p->zContentTbl==0 ){
117522     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
117523   }
117524   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
117525   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
117526   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
117527   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
117528
117529   /* If everything has worked, invoke fts3DisconnectMethod() to free the
117530   ** memory associated with the Fts3Table structure and return SQLITE_OK.
117531   ** Otherwise, return an SQLite error code.
117532   */
117533   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
117534 }
117535
117536
117537 /*
117538 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
117539 ** passed as the first argument. This is done as part of the xConnect()
117540 ** and xCreate() methods.
117541 **
117542 ** If *pRc is non-zero when this function is called, it is a no-op. 
117543 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117544 ** before returning.
117545 */
117546 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
117547   if( *pRc==SQLITE_OK ){
117548     int i;                        /* Iterator variable */
117549     int rc;                       /* Return code */
117550     char *zSql;                   /* SQL statement passed to declare_vtab() */
117551     char *zCols;                  /* List of user defined columns */
117552     const char *zLanguageid;
117553
117554     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
117555     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
117556
117557     /* Create a list of user columns for the virtual table */
117558     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
117559     for(i=1; zCols && i<p->nColumn; i++){
117560       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
117561     }
117562
117563     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
117564     zSql = sqlite3_mprintf(
117565         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
117566         zCols, p->zName, zLanguageid
117567     );
117568     if( !zCols || !zSql ){
117569       rc = SQLITE_NOMEM;
117570     }else{
117571       rc = sqlite3_declare_vtab(p->db, zSql);
117572     }
117573
117574     sqlite3_free(zSql);
117575     sqlite3_free(zCols);
117576     *pRc = rc;
117577   }
117578 }
117579
117580 /*
117581 ** Create the %_stat table if it does not already exist.
117582 */
117583 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
117584   fts3DbExec(pRc, p->db, 
117585       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
117586           "(id INTEGER PRIMARY KEY, value BLOB);",
117587       p->zDb, p->zName
117588   );
117589   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
117590 }
117591
117592 /*
117593 ** Create the backing store tables (%_content, %_segments and %_segdir)
117594 ** required by the FTS3 table passed as the only argument. This is done
117595 ** as part of the vtab xCreate() method.
117596 **
117597 ** If the p->bHasDocsize boolean is true (indicating that this is an
117598 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
117599 ** %_stat tables required by FTS4.
117600 */
117601 static int fts3CreateTables(Fts3Table *p){
117602   int rc = SQLITE_OK;             /* Return code */
117603   int i;                          /* Iterator variable */
117604   sqlite3 *db = p->db;            /* The database connection */
117605
117606   if( p->zContentTbl==0 ){
117607     const char *zLanguageid = p->zLanguageid;
117608     char *zContentCols;           /* Columns of %_content table */
117609
117610     /* Create a list of user columns for the content table */
117611     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
117612     for(i=0; zContentCols && i<p->nColumn; i++){
117613       char *z = p->azColumn[i];
117614       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
117615     }
117616     if( zLanguageid && zContentCols ){
117617       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
117618     }
117619     if( zContentCols==0 ) rc = SQLITE_NOMEM;
117620   
117621     /* Create the content table */
117622     fts3DbExec(&rc, db, 
117623        "CREATE TABLE %Q.'%q_content'(%s)",
117624        p->zDb, p->zName, zContentCols
117625     );
117626     sqlite3_free(zContentCols);
117627   }
117628
117629   /* Create other tables */
117630   fts3DbExec(&rc, db, 
117631       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
117632       p->zDb, p->zName
117633   );
117634   fts3DbExec(&rc, db, 
117635       "CREATE TABLE %Q.'%q_segdir'("
117636         "level INTEGER,"
117637         "idx INTEGER,"
117638         "start_block INTEGER,"
117639         "leaves_end_block INTEGER,"
117640         "end_block INTEGER,"
117641         "root BLOB,"
117642         "PRIMARY KEY(level, idx)"
117643       ");",
117644       p->zDb, p->zName
117645   );
117646   if( p->bHasDocsize ){
117647     fts3DbExec(&rc, db, 
117648         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
117649         p->zDb, p->zName
117650     );
117651   }
117652   assert( p->bHasStat==p->bFts4 );
117653   if( p->bHasStat ){
117654     sqlite3Fts3CreateStatTable(&rc, p);
117655   }
117656   return rc;
117657 }
117658
117659 /*
117660 ** Store the current database page-size in bytes in p->nPgsz.
117661 **
117662 ** If *pRc is non-zero when this function is called, it is a no-op. 
117663 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117664 ** before returning.
117665 */
117666 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
117667   if( *pRc==SQLITE_OK ){
117668     int rc;                       /* Return code */
117669     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
117670     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
117671   
117672     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
117673     if( !zSql ){
117674       rc = SQLITE_NOMEM;
117675     }else{
117676       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
117677       if( rc==SQLITE_OK ){
117678         sqlite3_step(pStmt);
117679         p->nPgsz = sqlite3_column_int(pStmt, 0);
117680         rc = sqlite3_finalize(pStmt);
117681       }else if( rc==SQLITE_AUTH ){
117682         p->nPgsz = 1024;
117683         rc = SQLITE_OK;
117684       }
117685     }
117686     assert( p->nPgsz>0 || rc!=SQLITE_OK );
117687     sqlite3_free(zSql);
117688     *pRc = rc;
117689   }
117690 }
117691
117692 /*
117693 ** "Special" FTS4 arguments are column specifications of the following form:
117694 **
117695 **   <key> = <value>
117696 **
117697 ** There may not be whitespace surrounding the "=" character. The <value> 
117698 ** term may be quoted, but the <key> may not.
117699 */
117700 static int fts3IsSpecialColumn(
117701   const char *z, 
117702   int *pnKey,
117703   char **pzValue
117704 ){
117705   char *zValue;
117706   const char *zCsr = z;
117707
117708   while( *zCsr!='=' ){
117709     if( *zCsr=='\0' ) return 0;
117710     zCsr++;
117711   }
117712
117713   *pnKey = (int)(zCsr-z);
117714   zValue = sqlite3_mprintf("%s", &zCsr[1]);
117715   if( zValue ){
117716     sqlite3Fts3Dequote(zValue);
117717   }
117718   *pzValue = zValue;
117719   return 1;
117720 }
117721
117722 /*
117723 ** Append the output of a printf() style formatting to an existing string.
117724 */
117725 static void fts3Appendf(
117726   int *pRc,                       /* IN/OUT: Error code */
117727   char **pz,                      /* IN/OUT: Pointer to string buffer */
117728   const char *zFormat,            /* Printf format string to append */
117729   ...                             /* Arguments for printf format string */
117730 ){
117731   if( *pRc==SQLITE_OK ){
117732     va_list ap;
117733     char *z;
117734     va_start(ap, zFormat);
117735     z = sqlite3_vmprintf(zFormat, ap);
117736     va_end(ap);
117737     if( z && *pz ){
117738       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
117739       sqlite3_free(z);
117740       z = z2;
117741     }
117742     if( z==0 ) *pRc = SQLITE_NOMEM;
117743     sqlite3_free(*pz);
117744     *pz = z;
117745   }
117746 }
117747
117748 /*
117749 ** Return a copy of input string zInput enclosed in double-quotes (") and
117750 ** with all double quote characters escaped. For example:
117751 **
117752 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
117753 **
117754 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
117755 ** is the callers responsibility to call sqlite3_free() to release this
117756 ** memory.
117757 */
117758 static char *fts3QuoteId(char const *zInput){
117759   int nRet;
117760   char *zRet;
117761   nRet = 2 + (int)strlen(zInput)*2 + 1;
117762   zRet = sqlite3_malloc(nRet);
117763   if( zRet ){
117764     int i;
117765     char *z = zRet;
117766     *(z++) = '"';
117767     for(i=0; zInput[i]; i++){
117768       if( zInput[i]=='"' ) *(z++) = '"';
117769       *(z++) = zInput[i];
117770     }
117771     *(z++) = '"';
117772     *(z++) = '\0';
117773   }
117774   return zRet;
117775 }
117776
117777 /*
117778 ** Return a list of comma separated SQL expressions and a FROM clause that 
117779 ** could be used in a SELECT statement such as the following:
117780 **
117781 **     SELECT <list of expressions> FROM %_content AS x ...
117782 **
117783 ** to return the docid, followed by each column of text data in order
117784 ** from left to write. If parameter zFunc is not NULL, then instead of
117785 ** being returned directly each column of text data is passed to an SQL
117786 ** function named zFunc first. For example, if zFunc is "unzip" and the
117787 ** table has the three user-defined columns "a", "b", and "c", the following
117788 ** string is returned:
117789 **
117790 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
117791 **
117792 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117793 ** is the responsibility of the caller to eventually free it.
117794 **
117795 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117796 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117797 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117798 ** no error occurs, *pRc is left unmodified.
117799 */
117800 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
117801   char *zRet = 0;
117802   char *zFree = 0;
117803   char *zFunction;
117804   int i;
117805
117806   if( p->zContentTbl==0 ){
117807     if( !zFunc ){
117808       zFunction = "";
117809     }else{
117810       zFree = zFunction = fts3QuoteId(zFunc);
117811     }
117812     fts3Appendf(pRc, &zRet, "docid");
117813     for(i=0; i<p->nColumn; i++){
117814       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
117815     }
117816     if( p->zLanguageid ){
117817       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
117818     }
117819     sqlite3_free(zFree);
117820   }else{
117821     fts3Appendf(pRc, &zRet, "rowid");
117822     for(i=0; i<p->nColumn; i++){
117823       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
117824     }
117825     if( p->zLanguageid ){
117826       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
117827     }
117828   }
117829   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
117830       p->zDb,
117831       (p->zContentTbl ? p->zContentTbl : p->zName),
117832       (p->zContentTbl ? "" : "_content")
117833   );
117834   return zRet;
117835 }
117836
117837 /*
117838 ** Return a list of N comma separated question marks, where N is the number
117839 ** of columns in the %_content table (one for the docid plus one for each
117840 ** user-defined text column).
117841 **
117842 ** If argument zFunc is not NULL, then all but the first question mark
117843 ** is preceded by zFunc and an open bracket, and followed by a closed
117844 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
117845 ** user-defined text columns, the following string is returned:
117846 **
117847 **     "?, zip(?), zip(?), zip(?)"
117848 **
117849 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117850 ** is the responsibility of the caller to eventually free it.
117851 **
117852 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117853 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117854 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117855 ** no error occurs, *pRc is left unmodified.
117856 */
117857 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
117858   char *zRet = 0;
117859   char *zFree = 0;
117860   char *zFunction;
117861   int i;
117862
117863   if( !zFunc ){
117864     zFunction = "";
117865   }else{
117866     zFree = zFunction = fts3QuoteId(zFunc);
117867   }
117868   fts3Appendf(pRc, &zRet, "?");
117869   for(i=0; i<p->nColumn; i++){
117870     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
117871   }
117872   if( p->zLanguageid ){
117873     fts3Appendf(pRc, &zRet, ", ?");
117874   }
117875   sqlite3_free(zFree);
117876   return zRet;
117877 }
117878
117879 /*
117880 ** This function interprets the string at (*pp) as a non-negative integer
117881 ** value. It reads the integer and sets *pnOut to the value read, then 
117882 ** sets *pp to point to the byte immediately following the last byte of
117883 ** the integer value.
117884 **
117885 ** Only decimal digits ('0'..'9') may be part of an integer value. 
117886 **
117887 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
117888 ** the output value undefined. Otherwise SQLITE_OK is returned.
117889 **
117890 ** This function is used when parsing the "prefix=" FTS4 parameter.
117891 */
117892 static int fts3GobbleInt(const char **pp, int *pnOut){
117893   const char *p;                  /* Iterator pointer */
117894   int nInt = 0;                   /* Output value */
117895
117896   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
117897     nInt = nInt * 10 + (p[0] - '0');
117898   }
117899   if( p==*pp ) return SQLITE_ERROR;
117900   *pnOut = nInt;
117901   *pp = p;
117902   return SQLITE_OK;
117903 }
117904
117905 /*
117906 ** This function is called to allocate an array of Fts3Index structures
117907 ** representing the indexes maintained by the current FTS table. FTS tables
117908 ** always maintain the main "terms" index, but may also maintain one or
117909 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
117910 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
117911 **
117912 ** Argument zParam is passed the value of the "prefix=" option if one was
117913 ** specified, or NULL otherwise.
117914 **
117915 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
117916 ** the allocated array. *pnIndex is set to the number of elements in the
117917 ** array. If an error does occur, an SQLite error code is returned.
117918 **
117919 ** Regardless of whether or not an error is returned, it is the responsibility
117920 ** of the caller to call sqlite3_free() on the output array to free it.
117921 */
117922 static int fts3PrefixParameter(
117923   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
117924   int *pnIndex,                   /* OUT: size of *apIndex[] array */
117925   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
117926 ){
117927   struct Fts3Index *aIndex;       /* Allocated array */
117928   int nIndex = 1;                 /* Number of entries in array */
117929
117930   if( zParam && zParam[0] ){
117931     const char *p;
117932     nIndex++;
117933     for(p=zParam; *p; p++){
117934       if( *p==',' ) nIndex++;
117935     }
117936   }
117937
117938   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
117939   *apIndex = aIndex;
117940   *pnIndex = nIndex;
117941   if( !aIndex ){
117942     return SQLITE_NOMEM;
117943   }
117944
117945   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
117946   if( zParam ){
117947     const char *p = zParam;
117948     int i;
117949     for(i=1; i<nIndex; i++){
117950       int nPrefix;
117951       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
117952       aIndex[i].nPrefix = nPrefix;
117953       p++;
117954     }
117955   }
117956
117957   return SQLITE_OK;
117958 }
117959
117960 /*
117961 ** This function is called when initializing an FTS4 table that uses the
117962 ** content=xxx option. It determines the number of and names of the columns
117963 ** of the new FTS4 table.
117964 **
117965 ** The third argument passed to this function is the value passed to the
117966 ** config=xxx option (i.e. "xxx"). This function queries the database for
117967 ** a table of that name. If found, the output variables are populated
117968 ** as follows:
117969 **
117970 **   *pnCol:   Set to the number of columns table xxx has,
117971 **
117972 **   *pnStr:   Set to the total amount of space required to store a copy
117973 **             of each columns name, including the nul-terminator.
117974 **
117975 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
117976 **             the name of the corresponding column in table xxx. The array
117977 **             and its contents are allocated using a single allocation. It
117978 **             is the responsibility of the caller to free this allocation
117979 **             by eventually passing the *pazCol value to sqlite3_free().
117980 **
117981 ** If the table cannot be found, an error code is returned and the output
117982 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
117983 ** returned (and the output variables are undefined).
117984 */
117985 static int fts3ContentColumns(
117986   sqlite3 *db,                    /* Database handle */
117987   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
117988   const char *zTbl,               /* Name of content table */
117989   const char ***pazCol,           /* OUT: Malloc'd array of column names */
117990   int *pnCol,                     /* OUT: Size of array *pazCol */
117991   int *pnStr                      /* OUT: Bytes of string content */
117992 ){
117993   int rc = SQLITE_OK;             /* Return code */
117994   char *zSql;                     /* "SELECT *" statement on zTbl */  
117995   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
117996
117997   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
117998   if( !zSql ){
117999     rc = SQLITE_NOMEM;
118000   }else{
118001     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
118002   }
118003   sqlite3_free(zSql);
118004
118005   if( rc==SQLITE_OK ){
118006     const char **azCol;           /* Output array */
118007     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
118008     int nCol;                     /* Number of table columns */
118009     int i;                        /* Used to iterate through columns */
118010
118011     /* Loop through the returned columns. Set nStr to the number of bytes of
118012     ** space required to store a copy of each column name, including the
118013     ** nul-terminator byte.  */
118014     nCol = sqlite3_column_count(pStmt);
118015     for(i=0; i<nCol; i++){
118016       const char *zCol = sqlite3_column_name(pStmt, i);
118017       nStr += (int)strlen(zCol) + 1;
118018     }
118019
118020     /* Allocate and populate the array to return. */
118021     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
118022     if( azCol==0 ){
118023       rc = SQLITE_NOMEM;
118024     }else{
118025       char *p = (char *)&azCol[nCol];
118026       for(i=0; i<nCol; i++){
118027         const char *zCol = sqlite3_column_name(pStmt, i);
118028         int n = (int)strlen(zCol)+1;
118029         memcpy(p, zCol, n);
118030         azCol[i] = p;
118031         p += n;
118032       }
118033     }
118034     sqlite3_finalize(pStmt);
118035
118036     /* Set the output variables. */
118037     *pnCol = nCol;
118038     *pnStr = nStr;
118039     *pazCol = azCol;
118040   }
118041
118042   return rc;
118043 }
118044
118045 /*
118046 ** This function is the implementation of both the xConnect and xCreate
118047 ** methods of the FTS3 virtual table.
118048 **
118049 ** The argv[] array contains the following:
118050 **
118051 **   argv[0]   -> module name  ("fts3" or "fts4")
118052 **   argv[1]   -> database name
118053 **   argv[2]   -> table name
118054 **   argv[...] -> "column name" and other module argument fields.
118055 */
118056 static int fts3InitVtab(
118057   int isCreate,                   /* True for xCreate, false for xConnect */
118058   sqlite3 *db,                    /* The SQLite database connection */
118059   void *pAux,                     /* Hash table containing tokenizers */
118060   int argc,                       /* Number of elements in argv array */
118061   const char * const *argv,       /* xCreate/xConnect argument array */
118062   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
118063   char **pzErr                    /* Write any error message here */
118064 ){
118065   Fts3Hash *pHash = (Fts3Hash *)pAux;
118066   Fts3Table *p = 0;               /* Pointer to allocated vtab */
118067   int rc = SQLITE_OK;             /* Return code */
118068   int i;                          /* Iterator variable */
118069   int nByte;                      /* Size of allocation used for *p */
118070   int iCol;                       /* Column index */
118071   int nString = 0;                /* Bytes required to hold all column names */
118072   int nCol = 0;                   /* Number of columns in the FTS table */
118073   char *zCsr;                     /* Space for holding column names */
118074   int nDb;                        /* Bytes required to hold database name */
118075   int nName;                      /* Bytes required to hold table name */
118076   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
118077   const char **aCol;              /* Array of column names */
118078   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
118079
118080   int nIndex;                     /* Size of aIndex[] array */
118081   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
118082
118083   /* The results of parsing supported FTS4 key=value options: */
118084   int bNoDocsize = 0;             /* True to omit %_docsize table */
118085   int bDescIdx = 0;               /* True to store descending indexes */
118086   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
118087   char *zCompress = 0;            /* compress=? parameter (or NULL) */
118088   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
118089   char *zContent = 0;             /* content=? parameter (or NULL) */
118090   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
118091
118092   assert( strlen(argv[0])==4 );
118093   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
118094        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
118095   );
118096
118097   nDb = (int)strlen(argv[1]) + 1;
118098   nName = (int)strlen(argv[2]) + 1;
118099
118100   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
118101   if( !aCol ) return SQLITE_NOMEM;
118102   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
118103
118104   /* Loop through all of the arguments passed by the user to the FTS3/4
118105   ** module (i.e. all the column names and special arguments). This loop
118106   ** does the following:
118107   **
118108   **   + Figures out the number of columns the FTSX table will have, and
118109   **     the number of bytes of space that must be allocated to store copies
118110   **     of the column names.
118111   **
118112   **   + If there is a tokenizer specification included in the arguments,
118113   **     initializes the tokenizer pTokenizer.
118114   */
118115   for(i=3; rc==SQLITE_OK && i<argc; i++){
118116     char const *z = argv[i];
118117     int nKey;
118118     char *zVal;
118119
118120     /* Check if this is a tokenizer specification */
118121     if( !pTokenizer 
118122      && strlen(z)>8
118123      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
118124      && 0==sqlite3Fts3IsIdChar(z[8])
118125     ){
118126       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
118127     }
118128
118129     /* Check if it is an FTS4 special argument. */
118130     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
118131       struct Fts4Option {
118132         const char *zOpt;
118133         int nOpt;
118134       } aFts4Opt[] = {
118135         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
118136         { "prefix",      6 },     /* 1 -> PREFIX */
118137         { "compress",    8 },     /* 2 -> COMPRESS */
118138         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
118139         { "order",       5 },     /* 4 -> ORDER */
118140         { "content",     7 },     /* 5 -> CONTENT */
118141         { "languageid", 10 }      /* 6 -> LANGUAGEID */
118142       };
118143
118144       int iOpt;
118145       if( !zVal ){
118146         rc = SQLITE_NOMEM;
118147       }else{
118148         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
118149           struct Fts4Option *pOp = &aFts4Opt[iOpt];
118150           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
118151             break;
118152           }
118153         }
118154         if( iOpt==SizeofArray(aFts4Opt) ){
118155           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
118156           rc = SQLITE_ERROR;
118157         }else{
118158           switch( iOpt ){
118159             case 0:               /* MATCHINFO */
118160               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
118161                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
118162                 rc = SQLITE_ERROR;
118163               }
118164               bNoDocsize = 1;
118165               break;
118166
118167             case 1:               /* PREFIX */
118168               sqlite3_free(zPrefix);
118169               zPrefix = zVal;
118170               zVal = 0;
118171               break;
118172
118173             case 2:               /* COMPRESS */
118174               sqlite3_free(zCompress);
118175               zCompress = zVal;
118176               zVal = 0;
118177               break;
118178
118179             case 3:               /* UNCOMPRESS */
118180               sqlite3_free(zUncompress);
118181               zUncompress = zVal;
118182               zVal = 0;
118183               break;
118184
118185             case 4:               /* ORDER */
118186               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
118187                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
118188               ){
118189                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
118190                 rc = SQLITE_ERROR;
118191               }
118192               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
118193               break;
118194
118195             case 5:              /* CONTENT */
118196               sqlite3_free(zContent);
118197               zContent = zVal;
118198               zVal = 0;
118199               break;
118200
118201             case 6:              /* LANGUAGEID */
118202               assert( iOpt==6 );
118203               sqlite3_free(zLanguageid);
118204               zLanguageid = zVal;
118205               zVal = 0;
118206               break;
118207           }
118208         }
118209         sqlite3_free(zVal);
118210       }
118211     }
118212
118213     /* Otherwise, the argument is a column name. */
118214     else {
118215       nString += (int)(strlen(z) + 1);
118216       aCol[nCol++] = z;
118217     }
118218   }
118219
118220   /* If a content=xxx option was specified, the following:
118221   **
118222   **   1. Ignore any compress= and uncompress= options.
118223   **
118224   **   2. If no column names were specified as part of the CREATE VIRTUAL
118225   **      TABLE statement, use all columns from the content table.
118226   */
118227   if( rc==SQLITE_OK && zContent ){
118228     sqlite3_free(zCompress); 
118229     sqlite3_free(zUncompress); 
118230     zCompress = 0;
118231     zUncompress = 0;
118232     if( nCol==0 ){
118233       sqlite3_free((void*)aCol); 
118234       aCol = 0;
118235       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
118236
118237       /* If a languageid= option was specified, remove the language id
118238       ** column from the aCol[] array. */ 
118239       if( rc==SQLITE_OK && zLanguageid ){
118240         int j;
118241         for(j=0; j<nCol; j++){
118242           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
118243             int k;
118244             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
118245             nCol--;
118246             break;
118247           }
118248         }
118249       }
118250     }
118251   }
118252   if( rc!=SQLITE_OK ) goto fts3_init_out;
118253
118254   if( nCol==0 ){
118255     assert( nString==0 );
118256     aCol[0] = "content";
118257     nString = 8;
118258     nCol = 1;
118259   }
118260
118261   if( pTokenizer==0 ){
118262     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
118263     if( rc!=SQLITE_OK ) goto fts3_init_out;
118264   }
118265   assert( pTokenizer );
118266
118267   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
118268   if( rc==SQLITE_ERROR ){
118269     assert( zPrefix );
118270     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
118271   }
118272   if( rc!=SQLITE_OK ) goto fts3_init_out;
118273
118274   /* Allocate and populate the Fts3Table structure. */
118275   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
118276           nCol * sizeof(char *) +              /* azColumn */
118277           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
118278           nName +                              /* zName */
118279           nDb +                                /* zDb */
118280           nString;                             /* Space for azColumn strings */
118281   p = (Fts3Table*)sqlite3_malloc(nByte);
118282   if( p==0 ){
118283     rc = SQLITE_NOMEM;
118284     goto fts3_init_out;
118285   }
118286   memset(p, 0, nByte);
118287   p->db = db;
118288   p->nColumn = nCol;
118289   p->nPendingData = 0;
118290   p->azColumn = (char **)&p[1];
118291   p->pTokenizer = pTokenizer;
118292   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
118293   p->bHasDocsize = (isFts4 && bNoDocsize==0);
118294   p->bHasStat = isFts4;
118295   p->bFts4 = isFts4;
118296   p->bDescIdx = bDescIdx;
118297   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
118298   p->zContentTbl = zContent;
118299   p->zLanguageid = zLanguageid;
118300   zContent = 0;
118301   zLanguageid = 0;
118302   TESTONLY( p->inTransaction = -1 );
118303   TESTONLY( p->mxSavepoint = -1 );
118304
118305   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
118306   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
118307   p->nIndex = nIndex;
118308   for(i=0; i<nIndex; i++){
118309     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
118310   }
118311
118312   /* Fill in the zName and zDb fields of the vtab structure. */
118313   zCsr = (char *)&p->aIndex[nIndex];
118314   p->zName = zCsr;
118315   memcpy(zCsr, argv[2], nName);
118316   zCsr += nName;
118317   p->zDb = zCsr;
118318   memcpy(zCsr, argv[1], nDb);
118319   zCsr += nDb;
118320
118321   /* Fill in the azColumn array */
118322   for(iCol=0; iCol<nCol; iCol++){
118323     char *z; 
118324     int n = 0;
118325     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
118326     memcpy(zCsr, z, n);
118327     zCsr[n] = '\0';
118328     sqlite3Fts3Dequote(zCsr);
118329     p->azColumn[iCol] = zCsr;
118330     zCsr += n+1;
118331     assert( zCsr <= &((char *)p)[nByte] );
118332   }
118333
118334   if( (zCompress==0)!=(zUncompress==0) ){
118335     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
118336     rc = SQLITE_ERROR;
118337     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
118338   }
118339   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
118340   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
118341   if( rc!=SQLITE_OK ) goto fts3_init_out;
118342
118343   /* If this is an xCreate call, create the underlying tables in the 
118344   ** database. TODO: For xConnect(), it could verify that said tables exist.
118345   */
118346   if( isCreate ){
118347     rc = fts3CreateTables(p);
118348   }
118349
118350   /* Check to see if a legacy fts3 table has been "upgraded" by the
118351   ** addition of a %_stat table so that it can use incremental merge.
118352   */
118353   if( !isFts4 && !isCreate ){
118354     int rc2 = SQLITE_OK;
118355     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
118356                p->zDb, p->zName);
118357     if( rc2==SQLITE_OK ) p->bHasStat = 1;
118358   }
118359
118360   /* Figure out the page-size for the database. This is required in order to
118361   ** estimate the cost of loading large doclists from the database.  */
118362   fts3DatabasePageSize(&rc, p);
118363   p->nNodeSize = p->nPgsz-35;
118364
118365   /* Declare the table schema to SQLite. */
118366   fts3DeclareVtab(&rc, p);
118367
118368 fts3_init_out:
118369   sqlite3_free(zPrefix);
118370   sqlite3_free(aIndex);
118371   sqlite3_free(zCompress);
118372   sqlite3_free(zUncompress);
118373   sqlite3_free(zContent);
118374   sqlite3_free(zLanguageid);
118375   sqlite3_free((void *)aCol);
118376   if( rc!=SQLITE_OK ){
118377     if( p ){
118378       fts3DisconnectMethod((sqlite3_vtab *)p);
118379     }else if( pTokenizer ){
118380       pTokenizer->pModule->xDestroy(pTokenizer);
118381     }
118382   }else{
118383     assert( p->pSegments==0 );
118384     *ppVTab = &p->base;
118385   }
118386   return rc;
118387 }
118388
118389 /*
118390 ** The xConnect() and xCreate() methods for the virtual table. All the
118391 ** work is done in function fts3InitVtab().
118392 */
118393 static int fts3ConnectMethod(
118394   sqlite3 *db,                    /* Database connection */
118395   void *pAux,                     /* Pointer to tokenizer hash table */
118396   int argc,                       /* Number of elements in argv array */
118397   const char * const *argv,       /* xCreate/xConnect argument array */
118398   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118399   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118400 ){
118401   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
118402 }
118403 static int fts3CreateMethod(
118404   sqlite3 *db,                    /* Database connection */
118405   void *pAux,                     /* Pointer to tokenizer hash table */
118406   int argc,                       /* Number of elements in argv array */
118407   const char * const *argv,       /* xCreate/xConnect argument array */
118408   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118409   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118410 ){
118411   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
118412 }
118413
118414 /* 
118415 ** Implementation of the xBestIndex method for FTS3 tables. There
118416 ** are three possible strategies, in order of preference:
118417 **
118418 **   1. Direct lookup by rowid or docid. 
118419 **   2. Full-text search using a MATCH operator on a non-docid column.
118420 **   3. Linear scan of %_content table.
118421 */
118422 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
118423   Fts3Table *p = (Fts3Table *)pVTab;
118424   int i;                          /* Iterator variable */
118425   int iCons = -1;                 /* Index of constraint to use */
118426   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
118427
118428   /* By default use a full table scan. This is an expensive option,
118429   ** so search through the constraints to see if a more efficient 
118430   ** strategy is possible.
118431   */
118432   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
118433   pInfo->estimatedCost = 500000;
118434   for(i=0; i<pInfo->nConstraint; i++){
118435     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
118436     if( pCons->usable==0 ) continue;
118437
118438     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
118439     if( iCons<0 
118440      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
118441      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
118442     ){
118443       pInfo->idxNum = FTS3_DOCID_SEARCH;
118444       pInfo->estimatedCost = 1.0;
118445       iCons = i;
118446     }
118447
118448     /* A MATCH constraint. Use a full-text search.
118449     **
118450     ** If there is more than one MATCH constraint available, use the first
118451     ** one encountered. If there is both a MATCH constraint and a direct
118452     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
118453     ** though the rowid/docid lookup is faster than a MATCH query, selecting
118454     ** it would lead to an "unable to use function MATCH in the requested 
118455     ** context" error.
118456     */
118457     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
118458      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
118459     ){
118460       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
118461       pInfo->estimatedCost = 2.0;
118462       iCons = i;
118463     }
118464
118465     /* Equality constraint on the langid column */
118466     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
118467      && pCons->iColumn==p->nColumn + 2
118468     ){
118469       iLangidCons = i;
118470     }
118471   }
118472
118473   if( iCons>=0 ){
118474     pInfo->aConstraintUsage[iCons].argvIndex = 1;
118475     pInfo->aConstraintUsage[iCons].omit = 1;
118476   } 
118477   if( iLangidCons>=0 ){
118478     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
118479   } 
118480
118481   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
118482   ** docid) order. Both ascending and descending are possible. 
118483   */
118484   if( pInfo->nOrderBy==1 ){
118485     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
118486     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
118487       if( pOrder->desc ){
118488         pInfo->idxStr = "DESC";
118489       }else{
118490         pInfo->idxStr = "ASC";
118491       }
118492       pInfo->orderByConsumed = 1;
118493     }
118494   }
118495
118496   assert( p->pSegments==0 );
118497   return SQLITE_OK;
118498 }
118499
118500 /*
118501 ** Implementation of xOpen method.
118502 */
118503 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
118504   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
118505
118506   UNUSED_PARAMETER(pVTab);
118507
118508   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
118509   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
118510   ** if the allocation fails, return SQLITE_NOMEM.
118511   */
118512   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
118513   if( !pCsr ){
118514     return SQLITE_NOMEM;
118515   }
118516   memset(pCsr, 0, sizeof(Fts3Cursor));
118517   return SQLITE_OK;
118518 }
118519
118520 /*
118521 ** Close the cursor.  For additional information see the documentation
118522 ** on the xClose method of the virtual table interface.
118523 */
118524 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
118525   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118526   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118527   sqlite3_finalize(pCsr->pStmt);
118528   sqlite3Fts3ExprFree(pCsr->pExpr);
118529   sqlite3Fts3FreeDeferredTokens(pCsr);
118530   sqlite3_free(pCsr->aDoclist);
118531   sqlite3_free(pCsr->aMatchinfo);
118532   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118533   sqlite3_free(pCsr);
118534   return SQLITE_OK;
118535 }
118536
118537 /*
118538 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
118539 ** compose and prepare an SQL statement of the form:
118540 **
118541 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
118542 **
118543 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
118544 ** it. If an error occurs, return an SQLite error code.
118545 **
118546 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
118547 */
118548 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
118549   int rc = SQLITE_OK;
118550   if( pCsr->pStmt==0 ){
118551     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118552     char *zSql;
118553     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
118554     if( !zSql ) return SQLITE_NOMEM;
118555     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
118556     sqlite3_free(zSql);
118557   }
118558   *ppStmt = pCsr->pStmt;
118559   return rc;
118560 }
118561
118562 /*
118563 ** Position the pCsr->pStmt statement so that it is on the row
118564 ** of the %_content table that contains the last match.  Return
118565 ** SQLITE_OK on success.  
118566 */
118567 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
118568   int rc = SQLITE_OK;
118569   if( pCsr->isRequireSeek ){
118570     sqlite3_stmt *pStmt = 0;
118571
118572     rc = fts3CursorSeekStmt(pCsr, &pStmt);
118573     if( rc==SQLITE_OK ){
118574       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
118575       pCsr->isRequireSeek = 0;
118576       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
118577         return SQLITE_OK;
118578       }else{
118579         rc = sqlite3_reset(pCsr->pStmt);
118580         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
118581           /* If no row was found and no error has occured, then the %_content
118582           ** table is missing a row that is present in the full-text index.
118583           ** The data structures are corrupt.  */
118584           rc = FTS_CORRUPT_VTAB;
118585           pCsr->isEof = 1;
118586         }
118587       }
118588     }
118589   }
118590
118591   if( rc!=SQLITE_OK && pContext ){
118592     sqlite3_result_error_code(pContext, rc);
118593   }
118594   return rc;
118595 }
118596
118597 /*
118598 ** This function is used to process a single interior node when searching
118599 ** a b-tree for a term or term prefix. The node data is passed to this 
118600 ** function via the zNode/nNode parameters. The term to search for is
118601 ** passed in zTerm/nTerm.
118602 **
118603 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
118604 ** of the child node that heads the sub-tree that may contain the term.
118605 **
118606 ** If piLast is not NULL, then *piLast is set to the right-most child node
118607 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
118608 ** a prefix.
118609 **
118610 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
118611 */
118612 static int fts3ScanInteriorNode(
118613   const char *zTerm,              /* Term to select leaves for */
118614   int nTerm,                      /* Size of term zTerm in bytes */
118615   const char *zNode,              /* Buffer containing segment interior node */
118616   int nNode,                      /* Size of buffer at zNode */
118617   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
118618   sqlite3_int64 *piLast           /* OUT: Selected child node */
118619 ){
118620   int rc = SQLITE_OK;             /* Return code */
118621   const char *zCsr = zNode;       /* Cursor to iterate through node */
118622   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
118623   char *zBuffer = 0;              /* Buffer to load terms into */
118624   int nAlloc = 0;                 /* Size of allocated buffer */
118625   int isFirstTerm = 1;            /* True when processing first term on page */
118626   sqlite3_int64 iChild;           /* Block id of child node to descend to */
118627
118628   /* Skip over the 'height' varint that occurs at the start of every 
118629   ** interior node. Then load the blockid of the left-child of the b-tree
118630   ** node into variable iChild.  
118631   **
118632   ** Even if the data structure on disk is corrupted, this (reading two
118633   ** varints from the buffer) does not risk an overread. If zNode is a
118634   ** root node, then the buffer comes from a SELECT statement. SQLite does
118635   ** not make this guarantee explicitly, but in practice there are always
118636   ** either more than 20 bytes of allocated space following the nNode bytes of
118637   ** contents, or two zero bytes. Or, if the node is read from the %_segments
118638   ** table, then there are always 20 bytes of zeroed padding following the
118639   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
118640   */
118641   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118642   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118643   if( zCsr>zEnd ){
118644     return FTS_CORRUPT_VTAB;
118645   }
118646   
118647   while( zCsr<zEnd && (piFirst || piLast) ){
118648     int cmp;                      /* memcmp() result */
118649     int nSuffix;                  /* Size of term suffix */
118650     int nPrefix = 0;              /* Size of term prefix */
118651     int nBuffer;                  /* Total term size */
118652   
118653     /* Load the next term on the node into zBuffer. Use realloc() to expand
118654     ** the size of zBuffer if required.  */
118655     if( !isFirstTerm ){
118656       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
118657     }
118658     isFirstTerm = 0;
118659     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
118660     
118661     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
118662       rc = FTS_CORRUPT_VTAB;
118663       goto finish_scan;
118664     }
118665     if( nPrefix+nSuffix>nAlloc ){
118666       char *zNew;
118667       nAlloc = (nPrefix+nSuffix) * 2;
118668       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
118669       if( !zNew ){
118670         rc = SQLITE_NOMEM;
118671         goto finish_scan;
118672       }
118673       zBuffer = zNew;
118674     }
118675     assert( zBuffer );
118676     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
118677     nBuffer = nPrefix + nSuffix;
118678     zCsr += nSuffix;
118679
118680     /* Compare the term we are searching for with the term just loaded from
118681     ** the interior node. If the specified term is greater than or equal
118682     ** to the term from the interior node, then all terms on the sub-tree 
118683     ** headed by node iChild are smaller than zTerm. No need to search 
118684     ** iChild.
118685     **
118686     ** If the interior node term is larger than the specified term, then
118687     ** the tree headed by iChild may contain the specified term.
118688     */
118689     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
118690     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
118691       *piFirst = iChild;
118692       piFirst = 0;
118693     }
118694
118695     if( piLast && cmp<0 ){
118696       *piLast = iChild;
118697       piLast = 0;
118698     }
118699
118700     iChild++;
118701   };
118702
118703   if( piFirst ) *piFirst = iChild;
118704   if( piLast ) *piLast = iChild;
118705
118706  finish_scan:
118707   sqlite3_free(zBuffer);
118708   return rc;
118709 }
118710
118711
118712 /*
118713 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
118714 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
118715 ** contains a term. This function searches the sub-tree headed by the zNode
118716 ** node for the range of leaf nodes that may contain the specified term
118717 ** or terms for which the specified term is a prefix.
118718 **
118719 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
118720 ** left-most leaf node in the tree that may contain the specified term.
118721 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
118722 ** right-most leaf node that may contain a term for which the specified
118723 ** term is a prefix.
118724 **
118725 ** It is possible that the range of returned leaf nodes does not contain 
118726 ** the specified term or any terms for which it is a prefix. However, if the 
118727 ** segment does contain any such terms, they are stored within the identified
118728 ** range. Because this function only inspects interior segment nodes (and
118729 ** never loads leaf nodes into memory), it is not possible to be sure.
118730 **
118731 ** If an error occurs, an error code other than SQLITE_OK is returned.
118732 */ 
118733 static int fts3SelectLeaf(
118734   Fts3Table *p,                   /* Virtual table handle */
118735   const char *zTerm,              /* Term to select leaves for */
118736   int nTerm,                      /* Size of term zTerm in bytes */
118737   const char *zNode,              /* Buffer containing segment interior node */
118738   int nNode,                      /* Size of buffer at zNode */
118739   sqlite3_int64 *piLeaf,          /* Selected leaf node */
118740   sqlite3_int64 *piLeaf2          /* Selected leaf node */
118741 ){
118742   int rc;                         /* Return code */
118743   int iHeight;                    /* Height of this node in tree */
118744
118745   assert( piLeaf || piLeaf2 );
118746
118747   sqlite3Fts3GetVarint32(zNode, &iHeight);
118748   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
118749   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
118750
118751   if( rc==SQLITE_OK && iHeight>1 ){
118752     char *zBlob = 0;              /* Blob read from %_segments table */
118753     int nBlob;                    /* Size of zBlob in bytes */
118754
118755     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
118756       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
118757       if( rc==SQLITE_OK ){
118758         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
118759       }
118760       sqlite3_free(zBlob);
118761       piLeaf = 0;
118762       zBlob = 0;
118763     }
118764
118765     if( rc==SQLITE_OK ){
118766       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
118767     }
118768     if( rc==SQLITE_OK ){
118769       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
118770     }
118771     sqlite3_free(zBlob);
118772   }
118773
118774   return rc;
118775 }
118776
118777 /*
118778 ** This function is used to create delta-encoded serialized lists of FTS3 
118779 ** varints. Each call to this function appends a single varint to a list.
118780 */
118781 static void fts3PutDeltaVarint(
118782   char **pp,                      /* IN/OUT: Output pointer */
118783   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118784   sqlite3_int64 iVal              /* Write this value to the list */
118785 ){
118786   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
118787   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
118788   *piPrev = iVal;
118789 }
118790
118791 /*
118792 ** When this function is called, *ppPoslist is assumed to point to the 
118793 ** start of a position-list. After it returns, *ppPoslist points to the
118794 ** first byte after the position-list.
118795 **
118796 ** A position list is list of positions (delta encoded) and columns for 
118797 ** a single document record of a doclist.  So, in other words, this
118798 ** routine advances *ppPoslist so that it points to the next docid in
118799 ** the doclist, or to the first byte past the end of the doclist.
118800 **
118801 ** If pp is not NULL, then the contents of the position list are copied
118802 ** to *pp. *pp is set to point to the first byte past the last byte copied
118803 ** before this function returns.
118804 */
118805 static void fts3PoslistCopy(char **pp, char **ppPoslist){
118806   char *pEnd = *ppPoslist;
118807   char c = 0;
118808
118809   /* The end of a position list is marked by a zero encoded as an FTS3 
118810   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
118811   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
118812   ** of some other, multi-byte, value.
118813   **
118814   ** The following while-loop moves pEnd to point to the first byte that is not 
118815   ** immediately preceded by a byte with the 0x80 bit set. Then increments
118816   ** pEnd once more so that it points to the byte immediately following the
118817   ** last byte in the position-list.
118818   */
118819   while( *pEnd | c ){
118820     c = *pEnd++ & 0x80;
118821     testcase( c!=0 && (*pEnd)==0 );
118822   }
118823   pEnd++;  /* Advance past the POS_END terminator byte */
118824
118825   if( pp ){
118826     int n = (int)(pEnd - *ppPoslist);
118827     char *p = *pp;
118828     memcpy(p, *ppPoslist, n);
118829     p += n;
118830     *pp = p;
118831   }
118832   *ppPoslist = pEnd;
118833 }
118834
118835 /*
118836 ** When this function is called, *ppPoslist is assumed to point to the 
118837 ** start of a column-list. After it returns, *ppPoslist points to the
118838 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
118839 **
118840 ** A column-list is list of delta-encoded positions for a single column
118841 ** within a single document within a doclist.
118842 **
118843 ** The column-list is terminated either by a POS_COLUMN varint (1) or
118844 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
118845 ** the POS_COLUMN or POS_END that terminates the column-list.
118846 **
118847 ** If pp is not NULL, then the contents of the column-list are copied
118848 ** to *pp. *pp is set to point to the first byte past the last byte copied
118849 ** before this function returns.  The POS_COLUMN or POS_END terminator
118850 ** is not copied into *pp.
118851 */
118852 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
118853   char *pEnd = *ppPoslist;
118854   char c = 0;
118855
118856   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
118857   ** not part of a multi-byte varint.
118858   */
118859   while( 0xFE & (*pEnd | c) ){
118860     c = *pEnd++ & 0x80;
118861     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
118862   }
118863   if( pp ){
118864     int n = (int)(pEnd - *ppPoslist);
118865     char *p = *pp;
118866     memcpy(p, *ppPoslist, n);
118867     p += n;
118868     *pp = p;
118869   }
118870   *ppPoslist = pEnd;
118871 }
118872
118873 /*
118874 ** Value used to signify the end of an position-list. This is safe because
118875 ** it is not possible to have a document with 2^31 terms.
118876 */
118877 #define POSITION_LIST_END 0x7fffffff
118878
118879 /*
118880 ** This function is used to help parse position-lists. When this function is
118881 ** called, *pp may point to the start of the next varint in the position-list
118882 ** being parsed, or it may point to 1 byte past the end of the position-list
118883 ** (in which case **pp will be a terminator bytes POS_END (0) or
118884 ** (1)).
118885 **
118886 ** If *pp points past the end of the current position-list, set *pi to 
118887 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
118888 ** increment the current value of *pi by the value read, and set *pp to
118889 ** point to the next value before returning.
118890 **
118891 ** Before calling this routine *pi must be initialized to the value of
118892 ** the previous position, or zero if we are reading the first position
118893 ** in the position-list.  Because positions are delta-encoded, the value
118894 ** of the previous position is needed in order to compute the value of
118895 ** the next position.
118896 */
118897 static void fts3ReadNextPos(
118898   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
118899   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
118900 ){
118901   if( (**pp)&0xFE ){
118902     fts3GetDeltaVarint(pp, pi);
118903     *pi -= 2;
118904   }else{
118905     *pi = POSITION_LIST_END;
118906   }
118907 }
118908
118909 /*
118910 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
118911 ** the value of iCol encoded as a varint to *pp.   This will start a new
118912 ** column list.
118913 **
118914 ** Set *pp to point to the byte just after the last byte written before 
118915 ** returning (do not modify it if iCol==0). Return the total number of bytes
118916 ** written (0 if iCol==0).
118917 */
118918 static int fts3PutColNumber(char **pp, int iCol){
118919   int n = 0;                      /* Number of bytes written */
118920   if( iCol ){
118921     char *p = *pp;                /* Output pointer */
118922     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
118923     *p = 0x01;
118924     *pp = &p[n];
118925   }
118926   return n;
118927 }
118928
118929 /*
118930 ** Compute the union of two position lists.  The output written
118931 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
118932 ** order and with any duplicates removed.  All pointers are
118933 ** updated appropriately.   The caller is responsible for insuring
118934 ** that there is enough space in *pp to hold the complete output.
118935 */
118936 static void fts3PoslistMerge(
118937   char **pp,                      /* Output buffer */
118938   char **pp1,                     /* Left input list */
118939   char **pp2                      /* Right input list */
118940 ){
118941   char *p = *pp;
118942   char *p1 = *pp1;
118943   char *p2 = *pp2;
118944
118945   while( *p1 || *p2 ){
118946     int iCol1;         /* The current column index in pp1 */
118947     int iCol2;         /* The current column index in pp2 */
118948
118949     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
118950     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
118951     else iCol1 = 0;
118952
118953     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
118954     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
118955     else iCol2 = 0;
118956
118957     if( iCol1==iCol2 ){
118958       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
118959       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
118960       sqlite3_int64 iPrev = 0;
118961       int n = fts3PutColNumber(&p, iCol1);
118962       p1 += n;
118963       p2 += n;
118964
118965       /* At this point, both p1 and p2 point to the start of column-lists
118966       ** for the same column (the column with index iCol1 and iCol2).
118967       ** A column-list is a list of non-negative delta-encoded varints, each 
118968       ** incremented by 2 before being stored. Each list is terminated by a
118969       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
118970       ** and writes the results to buffer p. p is left pointing to the byte
118971       ** after the list written. No terminator (POS_END or POS_COLUMN) is
118972       ** written to the output.
118973       */
118974       fts3GetDeltaVarint(&p1, &i1);
118975       fts3GetDeltaVarint(&p2, &i2);
118976       do {
118977         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
118978         iPrev -= 2;
118979         if( i1==i2 ){
118980           fts3ReadNextPos(&p1, &i1);
118981           fts3ReadNextPos(&p2, &i2);
118982         }else if( i1<i2 ){
118983           fts3ReadNextPos(&p1, &i1);
118984         }else{
118985           fts3ReadNextPos(&p2, &i2);
118986         }
118987       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
118988     }else if( iCol1<iCol2 ){
118989       p1 += fts3PutColNumber(&p, iCol1);
118990       fts3ColumnlistCopy(&p, &p1);
118991     }else{
118992       p2 += fts3PutColNumber(&p, iCol2);
118993       fts3ColumnlistCopy(&p, &p2);
118994     }
118995   }
118996
118997   *p++ = POS_END;
118998   *pp = p;
118999   *pp1 = p1 + 1;
119000   *pp2 = p2 + 1;
119001 }
119002
119003 /*
119004 ** This function is used to merge two position lists into one. When it is
119005 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
119006 ** the part of a doclist that follows each document id. For example, if a row
119007 ** contains:
119008 **
119009 **     'a b c'|'x y z'|'a b b a'
119010 **
119011 ** Then the position list for this row for token 'b' would consist of:
119012 **
119013 **     0x02 0x01 0x02 0x03 0x03 0x00
119014 **
119015 ** When this function returns, both *pp1 and *pp2 are left pointing to the
119016 ** byte following the 0x00 terminator of their respective position lists.
119017 **
119018 ** If isSaveLeft is 0, an entry is added to the output position list for 
119019 ** each position in *pp2 for which there exists one or more positions in
119020 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
119021 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
119022 ** slots before it.
119023 **
119024 ** e.g. nToken==1 searches for adjacent positions.
119025 */
119026 static int fts3PoslistPhraseMerge(
119027   char **pp,                      /* IN/OUT: Preallocated output buffer */
119028   int nToken,                     /* Maximum difference in token positions */
119029   int isSaveLeft,                 /* Save the left position */
119030   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
119031   char **pp1,                     /* IN/OUT: Left input list */
119032   char **pp2                      /* IN/OUT: Right input list */
119033 ){
119034   char *p = *pp;
119035   char *p1 = *pp1;
119036   char *p2 = *pp2;
119037   int iCol1 = 0;
119038   int iCol2 = 0;
119039
119040   /* Never set both isSaveLeft and isExact for the same invocation. */
119041   assert( isSaveLeft==0 || isExact==0 );
119042
119043   assert( p!=0 && *p1!=0 && *p2!=0 );
119044   if( *p1==POS_COLUMN ){ 
119045     p1++;
119046     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119047   }
119048   if( *p2==POS_COLUMN ){ 
119049     p2++;
119050     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119051   }
119052
119053   while( 1 ){
119054     if( iCol1==iCol2 ){
119055       char *pSave = p;
119056       sqlite3_int64 iPrev = 0;
119057       sqlite3_int64 iPos1 = 0;
119058       sqlite3_int64 iPos2 = 0;
119059
119060       if( iCol1 ){
119061         *p++ = POS_COLUMN;
119062         p += sqlite3Fts3PutVarint(p, iCol1);
119063       }
119064
119065       assert( *p1!=POS_END && *p1!=POS_COLUMN );
119066       assert( *p2!=POS_END && *p2!=POS_COLUMN );
119067       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119068       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119069
119070       while( 1 ){
119071         if( iPos2==iPos1+nToken 
119072          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
119073         ){
119074           sqlite3_int64 iSave;
119075           iSave = isSaveLeft ? iPos1 : iPos2;
119076           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
119077           pSave = 0;
119078           assert( p );
119079         }
119080         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
119081           if( (*p2&0xFE)==0 ) break;
119082           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119083         }else{
119084           if( (*p1&0xFE)==0 ) break;
119085           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119086         }
119087       }
119088
119089       if( pSave ){
119090         assert( pp && p );
119091         p = pSave;
119092       }
119093
119094       fts3ColumnlistCopy(0, &p1);
119095       fts3ColumnlistCopy(0, &p2);
119096       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
119097       if( 0==*p1 || 0==*p2 ) break;
119098
119099       p1++;
119100       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119101       p2++;
119102       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119103     }
119104
119105     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
119106     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
119107     ** end of the position list, or the 0x01 that precedes the next 
119108     ** column-number in the position list. 
119109     */
119110     else if( iCol1<iCol2 ){
119111       fts3ColumnlistCopy(0, &p1);
119112       if( 0==*p1 ) break;
119113       p1++;
119114       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119115     }else{
119116       fts3ColumnlistCopy(0, &p2);
119117       if( 0==*p2 ) break;
119118       p2++;
119119       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119120     }
119121   }
119122
119123   fts3PoslistCopy(0, &p2);
119124   fts3PoslistCopy(0, &p1);
119125   *pp1 = p1;
119126   *pp2 = p2;
119127   if( *pp==p ){
119128     return 0;
119129   }
119130   *p++ = 0x00;
119131   *pp = p;
119132   return 1;
119133 }
119134
119135 /*
119136 ** Merge two position-lists as required by the NEAR operator. The argument
119137 ** position lists correspond to the left and right phrases of an expression 
119138 ** like:
119139 **
119140 **     "phrase 1" NEAR "phrase number 2"
119141 **
119142 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
119143 ** expression and *pp2 to the right. As usual, the indexes in the position 
119144 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
119145 ** in the example above).
119146 **
119147 ** The output position list - written to *pp - is a copy of *pp2 with those
119148 ** entries that are not sufficiently NEAR entries in *pp1 removed.
119149 */
119150 static int fts3PoslistNearMerge(
119151   char **pp,                      /* Output buffer */
119152   char *aTmp,                     /* Temporary buffer space */
119153   int nRight,                     /* Maximum difference in token positions */
119154   int nLeft,                      /* Maximum difference in token positions */
119155   char **pp1,                     /* IN/OUT: Left input list */
119156   char **pp2                      /* IN/OUT: Right input list */
119157 ){
119158   char *p1 = *pp1;
119159   char *p2 = *pp2;
119160
119161   char *pTmp1 = aTmp;
119162   char *pTmp2;
119163   char *aTmp2;
119164   int res = 1;
119165
119166   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
119167   aTmp2 = pTmp2 = pTmp1;
119168   *pp1 = p1;
119169   *pp2 = p2;
119170   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
119171   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
119172     fts3PoslistMerge(pp, &aTmp, &aTmp2);
119173   }else if( pTmp1!=aTmp ){
119174     fts3PoslistCopy(pp, &aTmp);
119175   }else if( pTmp2!=aTmp2 ){
119176     fts3PoslistCopy(pp, &aTmp2);
119177   }else{
119178     res = 0;
119179   }
119180
119181   return res;
119182 }
119183
119184 /* 
119185 ** An instance of this function is used to merge together the (potentially
119186 ** large number of) doclists for each term that matches a prefix query.
119187 ** See function fts3TermSelectMerge() for details.
119188 */
119189 typedef struct TermSelect TermSelect;
119190 struct TermSelect {
119191   char *aaOutput[16];             /* Malloc'd output buffers */
119192   int anOutput[16];               /* Size each output buffer in bytes */
119193 };
119194
119195 /*
119196 ** This function is used to read a single varint from a buffer. Parameter
119197 ** pEnd points 1 byte past the end of the buffer. When this function is
119198 ** called, if *pp points to pEnd or greater, then the end of the buffer
119199 ** has been reached. In this case *pp is set to 0 and the function returns.
119200 **
119201 ** If *pp does not point to or past pEnd, then a single varint is read
119202 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
119203 **
119204 ** If bDescIdx is false, the value read is added to *pVal before returning.
119205 ** If it is true, the value read is subtracted from *pVal before this 
119206 ** function returns.
119207 */
119208 static void fts3GetDeltaVarint3(
119209   char **pp,                      /* IN/OUT: Point to read varint from */
119210   char *pEnd,                     /* End of buffer */
119211   int bDescIdx,                   /* True if docids are descending */
119212   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
119213 ){
119214   if( *pp>=pEnd ){
119215     *pp = 0;
119216   }else{
119217     sqlite3_int64 iVal;
119218     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119219     if( bDescIdx ){
119220       *pVal -= iVal;
119221     }else{
119222       *pVal += iVal;
119223     }
119224   }
119225 }
119226
119227 /*
119228 ** This function is used to write a single varint to a buffer. The varint
119229 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
119230 ** end of the value written.
119231 **
119232 ** If *pbFirst is zero when this function is called, the value written to
119233 ** the buffer is that of parameter iVal. 
119234 **
119235 ** If *pbFirst is non-zero when this function is called, then the value 
119236 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
119237 ** (if bDescIdx is non-zero).
119238 **
119239 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
119240 ** to the value of parameter iVal.
119241 */
119242 static void fts3PutDeltaVarint3(
119243   char **pp,                      /* IN/OUT: Output pointer */
119244   int bDescIdx,                   /* True for descending docids */
119245   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119246   int *pbFirst,                   /* IN/OUT: True after first int written */
119247   sqlite3_int64 iVal              /* Write this value to the list */
119248 ){
119249   sqlite3_int64 iWrite;
119250   if( bDescIdx==0 || *pbFirst==0 ){
119251     iWrite = iVal - *piPrev;
119252   }else{
119253     iWrite = *piPrev - iVal;
119254   }
119255   assert( *pbFirst || *piPrev==0 );
119256   assert( *pbFirst==0 || iWrite>0 );
119257   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
119258   *piPrev = iVal;
119259   *pbFirst = 1;
119260 }
119261
119262
119263 /*
119264 ** This macro is used by various functions that merge doclists. The two
119265 ** arguments are 64-bit docid values. If the value of the stack variable
119266 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
119267 ** Otherwise, (i2-i1).
119268 **
119269 ** Using this makes it easier to write code that can merge doclists that are
119270 ** sorted in either ascending or descending order.
119271 */
119272 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
119273
119274 /*
119275 ** This function does an "OR" merge of two doclists (output contains all
119276 ** positions contained in either argument doclist). If the docids in the 
119277 ** input doclists are sorted in ascending order, parameter bDescDoclist
119278 ** should be false. If they are sorted in ascending order, it should be
119279 ** passed a non-zero value.
119280 **
119281 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
119282 ** containing the output doclist and SQLITE_OK is returned. In this case
119283 ** *pnOut is set to the number of bytes in the output doclist.
119284 **
119285 ** If an error occurs, an SQLite error code is returned. The output values
119286 ** are undefined in this case.
119287 */
119288 static int fts3DoclistOrMerge(
119289   int bDescDoclist,               /* True if arguments are desc */
119290   char *a1, int n1,               /* First doclist */
119291   char *a2, int n2,               /* Second doclist */
119292   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
119293 ){
119294   sqlite3_int64 i1 = 0;
119295   sqlite3_int64 i2 = 0;
119296   sqlite3_int64 iPrev = 0;
119297   char *pEnd1 = &a1[n1];
119298   char *pEnd2 = &a2[n2];
119299   char *p1 = a1;
119300   char *p2 = a2;
119301   char *p;
119302   char *aOut;
119303   int bFirstOut = 0;
119304
119305   *paOut = 0;
119306   *pnOut = 0;
119307
119308   /* Allocate space for the output. Both the input and output doclists
119309   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
119310   ** then the first docid in each list is simply encoded as a varint. For
119311   ** each subsequent docid, the varint stored is the difference between the
119312   ** current and previous docid (a positive number - since the list is in
119313   ** ascending order).
119314   **
119315   ** The first docid written to the output is therefore encoded using the 
119316   ** same number of bytes as it is in whichever of the input lists it is
119317   ** read from. And each subsequent docid read from the same input list 
119318   ** consumes either the same or less bytes as it did in the input (since
119319   ** the difference between it and the previous value in the output must
119320   ** be a positive value less than or equal to the delta value read from 
119321   ** the input list). The same argument applies to all but the first docid
119322   ** read from the 'other' list. And to the contents of all position lists
119323   ** that will be copied and merged from the input to the output.
119324   **
119325   ** However, if the first docid copied to the output is a negative number,
119326   ** then the encoding of the first docid from the 'other' input list may
119327   ** be larger in the output than it was in the input (since the delta value
119328   ** may be a larger positive integer than the actual docid).
119329   **
119330   ** The space required to store the output is therefore the sum of the
119331   ** sizes of the two inputs, plus enough space for exactly one of the input
119332   ** docids to grow. 
119333   **
119334   ** A symetric argument may be made if the doclists are in descending 
119335   ** order.
119336   */
119337   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
119338   if( !aOut ) return SQLITE_NOMEM;
119339
119340   p = aOut;
119341   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
119342   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
119343   while( p1 || p2 ){
119344     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
119345
119346     if( p2 && p1 && iDiff==0 ){
119347       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
119348       fts3PoslistMerge(&p, &p1, &p2);
119349       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119350       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119351     }else if( !p2 || (p1 && iDiff<0) ){
119352       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
119353       fts3PoslistCopy(&p, &p1);
119354       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119355     }else{
119356       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
119357       fts3PoslistCopy(&p, &p2);
119358       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119359     }
119360   }
119361
119362   *paOut = aOut;
119363   *pnOut = (int)(p-aOut);
119364   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
119365   return SQLITE_OK;
119366 }
119367
119368 /*
119369 ** This function does a "phrase" merge of two doclists. In a phrase merge,
119370 ** the output contains a copy of each position from the right-hand input
119371 ** doclist for which there is a position in the left-hand input doclist
119372 ** exactly nDist tokens before it.
119373 **
119374 ** If the docids in the input doclists are sorted in ascending order,
119375 ** parameter bDescDoclist should be false. If they are sorted in ascending 
119376 ** order, it should be passed a non-zero value.
119377 **
119378 ** The right-hand input doclist is overwritten by this function.
119379 */
119380 static void fts3DoclistPhraseMerge(
119381   int bDescDoclist,               /* True if arguments are desc */
119382   int nDist,                      /* Distance from left to right (1=adjacent) */
119383   char *aLeft, int nLeft,         /* Left doclist */
119384   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
119385 ){
119386   sqlite3_int64 i1 = 0;
119387   sqlite3_int64 i2 = 0;
119388   sqlite3_int64 iPrev = 0;
119389   char *pEnd1 = &aLeft[nLeft];
119390   char *pEnd2 = &aRight[*pnRight];
119391   char *p1 = aLeft;
119392   char *p2 = aRight;
119393   char *p;
119394   int bFirstOut = 0;
119395   char *aOut = aRight;
119396
119397   assert( nDist>0 );
119398
119399   p = aOut;
119400   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
119401   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
119402
119403   while( p1 && p2 ){
119404     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
119405     if( iDiff==0 ){
119406       char *pSave = p;
119407       sqlite3_int64 iPrevSave = iPrev;
119408       int bFirstOutSave = bFirstOut;
119409
119410       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
119411       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
119412         p = pSave;
119413         iPrev = iPrevSave;
119414         bFirstOut = bFirstOutSave;
119415       }
119416       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119417       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119418     }else if( iDiff<0 ){
119419       fts3PoslistCopy(0, &p1);
119420       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119421     }else{
119422       fts3PoslistCopy(0, &p2);
119423       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119424     }
119425   }
119426
119427   *pnRight = (int)(p - aOut);
119428 }
119429
119430 /*
119431 ** Argument pList points to a position list nList bytes in size. This
119432 ** function checks to see if the position list contains any entries for
119433 ** a token in position 0 (of any column). If so, it writes argument iDelta
119434 ** to the output buffer pOut, followed by a position list consisting only
119435 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
119436 ** The value returned is the number of bytes written to pOut (if any).
119437 */
119438 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
119439   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
119440   char *pList,                    /* Position list (no 0x00 term) */
119441   int nList,                      /* Size of pList in bytes */
119442   char *pOut                      /* Write output here */
119443 ){
119444   int nOut = 0;
119445   int bWritten = 0;               /* True once iDelta has been written */
119446   char *p = pList;
119447   char *pEnd = &pList[nList];
119448
119449   if( *p!=0x01 ){
119450     if( *p==0x02 ){
119451       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119452       pOut[nOut++] = 0x02;
119453       bWritten = 1;
119454     }
119455     fts3ColumnlistCopy(0, &p);
119456   }
119457
119458   while( p<pEnd && *p==0x01 ){
119459     sqlite3_int64 iCol;
119460     p++;
119461     p += sqlite3Fts3GetVarint(p, &iCol);
119462     if( *p==0x02 ){
119463       if( bWritten==0 ){
119464         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119465         bWritten = 1;
119466       }
119467       pOut[nOut++] = 0x01;
119468       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
119469       pOut[nOut++] = 0x02;
119470     }
119471     fts3ColumnlistCopy(0, &p);
119472   }
119473   if( bWritten ){
119474     pOut[nOut++] = 0x00;
119475   }
119476
119477   return nOut;
119478 }
119479
119480
119481 /*
119482 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
119483 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
119484 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
119485 **
119486 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
119487 ** the responsibility of the caller to free any doclists left in the
119488 ** TermSelect.aaOutput[] array.
119489 */
119490 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
119491   char *aOut = 0;
119492   int nOut = 0;
119493   int i;
119494
119495   /* Loop through the doclists in the aaOutput[] array. Merge them all
119496   ** into a single doclist.
119497   */
119498   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
119499     if( pTS->aaOutput[i] ){
119500       if( !aOut ){
119501         aOut = pTS->aaOutput[i];
119502         nOut = pTS->anOutput[i];
119503         pTS->aaOutput[i] = 0;
119504       }else{
119505         int nNew;
119506         char *aNew;
119507
119508         int rc = fts3DoclistOrMerge(p->bDescIdx, 
119509             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
119510         );
119511         if( rc!=SQLITE_OK ){
119512           sqlite3_free(aOut);
119513           return rc;
119514         }
119515
119516         sqlite3_free(pTS->aaOutput[i]);
119517         sqlite3_free(aOut);
119518         pTS->aaOutput[i] = 0;
119519         aOut = aNew;
119520         nOut = nNew;
119521       }
119522     }
119523   }
119524
119525   pTS->aaOutput[0] = aOut;
119526   pTS->anOutput[0] = nOut;
119527   return SQLITE_OK;
119528 }
119529
119530 /*
119531 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
119532 ** as the first argument. The merge is an "OR" merge (see function
119533 ** fts3DoclistOrMerge() for details).
119534 **
119535 ** This function is called with the doclist for each term that matches
119536 ** a queried prefix. It merges all these doclists into one, the doclist
119537 ** for the specified prefix. Since there can be a very large number of
119538 ** doclists to merge, the merging is done pair-wise using the TermSelect
119539 ** object.
119540 **
119541 ** This function returns SQLITE_OK if the merge is successful, or an
119542 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
119543 */
119544 static int fts3TermSelectMerge(
119545   Fts3Table *p,                   /* FTS table handle */
119546   TermSelect *pTS,                /* TermSelect object to merge into */
119547   char *aDoclist,                 /* Pointer to doclist */
119548   int nDoclist                    /* Size of aDoclist in bytes */
119549 ){
119550   if( pTS->aaOutput[0]==0 ){
119551     /* If this is the first term selected, copy the doclist to the output
119552     ** buffer using memcpy(). */
119553     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
119554     pTS->anOutput[0] = nDoclist;
119555     if( pTS->aaOutput[0] ){
119556       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
119557     }else{
119558       return SQLITE_NOMEM;
119559     }
119560   }else{
119561     char *aMerge = aDoclist;
119562     int nMerge = nDoclist;
119563     int iOut;
119564
119565     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
119566       if( pTS->aaOutput[iOut]==0 ){
119567         assert( iOut>0 );
119568         pTS->aaOutput[iOut] = aMerge;
119569         pTS->anOutput[iOut] = nMerge;
119570         break;
119571       }else{
119572         char *aNew;
119573         int nNew;
119574
119575         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
119576             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
119577         );
119578         if( rc!=SQLITE_OK ){
119579           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119580           return rc;
119581         }
119582
119583         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119584         sqlite3_free(pTS->aaOutput[iOut]);
119585         pTS->aaOutput[iOut] = 0;
119586   
119587         aMerge = aNew;
119588         nMerge = nNew;
119589         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
119590           pTS->aaOutput[iOut] = aMerge;
119591           pTS->anOutput[iOut] = nMerge;
119592         }
119593       }
119594     }
119595   }
119596   return SQLITE_OK;
119597 }
119598
119599 /*
119600 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
119601 */
119602 static int fts3SegReaderCursorAppend(
119603   Fts3MultiSegReader *pCsr, 
119604   Fts3SegReader *pNew
119605 ){
119606   if( (pCsr->nSegment%16)==0 ){
119607     Fts3SegReader **apNew;
119608     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
119609     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
119610     if( !apNew ){
119611       sqlite3Fts3SegReaderFree(pNew);
119612       return SQLITE_NOMEM;
119613     }
119614     pCsr->apSegment = apNew;
119615   }
119616   pCsr->apSegment[pCsr->nSegment++] = pNew;
119617   return SQLITE_OK;
119618 }
119619
119620 /*
119621 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
119622 ** 8th argument.
119623 **
119624 ** This function returns SQLITE_OK if successful, or an SQLite error code
119625 ** otherwise.
119626 */
119627 static int fts3SegReaderCursor(
119628   Fts3Table *p,                   /* FTS3 table handle */
119629   int iLangid,                    /* Language id */
119630   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119631   int iLevel,                     /* Level of segments to scan */
119632   const char *zTerm,              /* Term to query for */
119633   int nTerm,                      /* Size of zTerm in bytes */
119634   int isPrefix,                   /* True for a prefix search */
119635   int isScan,                     /* True to scan from zTerm to EOF */
119636   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
119637 ){
119638   int rc = SQLITE_OK;             /* Error code */
119639   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
119640   int rc2;                        /* Result of sqlite3_reset() */
119641
119642   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
119643   ** for the pending-terms. If this is a scan, then this call must be being
119644   ** made by an fts4aux module, not an FTS table. In this case calling
119645   ** Fts3SegReaderPending might segfault, as the data structures used by 
119646   ** fts4aux are not completely populated. So it's easiest to filter these
119647   ** calls out here.  */
119648   if( iLevel<0 && p->aIndex ){
119649     Fts3SegReader *pSeg = 0;
119650     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
119651     if( rc==SQLITE_OK && pSeg ){
119652       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119653     }
119654   }
119655
119656   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
119657     if( rc==SQLITE_OK ){
119658       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
119659     }
119660
119661     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
119662       Fts3SegReader *pSeg = 0;
119663
119664       /* Read the values returned by the SELECT into local variables. */
119665       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
119666       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
119667       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
119668       int nRoot = sqlite3_column_bytes(pStmt, 4);
119669       char const *zRoot = sqlite3_column_blob(pStmt, 4);
119670
119671       /* If zTerm is not NULL, and this segment is not stored entirely on its
119672       ** root node, the range of leaves scanned can be reduced. Do this. */
119673       if( iStartBlock && zTerm ){
119674         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
119675         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
119676         if( rc!=SQLITE_OK ) goto finished;
119677         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
119678       }
119679  
119680       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
119681           (isPrefix==0 && isScan==0),
119682           iStartBlock, iLeavesEndBlock, 
119683           iEndBlock, zRoot, nRoot, &pSeg
119684       );
119685       if( rc!=SQLITE_OK ) goto finished;
119686       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119687     }
119688   }
119689
119690  finished:
119691   rc2 = sqlite3_reset(pStmt);
119692   if( rc==SQLITE_DONE ) rc = rc2;
119693
119694   return rc;
119695 }
119696
119697 /*
119698 ** Set up a cursor object for iterating through a full-text index or a 
119699 ** single level therein.
119700 */
119701 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
119702   Fts3Table *p,                   /* FTS3 table handle */
119703   int iLangid,                    /* Language-id to search */
119704   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119705   int iLevel,                     /* Level of segments to scan */
119706   const char *zTerm,              /* Term to query for */
119707   int nTerm,                      /* Size of zTerm in bytes */
119708   int isPrefix,                   /* True for a prefix search */
119709   int isScan,                     /* True to scan from zTerm to EOF */
119710   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
119711 ){
119712   assert( iIndex>=0 && iIndex<p->nIndex );
119713   assert( iLevel==FTS3_SEGCURSOR_ALL
119714       ||  iLevel==FTS3_SEGCURSOR_PENDING 
119715       ||  iLevel>=0
119716   );
119717   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
119718   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
119719   assert( isPrefix==0 || isScan==0 );
119720
119721   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
119722   return fts3SegReaderCursor(
119723       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
119724   );
119725 }
119726
119727 /*
119728 ** In addition to its current configuration, have the Fts3MultiSegReader
119729 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
119730 **
119731 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119732 */
119733 static int fts3SegReaderCursorAddZero(
119734   Fts3Table *p,                   /* FTS virtual table handle */
119735   int iLangid,
119736   const char *zTerm,              /* Term to scan doclist of */
119737   int nTerm,                      /* Number of bytes in zTerm */
119738   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
119739 ){
119740   return fts3SegReaderCursor(p, 
119741       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
119742   );
119743 }
119744
119745 /*
119746 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
119747 ** if isPrefix is true, to scan the doclist for all terms for which 
119748 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
119749 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
119750 ** an SQLite error code.
119751 **
119752 ** It is the responsibility of the caller to free this object by eventually
119753 ** passing it to fts3SegReaderCursorFree() 
119754 **
119755 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119756 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
119757 */
119758 static int fts3TermSegReaderCursor(
119759   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
119760   const char *zTerm,              /* Term to query for */
119761   int nTerm,                      /* Size of zTerm in bytes */
119762   int isPrefix,                   /* True for a prefix search */
119763   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
119764 ){
119765   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
119766   int rc = SQLITE_NOMEM;          /* Return code */
119767
119768   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
119769   if( pSegcsr ){
119770     int i;
119771     int bFound = 0;               /* True once an index has been found */
119772     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119773
119774     if( isPrefix ){
119775       for(i=1; bFound==0 && i<p->nIndex; i++){
119776         if( p->aIndex[i].nPrefix==nTerm ){
119777           bFound = 1;
119778           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
119779               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
119780           );
119781           pSegcsr->bLookup = 1;
119782         }
119783       }
119784
119785       for(i=1; bFound==0 && i<p->nIndex; i++){
119786         if( p->aIndex[i].nPrefix==nTerm+1 ){
119787           bFound = 1;
119788           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
119789               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
119790           );
119791           if( rc==SQLITE_OK ){
119792             rc = fts3SegReaderCursorAddZero(
119793                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
119794             );
119795           }
119796         }
119797       }
119798     }
119799
119800     if( bFound==0 ){
119801       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
119802           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
119803       );
119804       pSegcsr->bLookup = !isPrefix;
119805     }
119806   }
119807
119808   *ppSegcsr = pSegcsr;
119809   return rc;
119810 }
119811
119812 /*
119813 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
119814 */
119815 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
119816   sqlite3Fts3SegReaderFinish(pSegcsr);
119817   sqlite3_free(pSegcsr);
119818 }
119819
119820 /*
119821 ** This function retreives the doclist for the specified term (or term
119822 ** prefix) from the database.
119823 */
119824 static int fts3TermSelect(
119825   Fts3Table *p,                   /* Virtual table handle */
119826   Fts3PhraseToken *pTok,          /* Token to query for */
119827   int iColumn,                    /* Column to query (or -ve for all columns) */
119828   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
119829   char **ppOut                    /* OUT: Malloced result buffer */
119830 ){
119831   int rc;                         /* Return code */
119832   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
119833   TermSelect tsc;                 /* Object for pair-wise doclist merging */
119834   Fts3SegFilter filter;           /* Segment term filter configuration */
119835
119836   pSegcsr = pTok->pSegcsr;
119837   memset(&tsc, 0, sizeof(TermSelect));
119838
119839   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
119840         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
119841         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
119842         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
119843   filter.iCol = iColumn;
119844   filter.zTerm = pTok->z;
119845   filter.nTerm = pTok->n;
119846
119847   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
119848   while( SQLITE_OK==rc
119849       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
119850   ){
119851     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
119852   }
119853
119854   if( rc==SQLITE_OK ){
119855     rc = fts3TermSelectFinishMerge(p, &tsc);
119856   }
119857   if( rc==SQLITE_OK ){
119858     *ppOut = tsc.aaOutput[0];
119859     *pnOut = tsc.anOutput[0];
119860   }else{
119861     int i;
119862     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
119863       sqlite3_free(tsc.aaOutput[i]);
119864     }
119865   }
119866
119867   fts3SegReaderCursorFree(pSegcsr);
119868   pTok->pSegcsr = 0;
119869   return rc;
119870 }
119871
119872 /*
119873 ** This function counts the total number of docids in the doclist stored
119874 ** in buffer aList[], size nList bytes.
119875 **
119876 ** If the isPoslist argument is true, then it is assumed that the doclist
119877 ** contains a position-list following each docid. Otherwise, it is assumed
119878 ** that the doclist is simply a list of docids stored as delta encoded 
119879 ** varints.
119880 */
119881 static int fts3DoclistCountDocids(char *aList, int nList){
119882   int nDoc = 0;                   /* Return value */
119883   if( aList ){
119884     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
119885     char *p = aList;              /* Cursor */
119886     while( p<aEnd ){
119887       nDoc++;
119888       while( (*p++)&0x80 );     /* Skip docid varint */
119889       fts3PoslistCopy(0, &p);   /* Skip over position list */
119890     }
119891   }
119892
119893   return nDoc;
119894 }
119895
119896 /*
119897 ** Advance the cursor to the next row in the %_content table that
119898 ** matches the search criteria.  For a MATCH search, this will be
119899 ** the next row that matches. For a full-table scan, this will be
119900 ** simply the next row in the %_content table.  For a docid lookup,
119901 ** this routine simply sets the EOF flag.
119902 **
119903 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
119904 ** even if we reach end-of-file.  The fts3EofMethod() will be called
119905 ** subsequently to determine whether or not an EOF was hit.
119906 */
119907 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
119908   int rc;
119909   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119910   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
119911     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
119912       pCsr->isEof = 1;
119913       rc = sqlite3_reset(pCsr->pStmt);
119914     }else{
119915       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
119916       rc = SQLITE_OK;
119917     }
119918   }else{
119919     rc = fts3EvalNext((Fts3Cursor *)pCursor);
119920   }
119921   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119922   return rc;
119923 }
119924
119925 /*
119926 ** This is the xFilter interface for the virtual table.  See
119927 ** the virtual table xFilter method documentation for additional
119928 ** information.
119929 **
119930 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
119931 ** the %_content table.
119932 **
119933 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
119934 ** in the %_content table.
119935 **
119936 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
119937 ** column on the left-hand side of the MATCH operator is column
119938 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
119939 ** side of the MATCH operator.
119940 */
119941 static int fts3FilterMethod(
119942   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
119943   int idxNum,                     /* Strategy index */
119944   const char *idxStr,             /* Unused */
119945   int nVal,                       /* Number of elements in apVal */
119946   sqlite3_value **apVal           /* Arguments for the indexing scheme */
119947 ){
119948   int rc;
119949   char *zSql;                     /* SQL statement used to access %_content */
119950   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119951   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119952
119953   UNUSED_PARAMETER(idxStr);
119954   UNUSED_PARAMETER(nVal);
119955
119956   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
119957   assert( nVal==0 || nVal==1 || nVal==2 );
119958   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
119959   assert( p->pSegments==0 );
119960
119961   /* In case the cursor has been used before, clear it now. */
119962   sqlite3_finalize(pCsr->pStmt);
119963   sqlite3_free(pCsr->aDoclist);
119964   sqlite3Fts3ExprFree(pCsr->pExpr);
119965   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
119966
119967   if( idxStr ){
119968     pCsr->bDesc = (idxStr[0]=='D');
119969   }else{
119970     pCsr->bDesc = p->bDescIdx;
119971   }
119972   pCsr->eSearch = (i16)idxNum;
119973
119974   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
119975     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
119976     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
119977
119978     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
119979       return SQLITE_NOMEM;
119980     }
119981
119982     pCsr->iLangid = 0;
119983     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
119984
119985     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
119986         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
119987     );
119988     if( rc!=SQLITE_OK ){
119989       if( rc==SQLITE_ERROR ){
119990         static const char *zErr = "malformed MATCH expression: [%s]";
119991         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
119992       }
119993       return rc;
119994     }
119995
119996     rc = sqlite3Fts3ReadLock(p);
119997     if( rc!=SQLITE_OK ) return rc;
119998
119999     rc = fts3EvalStart(pCsr);
120000
120001     sqlite3Fts3SegmentsClose(p);
120002     if( rc!=SQLITE_OK ) return rc;
120003     pCsr->pNextId = pCsr->aDoclist;
120004     pCsr->iPrevId = 0;
120005   }
120006
120007   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
120008   ** statement loops through all rows of the %_content table. For a
120009   ** full-text query or docid lookup, the statement retrieves a single
120010   ** row by docid.
120011   */
120012   if( idxNum==FTS3_FULLSCAN_SEARCH ){
120013     zSql = sqlite3_mprintf(
120014         "SELECT %s ORDER BY rowid %s",
120015         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
120016     );
120017     if( zSql ){
120018       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120019       sqlite3_free(zSql);
120020     }else{
120021       rc = SQLITE_NOMEM;
120022     }
120023   }else if( idxNum==FTS3_DOCID_SEARCH ){
120024     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
120025     if( rc==SQLITE_OK ){
120026       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
120027     }
120028   }
120029   if( rc!=SQLITE_OK ) return rc;
120030
120031   return fts3NextMethod(pCursor);
120032 }
120033
120034 /* 
120035 ** This is the xEof method of the virtual table. SQLite calls this 
120036 ** routine to find out if it has reached the end of a result set.
120037 */
120038 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
120039   return ((Fts3Cursor *)pCursor)->isEof;
120040 }
120041
120042 /* 
120043 ** This is the xRowid method. The SQLite core calls this routine to
120044 ** retrieve the rowid for the current row of the result set. fts3
120045 ** exposes %_content.docid as the rowid for the virtual table. The
120046 ** rowid should be written to *pRowid.
120047 */
120048 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
120049   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120050   *pRowid = pCsr->iPrevId;
120051   return SQLITE_OK;
120052 }
120053
120054 /* 
120055 ** This is the xColumn method, called by SQLite to request a value from
120056 ** the row that the supplied cursor currently points to.
120057 **
120058 ** If:
120059 **
120060 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
120061 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
120062 **   (iCol == p->nColumn+1) -> Docid column
120063 **   (iCol == p->nColumn+2) -> Langid column
120064 */
120065 static int fts3ColumnMethod(
120066   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
120067   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
120068   int iCol                        /* Index of column to read value from */
120069 ){
120070   int rc = SQLITE_OK;             /* Return Code */
120071   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120072   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120073
120074   /* The column value supplied by SQLite must be in range. */
120075   assert( iCol>=0 && iCol<=p->nColumn+2 );
120076
120077   if( iCol==p->nColumn+1 ){
120078     /* This call is a request for the "docid" column. Since "docid" is an 
120079     ** alias for "rowid", use the xRowid() method to obtain the value.
120080     */
120081     sqlite3_result_int64(pCtx, pCsr->iPrevId);
120082   }else if( iCol==p->nColumn ){
120083     /* The extra column whose name is the same as the table.
120084     ** Return a blob which is a pointer to the cursor.  */
120085     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
120086   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
120087     sqlite3_result_int64(pCtx, pCsr->iLangid);
120088   }else{
120089     /* The requested column is either a user column (one that contains 
120090     ** indexed data), or the language-id column.  */
120091     rc = fts3CursorSeek(0, pCsr);
120092
120093     if( rc==SQLITE_OK ){
120094       if( iCol==p->nColumn+2 ){
120095         int iLangid = 0;
120096         if( p->zLanguageid ){
120097           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
120098         }
120099         sqlite3_result_int(pCtx, iLangid);
120100       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
120101         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
120102       }
120103     }
120104   }
120105
120106   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120107   return rc;
120108 }
120109
120110 /* 
120111 ** This function is the implementation of the xUpdate callback used by 
120112 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
120113 ** inserted, updated or deleted.
120114 */
120115 static int fts3UpdateMethod(
120116   sqlite3_vtab *pVtab,            /* Virtual table handle */
120117   int nArg,                       /* Size of argument array */
120118   sqlite3_value **apVal,          /* Array of arguments */
120119   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120120 ){
120121   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
120122 }
120123
120124 /*
120125 ** Implementation of xSync() method. Flush the contents of the pending-terms
120126 ** hash-table to the database.
120127 */
120128 static int fts3SyncMethod(sqlite3_vtab *pVtab){
120129
120130   /* Following an incremental-merge operation, assuming that the input
120131   ** segments are not completely consumed (the usual case), they are updated
120132   ** in place to remove the entries that have already been merged. This
120133   ** involves updating the leaf block that contains the smallest unmerged
120134   ** entry and each block (if any) between the leaf and the root node. So
120135   ** if the height of the input segment b-trees is N, and input segments
120136   ** are merged eight at a time, updating the input segments at the end
120137   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
120138   ** small - often between 0 and 2. So the overhead of the incremental
120139   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
120140   ** dwarfing the actual productive work accomplished, the incremental merge
120141   ** is only attempted if it will write at least 64 leaf blocks. Hence
120142   ** nMinMerge.
120143   **
120144   ** Of course, updating the input segments also involves deleting a bunch
120145   ** of blocks from the segments table. But this is not considered overhead
120146   ** as it would also be required by a crisis-merge that used the same input 
120147   ** segments.
120148   */
120149   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
120150
120151   Fts3Table *p = (Fts3Table*)pVtab;
120152   int rc = sqlite3Fts3PendingTermsFlush(p);
120153
120154   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
120155     int mxLevel = 0;              /* Maximum relative level value in db */
120156     int A;                        /* Incr-merge parameter A */
120157
120158     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
120159     assert( rc==SQLITE_OK || mxLevel==0 );
120160     A = p->nLeafAdd * mxLevel;
120161     A += (A/2);
120162     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
120163   }
120164   sqlite3Fts3SegmentsClose(p);
120165   return rc;
120166 }
120167
120168 /*
120169 ** Implementation of xBegin() method. This is a no-op.
120170 */
120171 static int fts3BeginMethod(sqlite3_vtab *pVtab){
120172   Fts3Table *p = (Fts3Table*)pVtab;
120173   UNUSED_PARAMETER(pVtab);
120174   assert( p->pSegments==0 );
120175   assert( p->nPendingData==0 );
120176   assert( p->inTransaction!=1 );
120177   TESTONLY( p->inTransaction = 1 );
120178   TESTONLY( p->mxSavepoint = -1; );
120179   p->nLeafAdd = 0;
120180   return SQLITE_OK;
120181 }
120182
120183 /*
120184 ** Implementation of xCommit() method. This is a no-op. The contents of
120185 ** the pending-terms hash-table have already been flushed into the database
120186 ** by fts3SyncMethod().
120187 */
120188 static int fts3CommitMethod(sqlite3_vtab *pVtab){
120189   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120190   UNUSED_PARAMETER(pVtab);
120191   assert( p->nPendingData==0 );
120192   assert( p->inTransaction!=0 );
120193   assert( p->pSegments==0 );
120194   TESTONLY( p->inTransaction = 0 );
120195   TESTONLY( p->mxSavepoint = -1; );
120196   return SQLITE_OK;
120197 }
120198
120199 /*
120200 ** Implementation of xRollback(). Discard the contents of the pending-terms
120201 ** hash-table. Any changes made to the database are reverted by SQLite.
120202 */
120203 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
120204   Fts3Table *p = (Fts3Table*)pVtab;
120205   sqlite3Fts3PendingTermsClear(p);
120206   assert( p->inTransaction!=0 );
120207   TESTONLY( p->inTransaction = 0 );
120208   TESTONLY( p->mxSavepoint = -1; );
120209   return SQLITE_OK;
120210 }
120211
120212 /*
120213 ** When called, *ppPoslist must point to the byte immediately following the
120214 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
120215 ** moves *ppPoslist so that it instead points to the first byte of the
120216 ** same position list.
120217 */
120218 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
120219   char *p = &(*ppPoslist)[-2];
120220   char c = 0;
120221
120222   while( p>pStart && (c=*p--)==0 );
120223   while( p>pStart && (*p & 0x80) | c ){ 
120224     c = *p--; 
120225   }
120226   if( p>pStart ){ p = &p[2]; }
120227   while( *p++&0x80 );
120228   *ppPoslist = p;
120229 }
120230
120231 /*
120232 ** Helper function used by the implementation of the overloaded snippet(),
120233 ** offsets() and optimize() SQL functions.
120234 **
120235 ** If the value passed as the third argument is a blob of size
120236 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
120237 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
120238 ** message is written to context pContext and SQLITE_ERROR returned. The
120239 ** string passed via zFunc is used as part of the error message.
120240 */
120241 static int fts3FunctionArg(
120242   sqlite3_context *pContext,      /* SQL function call context */
120243   const char *zFunc,              /* Function name */
120244   sqlite3_value *pVal,            /* argv[0] passed to function */
120245   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
120246 ){
120247   Fts3Cursor *pRet;
120248   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
120249    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
120250   ){
120251     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
120252     sqlite3_result_error(pContext, zErr, -1);
120253     sqlite3_free(zErr);
120254     return SQLITE_ERROR;
120255   }
120256   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
120257   *ppCsr = pRet;
120258   return SQLITE_OK;
120259 }
120260
120261 /*
120262 ** Implementation of the snippet() function for FTS3
120263 */
120264 static void fts3SnippetFunc(
120265   sqlite3_context *pContext,      /* SQLite function call context */
120266   int nVal,                       /* Size of apVal[] array */
120267   sqlite3_value **apVal           /* Array of arguments */
120268 ){
120269   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120270   const char *zStart = "<b>";
120271   const char *zEnd = "</b>";
120272   const char *zEllipsis = "<b>...</b>";
120273   int iCol = -1;
120274   int nToken = 15;                /* Default number of tokens in snippet */
120275
120276   /* There must be at least one argument passed to this function (otherwise
120277   ** the non-overloaded version would have been called instead of this one).
120278   */
120279   assert( nVal>=1 );
120280
120281   if( nVal>6 ){
120282     sqlite3_result_error(pContext, 
120283         "wrong number of arguments to function snippet()", -1);
120284     return;
120285   }
120286   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
120287
120288   switch( nVal ){
120289     case 6: nToken = sqlite3_value_int(apVal[5]);
120290     case 5: iCol = sqlite3_value_int(apVal[4]);
120291     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
120292     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
120293     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
120294   }
120295   if( !zEllipsis || !zEnd || !zStart ){
120296     sqlite3_result_error_nomem(pContext);
120297   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
120298     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
120299   }
120300 }
120301
120302 /*
120303 ** Implementation of the offsets() function for FTS3
120304 */
120305 static void fts3OffsetsFunc(
120306   sqlite3_context *pContext,      /* SQLite function call context */
120307   int nVal,                       /* Size of argument array */
120308   sqlite3_value **apVal           /* Array of arguments */
120309 ){
120310   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120311
120312   UNUSED_PARAMETER(nVal);
120313
120314   assert( nVal==1 );
120315   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
120316   assert( pCsr );
120317   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
120318     sqlite3Fts3Offsets(pContext, pCsr);
120319   }
120320 }
120321
120322 /* 
120323 ** Implementation of the special optimize() function for FTS3. This 
120324 ** function merges all segments in the database to a single segment.
120325 ** Example usage is:
120326 **
120327 **   SELECT optimize(t) FROM t LIMIT 1;
120328 **
120329 ** where 't' is the name of an FTS3 table.
120330 */
120331 static void fts3OptimizeFunc(
120332   sqlite3_context *pContext,      /* SQLite function call context */
120333   int nVal,                       /* Size of argument array */
120334   sqlite3_value **apVal           /* Array of arguments */
120335 ){
120336   int rc;                         /* Return code */
120337   Fts3Table *p;                   /* Virtual table handle */
120338   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
120339
120340   UNUSED_PARAMETER(nVal);
120341
120342   assert( nVal==1 );
120343   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
120344   p = (Fts3Table *)pCursor->base.pVtab;
120345   assert( p );
120346
120347   rc = sqlite3Fts3Optimize(p);
120348
120349   switch( rc ){
120350     case SQLITE_OK:
120351       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
120352       break;
120353     case SQLITE_DONE:
120354       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
120355       break;
120356     default:
120357       sqlite3_result_error_code(pContext, rc);
120358       break;
120359   }
120360 }
120361
120362 /*
120363 ** Implementation of the matchinfo() function for FTS3
120364 */
120365 static void fts3MatchinfoFunc(
120366   sqlite3_context *pContext,      /* SQLite function call context */
120367   int nVal,                       /* Size of argument array */
120368   sqlite3_value **apVal           /* Array of arguments */
120369 ){
120370   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120371   assert( nVal==1 || nVal==2 );
120372   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
120373     const char *zArg = 0;
120374     if( nVal>1 ){
120375       zArg = (const char *)sqlite3_value_text(apVal[1]);
120376     }
120377     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
120378   }
120379 }
120380
120381 /*
120382 ** This routine implements the xFindFunction method for the FTS3
120383 ** virtual table.
120384 */
120385 static int fts3FindFunctionMethod(
120386   sqlite3_vtab *pVtab,            /* Virtual table handle */
120387   int nArg,                       /* Number of SQL function arguments */
120388   const char *zName,              /* Name of SQL function */
120389   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
120390   void **ppArg                    /* Unused */
120391 ){
120392   struct Overloaded {
120393     const char *zName;
120394     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
120395   } aOverload[] = {
120396     { "snippet", fts3SnippetFunc },
120397     { "offsets", fts3OffsetsFunc },
120398     { "optimize", fts3OptimizeFunc },
120399     { "matchinfo", fts3MatchinfoFunc },
120400   };
120401   int i;                          /* Iterator variable */
120402
120403   UNUSED_PARAMETER(pVtab);
120404   UNUSED_PARAMETER(nArg);
120405   UNUSED_PARAMETER(ppArg);
120406
120407   for(i=0; i<SizeofArray(aOverload); i++){
120408     if( strcmp(zName, aOverload[i].zName)==0 ){
120409       *pxFunc = aOverload[i].xFunc;
120410       return 1;
120411     }
120412   }
120413
120414   /* No function of the specified name was found. Return 0. */
120415   return 0;
120416 }
120417
120418 /*
120419 ** Implementation of FTS3 xRename method. Rename an fts3 table.
120420 */
120421 static int fts3RenameMethod(
120422   sqlite3_vtab *pVtab,            /* Virtual table handle */
120423   const char *zName               /* New name of table */
120424 ){
120425   Fts3Table *p = (Fts3Table *)pVtab;
120426   sqlite3 *db = p->db;            /* Database connection */
120427   int rc;                         /* Return Code */
120428
120429   /* As it happens, the pending terms table is always empty here. This is
120430   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
120431   ** always opens a savepoint transaction. And the xSavepoint() method 
120432   ** flushes the pending terms table. But leave the (no-op) call to
120433   ** PendingTermsFlush() in in case that changes.
120434   */
120435   assert( p->nPendingData==0 );
120436   rc = sqlite3Fts3PendingTermsFlush(p);
120437
120438   if( p->zContentTbl==0 ){
120439     fts3DbExec(&rc, db,
120440       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
120441       p->zDb, p->zName, zName
120442     );
120443   }
120444
120445   if( p->bHasDocsize ){
120446     fts3DbExec(&rc, db,
120447       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
120448       p->zDb, p->zName, zName
120449     );
120450   }
120451   if( p->bHasStat ){
120452     fts3DbExec(&rc, db,
120453       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
120454       p->zDb, p->zName, zName
120455     );
120456   }
120457   fts3DbExec(&rc, db,
120458     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
120459     p->zDb, p->zName, zName
120460   );
120461   fts3DbExec(&rc, db,
120462     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
120463     p->zDb, p->zName, zName
120464   );
120465   return rc;
120466 }
120467
120468 /*
120469 ** The xSavepoint() method.
120470 **
120471 ** Flush the contents of the pending-terms table to disk.
120472 */
120473 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
120474   int rc = SQLITE_OK;
120475   UNUSED_PARAMETER(iSavepoint);
120476   assert( ((Fts3Table *)pVtab)->inTransaction );
120477   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
120478   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
120479   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
120480     rc = fts3SyncMethod(pVtab);
120481   }
120482   return rc;
120483 }
120484
120485 /*
120486 ** The xRelease() method.
120487 **
120488 ** This is a no-op.
120489 */
120490 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
120491   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120492   UNUSED_PARAMETER(iSavepoint);
120493   UNUSED_PARAMETER(pVtab);
120494   assert( p->inTransaction );
120495   assert( p->mxSavepoint >= iSavepoint );
120496   TESTONLY( p->mxSavepoint = iSavepoint-1 );
120497   return SQLITE_OK;
120498 }
120499
120500 /*
120501 ** The xRollbackTo() method.
120502 **
120503 ** Discard the contents of the pending terms table.
120504 */
120505 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
120506   Fts3Table *p = (Fts3Table*)pVtab;
120507   UNUSED_PARAMETER(iSavepoint);
120508   assert( p->inTransaction );
120509   assert( p->mxSavepoint >= iSavepoint );
120510   TESTONLY( p->mxSavepoint = iSavepoint );
120511   sqlite3Fts3PendingTermsClear(p);
120512   return SQLITE_OK;
120513 }
120514
120515 static const sqlite3_module fts3Module = {
120516   /* iVersion      */ 2,
120517   /* xCreate       */ fts3CreateMethod,
120518   /* xConnect      */ fts3ConnectMethod,
120519   /* xBestIndex    */ fts3BestIndexMethod,
120520   /* xDisconnect   */ fts3DisconnectMethod,
120521   /* xDestroy      */ fts3DestroyMethod,
120522   /* xOpen         */ fts3OpenMethod,
120523   /* xClose        */ fts3CloseMethod,
120524   /* xFilter       */ fts3FilterMethod,
120525   /* xNext         */ fts3NextMethod,
120526   /* xEof          */ fts3EofMethod,
120527   /* xColumn       */ fts3ColumnMethod,
120528   /* xRowid        */ fts3RowidMethod,
120529   /* xUpdate       */ fts3UpdateMethod,
120530   /* xBegin        */ fts3BeginMethod,
120531   /* xSync         */ fts3SyncMethod,
120532   /* xCommit       */ fts3CommitMethod,
120533   /* xRollback     */ fts3RollbackMethod,
120534   /* xFindFunction */ fts3FindFunctionMethod,
120535   /* xRename */       fts3RenameMethod,
120536   /* xSavepoint    */ fts3SavepointMethod,
120537   /* xRelease      */ fts3ReleaseMethod,
120538   /* xRollbackTo   */ fts3RollbackToMethod,
120539 };
120540
120541 /*
120542 ** This function is registered as the module destructor (called when an
120543 ** FTS3 enabled database connection is closed). It frees the memory
120544 ** allocated for the tokenizer hash table.
120545 */
120546 static void hashDestroy(void *p){
120547   Fts3Hash *pHash = (Fts3Hash *)p;
120548   sqlite3Fts3HashClear(pHash);
120549   sqlite3_free(pHash);
120550 }
120551
120552 /*
120553 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
120554 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
120555 ** respectively. The following three forward declarations are for functions
120556 ** declared in these files used to retrieve the respective implementations.
120557 **
120558 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
120559 ** to by the argument to point to the "simple" tokenizer implementation.
120560 ** And so on.
120561 */
120562 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120563 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120564 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
120565 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
120566 #endif
120567 #ifdef SQLITE_ENABLE_ICU
120568 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120569 #endif
120570
120571 /*
120572 ** Initialise the fts3 extension. If this extension is built as part
120573 ** of the sqlite library, then this function is called directly by
120574 ** SQLite. If fts3 is built as a dynamically loadable extension, this
120575 ** function is called by the sqlite3_extension_init() entry point.
120576 */
120577 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
120578   int rc = SQLITE_OK;
120579   Fts3Hash *pHash = 0;
120580   const sqlite3_tokenizer_module *pSimple = 0;
120581   const sqlite3_tokenizer_module *pPorter = 0;
120582 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
120583   const sqlite3_tokenizer_module *pUnicode = 0;
120584 #endif
120585
120586 #ifdef SQLITE_ENABLE_ICU
120587   const sqlite3_tokenizer_module *pIcu = 0;
120588   sqlite3Fts3IcuTokenizerModule(&pIcu);
120589 #endif
120590
120591 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
120592   sqlite3Fts3UnicodeTokenizer(&pUnicode);
120593 #endif
120594
120595 #ifdef SQLITE_TEST
120596   rc = sqlite3Fts3InitTerm(db);
120597   if( rc!=SQLITE_OK ) return rc;
120598 #endif
120599
120600   rc = sqlite3Fts3InitAux(db);
120601   if( rc!=SQLITE_OK ) return rc;
120602
120603   sqlite3Fts3SimpleTokenizerModule(&pSimple);
120604   sqlite3Fts3PorterTokenizerModule(&pPorter);
120605
120606   /* Allocate and initialise the hash-table used to store tokenizers. */
120607   pHash = sqlite3_malloc(sizeof(Fts3Hash));
120608   if( !pHash ){
120609     rc = SQLITE_NOMEM;
120610   }else{
120611     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
120612   }
120613
120614   /* Load the built-in tokenizers into the hash table */
120615   if( rc==SQLITE_OK ){
120616     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
120617      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
120618
120619 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
120620      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
120621 #endif
120622 #ifdef SQLITE_ENABLE_ICU
120623      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
120624 #endif
120625     ){
120626       rc = SQLITE_NOMEM;
120627     }
120628   }
120629
120630 #ifdef SQLITE_TEST
120631   if( rc==SQLITE_OK ){
120632     rc = sqlite3Fts3ExprInitTestInterface(db);
120633   }
120634 #endif
120635
120636   /* Create the virtual table wrapper around the hash-table and overload 
120637   ** the two scalar functions. If this is successful, register the
120638   ** module with sqlite.
120639   */
120640   if( SQLITE_OK==rc 
120641    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
120642    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
120643    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
120644    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
120645    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
120646    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
120647   ){
120648     rc = sqlite3_create_module_v2(
120649         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
120650     );
120651     if( rc==SQLITE_OK ){
120652       rc = sqlite3_create_module_v2(
120653           db, "fts4", &fts3Module, (void *)pHash, 0
120654       );
120655     }
120656     return rc;
120657   }
120658
120659   /* An error has occurred. Delete the hash table and return the error code. */
120660   assert( rc!=SQLITE_OK );
120661   if( pHash ){
120662     sqlite3Fts3HashClear(pHash);
120663     sqlite3_free(pHash);
120664   }
120665   return rc;
120666 }
120667
120668 /*
120669 ** Allocate an Fts3MultiSegReader for each token in the expression headed
120670 ** by pExpr. 
120671 **
120672 ** An Fts3SegReader object is a cursor that can seek or scan a range of
120673 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
120674 ** Fts3SegReader objects internally to provide an interface to seek or scan
120675 ** within the union of all segments of a b-tree. Hence the name.
120676 **
120677 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
120678 ** segment b-tree (if the term is not a prefix or it is a prefix for which
120679 ** there exists prefix b-tree of the right length) then it may be traversed
120680 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
120681 ** doclist and then traversed.
120682 */
120683 static void fts3EvalAllocateReaders(
120684   Fts3Cursor *pCsr,               /* FTS cursor handle */
120685   Fts3Expr *pExpr,                /* Allocate readers for this expression */
120686   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
120687   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
120688   int *pRc                        /* IN/OUT: Error code */
120689 ){
120690   if( pExpr && SQLITE_OK==*pRc ){
120691     if( pExpr->eType==FTSQUERY_PHRASE ){
120692       int i;
120693       int nToken = pExpr->pPhrase->nToken;
120694       *pnToken += nToken;
120695       for(i=0; i<nToken; i++){
120696         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
120697         int rc = fts3TermSegReaderCursor(pCsr, 
120698             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
120699         );
120700         if( rc!=SQLITE_OK ){
120701           *pRc = rc;
120702           return;
120703         }
120704       }
120705       assert( pExpr->pPhrase->iDoclistToken==0 );
120706       pExpr->pPhrase->iDoclistToken = -1;
120707     }else{
120708       *pnOr += (pExpr->eType==FTSQUERY_OR);
120709       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
120710       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
120711     }
120712   }
120713 }
120714
120715 /*
120716 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
120717 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
120718 **
120719 ** This function assumes that pList points to a buffer allocated using
120720 ** sqlite3_malloc(). This function takes responsibility for eventually
120721 ** freeing the buffer.
120722 */
120723 static void fts3EvalPhraseMergeToken(
120724   Fts3Table *pTab,                /* FTS Table pointer */
120725   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
120726   int iToken,                     /* Token pList/nList corresponds to */
120727   char *pList,                    /* Pointer to doclist */
120728   int nList                       /* Number of bytes in pList */
120729 ){
120730   assert( iToken!=p->iDoclistToken );
120731
120732   if( pList==0 ){
120733     sqlite3_free(p->doclist.aAll);
120734     p->doclist.aAll = 0;
120735     p->doclist.nAll = 0;
120736   }
120737
120738   else if( p->iDoclistToken<0 ){
120739     p->doclist.aAll = pList;
120740     p->doclist.nAll = nList;
120741   }
120742
120743   else if( p->doclist.aAll==0 ){
120744     sqlite3_free(pList);
120745   }
120746
120747   else {
120748     char *pLeft;
120749     char *pRight;
120750     int nLeft;
120751     int nRight;
120752     int nDiff;
120753
120754     if( p->iDoclistToken<iToken ){
120755       pLeft = p->doclist.aAll;
120756       nLeft = p->doclist.nAll;
120757       pRight = pList;
120758       nRight = nList;
120759       nDiff = iToken - p->iDoclistToken;
120760     }else{
120761       pRight = p->doclist.aAll;
120762       nRight = p->doclist.nAll;
120763       pLeft = pList;
120764       nLeft = nList;
120765       nDiff = p->iDoclistToken - iToken;
120766     }
120767
120768     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
120769     sqlite3_free(pLeft);
120770     p->doclist.aAll = pRight;
120771     p->doclist.nAll = nRight;
120772   }
120773
120774   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
120775 }
120776
120777 /*
120778 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
120779 ** does not take deferred tokens into account.
120780 **
120781 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120782 */
120783 static int fts3EvalPhraseLoad(
120784   Fts3Cursor *pCsr,               /* FTS Cursor handle */
120785   Fts3Phrase *p                   /* Phrase object */
120786 ){
120787   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120788   int iToken;
120789   int rc = SQLITE_OK;
120790
120791   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
120792     Fts3PhraseToken *pToken = &p->aToken[iToken];
120793     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
120794
120795     if( pToken->pSegcsr ){
120796       int nThis = 0;
120797       char *pThis = 0;
120798       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
120799       if( rc==SQLITE_OK ){
120800         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
120801       }
120802     }
120803     assert( pToken->pSegcsr==0 );
120804   }
120805
120806   return rc;
120807 }
120808
120809 /*
120810 ** This function is called on each phrase after the position lists for
120811 ** any deferred tokens have been loaded into memory. It updates the phrases
120812 ** current position list to include only those positions that are really
120813 ** instances of the phrase (after considering deferred tokens). If this
120814 ** means that the phrase does not appear in the current row, doclist.pList
120815 ** and doclist.nList are both zeroed.
120816 **
120817 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120818 */
120819 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
120820   int iToken;                     /* Used to iterate through phrase tokens */
120821   char *aPoslist = 0;             /* Position list for deferred tokens */
120822   int nPoslist = 0;               /* Number of bytes in aPoslist */
120823   int iPrev = -1;                 /* Token number of previous deferred token */
120824
120825   assert( pPhrase->doclist.bFreeList==0 );
120826
120827   for(iToken=0; iToken<pPhrase->nToken; iToken++){
120828     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
120829     Fts3DeferredToken *pDeferred = pToken->pDeferred;
120830
120831     if( pDeferred ){
120832       char *pList;
120833       int nList;
120834       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
120835       if( rc!=SQLITE_OK ) return rc;
120836
120837       if( pList==0 ){
120838         sqlite3_free(aPoslist);
120839         pPhrase->doclist.pList = 0;
120840         pPhrase->doclist.nList = 0;
120841         return SQLITE_OK;
120842
120843       }else if( aPoslist==0 ){
120844         aPoslist = pList;
120845         nPoslist = nList;
120846
120847       }else{
120848         char *aOut = pList;
120849         char *p1 = aPoslist;
120850         char *p2 = aOut;
120851
120852         assert( iPrev>=0 );
120853         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
120854         sqlite3_free(aPoslist);
120855         aPoslist = pList;
120856         nPoslist = (int)(aOut - aPoslist);
120857         if( nPoslist==0 ){
120858           sqlite3_free(aPoslist);
120859           pPhrase->doclist.pList = 0;
120860           pPhrase->doclist.nList = 0;
120861           return SQLITE_OK;
120862         }
120863       }
120864       iPrev = iToken;
120865     }
120866   }
120867
120868   if( iPrev>=0 ){
120869     int nMaxUndeferred = pPhrase->iDoclistToken;
120870     if( nMaxUndeferred<0 ){
120871       pPhrase->doclist.pList = aPoslist;
120872       pPhrase->doclist.nList = nPoslist;
120873       pPhrase->doclist.iDocid = pCsr->iPrevId;
120874       pPhrase->doclist.bFreeList = 1;
120875     }else{
120876       int nDistance;
120877       char *p1;
120878       char *p2;
120879       char *aOut;
120880
120881       if( nMaxUndeferred>iPrev ){
120882         p1 = aPoslist;
120883         p2 = pPhrase->doclist.pList;
120884         nDistance = nMaxUndeferred - iPrev;
120885       }else{
120886         p1 = pPhrase->doclist.pList;
120887         p2 = aPoslist;
120888         nDistance = iPrev - nMaxUndeferred;
120889       }
120890
120891       aOut = (char *)sqlite3_malloc(nPoslist+8);
120892       if( !aOut ){
120893         sqlite3_free(aPoslist);
120894         return SQLITE_NOMEM;
120895       }
120896       
120897       pPhrase->doclist.pList = aOut;
120898       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
120899         pPhrase->doclist.bFreeList = 1;
120900         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
120901       }else{
120902         sqlite3_free(aOut);
120903         pPhrase->doclist.pList = 0;
120904         pPhrase->doclist.nList = 0;
120905       }
120906       sqlite3_free(aPoslist);
120907     }
120908   }
120909
120910   return SQLITE_OK;
120911 }
120912
120913 /*
120914 ** This function is called for each Fts3Phrase in a full-text query 
120915 ** expression to initialize the mechanism for returning rows. Once this
120916 ** function has been called successfully on an Fts3Phrase, it may be
120917 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
120918 **
120919 ** If parameter bOptOk is true, then the phrase may (or may not) use the
120920 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
120921 ** memory within this call.
120922 **
120923 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120924 */
120925 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
120926   int rc;                         /* Error code */
120927   Fts3PhraseToken *pFirst = &p->aToken[0];
120928   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120929
120930   if( pCsr->bDesc==pTab->bDescIdx 
120931    && bOptOk==1 
120932    && p->nToken==1 
120933    && pFirst->pSegcsr 
120934    && pFirst->pSegcsr->bLookup 
120935    && pFirst->bFirst==0
120936   ){
120937     /* Use the incremental approach. */
120938     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
120939     rc = sqlite3Fts3MsrIncrStart(
120940         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
120941     p->bIncr = 1;
120942
120943   }else{
120944     /* Load the full doclist for the phrase into memory. */
120945     rc = fts3EvalPhraseLoad(pCsr, p);
120946     p->bIncr = 0;
120947   }
120948
120949   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
120950   return rc;
120951 }
120952
120953 /*
120954 ** This function is used to iterate backwards (from the end to start) 
120955 ** through doclists. It is used by this module to iterate through phrase
120956 ** doclists in reverse and by the fts3_write.c module to iterate through
120957 ** pending-terms lists when writing to databases with "order=desc".
120958 **
120959 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
120960 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
120961 ** function iterates from the end of the doclist to the beginning.
120962 */
120963 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
120964   int bDescIdx,                   /* True if the doclist is desc */
120965   char *aDoclist,                 /* Pointer to entire doclist */
120966   int nDoclist,                   /* Length of aDoclist in bytes */
120967   char **ppIter,                  /* IN/OUT: Iterator pointer */
120968   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
120969   int *pnList,                    /* OUT: List length pointer */
120970   u8 *pbEof                       /* OUT: End-of-file flag */
120971 ){
120972   char *p = *ppIter;
120973
120974   assert( nDoclist>0 );
120975   assert( *pbEof==0 );
120976   assert( p || *piDocid==0 );
120977   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
120978
120979   if( p==0 ){
120980     sqlite3_int64 iDocid = 0;
120981     char *pNext = 0;
120982     char *pDocid = aDoclist;
120983     char *pEnd = &aDoclist[nDoclist];
120984     int iMul = 1;
120985
120986     while( pDocid<pEnd ){
120987       sqlite3_int64 iDelta;
120988       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
120989       iDocid += (iMul * iDelta);
120990       pNext = pDocid;
120991       fts3PoslistCopy(0, &pDocid);
120992       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
120993       iMul = (bDescIdx ? -1 : 1);
120994     }
120995
120996     *pnList = (int)(pEnd - pNext);
120997     *ppIter = pNext;
120998     *piDocid = iDocid;
120999   }else{
121000     int iMul = (bDescIdx ? -1 : 1);
121001     sqlite3_int64 iDelta;
121002     fts3GetReverseVarint(&p, aDoclist, &iDelta);
121003     *piDocid -= (iMul * iDelta);
121004
121005     if( p==aDoclist ){
121006       *pbEof = 1;
121007     }else{
121008       char *pSave = p;
121009       fts3ReversePoslist(aDoclist, &p);
121010       *pnList = (int)(pSave - p);
121011     }
121012     *ppIter = p;
121013   }
121014 }
121015
121016 /*
121017 ** Iterate forwards through a doclist.
121018 */
121019 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
121020   int bDescIdx,                   /* True if the doclist is desc */
121021   char *aDoclist,                 /* Pointer to entire doclist */
121022   int nDoclist,                   /* Length of aDoclist in bytes */
121023   char **ppIter,                  /* IN/OUT: Iterator pointer */
121024   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121025   u8 *pbEof                       /* OUT: End-of-file flag */
121026 ){
121027   char *p = *ppIter;
121028
121029   assert( nDoclist>0 );
121030   assert( *pbEof==0 );
121031   assert( p || *piDocid==0 );
121032   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
121033
121034   if( p==0 ){
121035     p = aDoclist;
121036     p += sqlite3Fts3GetVarint(p, piDocid);
121037   }else{
121038     fts3PoslistCopy(0, &p);
121039     if( p>=&aDoclist[nDoclist] ){
121040       *pbEof = 1;
121041     }else{
121042       sqlite3_int64 iVar;
121043       p += sqlite3Fts3GetVarint(p, &iVar);
121044       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
121045     }
121046   }
121047
121048   *ppIter = p;
121049 }
121050
121051 /*
121052 ** Attempt to move the phrase iterator to point to the next matching docid. 
121053 ** If an error occurs, return an SQLite error code. Otherwise, return 
121054 ** SQLITE_OK.
121055 **
121056 ** If there is no "next" entry and no error occurs, then *pbEof is set to
121057 ** 1 before returning. Otherwise, if no error occurs and the iterator is
121058 ** successfully advanced, *pbEof is set to 0.
121059 */
121060 static int fts3EvalPhraseNext(
121061   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121062   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
121063   u8 *pbEof                       /* OUT: Set to 1 if EOF */
121064 ){
121065   int rc = SQLITE_OK;
121066   Fts3Doclist *pDL = &p->doclist;
121067   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121068
121069   if( p->bIncr ){
121070     assert( p->nToken==1 );
121071     assert( pDL->pNextDocid==0 );
121072     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
121073         &pDL->iDocid, &pDL->pList, &pDL->nList
121074     );
121075     if( rc==SQLITE_OK && !pDL->pList ){
121076       *pbEof = 1;
121077     }
121078   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
121079     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
121080         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
121081     );
121082     pDL->pList = pDL->pNextDocid;
121083   }else{
121084     char *pIter;                            /* Used to iterate through aAll */
121085     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
121086     if( pDL->pNextDocid ){
121087       pIter = pDL->pNextDocid;
121088     }else{
121089       pIter = pDL->aAll;
121090     }
121091
121092     if( pIter>=pEnd ){
121093       /* We have already reached the end of this doclist. EOF. */
121094       *pbEof = 1;
121095     }else{
121096       sqlite3_int64 iDelta;
121097       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
121098       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
121099         pDL->iDocid += iDelta;
121100       }else{
121101         pDL->iDocid -= iDelta;
121102       }
121103       pDL->pList = pIter;
121104       fts3PoslistCopy(0, &pIter);
121105       pDL->nList = (int)(pIter - pDL->pList);
121106
121107       /* pIter now points just past the 0x00 that terminates the position-
121108       ** list for document pDL->iDocid. However, if this position-list was
121109       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
121110       ** point to the start of the next docid value. The following line deals
121111       ** with this case by advancing pIter past the zero-padding added by
121112       ** fts3EvalNearTrim().  */
121113       while( pIter<pEnd && *pIter==0 ) pIter++;
121114
121115       pDL->pNextDocid = pIter;
121116       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
121117       *pbEof = 0;
121118     }
121119   }
121120
121121   return rc;
121122 }
121123
121124 /*
121125 **
121126 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121127 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
121128 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
121129 ** expressions for which all descendent tokens are deferred.
121130 **
121131 ** If parameter bOptOk is zero, then it is guaranteed that the
121132 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
121133 ** each phrase in the expression (subject to deferred token processing).
121134 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
121135 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
121136 **
121137 ** If an error occurs within this function, *pRc is set to an SQLite error
121138 ** code before returning.
121139 */
121140 static void fts3EvalStartReaders(
121141   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121142   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
121143   int bOptOk,                     /* True to enable incremental loading */
121144   int *pRc                        /* IN/OUT: Error code */
121145 ){
121146   if( pExpr && SQLITE_OK==*pRc ){
121147     if( pExpr->eType==FTSQUERY_PHRASE ){
121148       int i;
121149       int nToken = pExpr->pPhrase->nToken;
121150       for(i=0; i<nToken; i++){
121151         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
121152       }
121153       pExpr->bDeferred = (i==nToken);
121154       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
121155     }else{
121156       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
121157       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
121158       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
121159     }
121160   }
121161 }
121162
121163 /*
121164 ** An array of the following structures is assembled as part of the process
121165 ** of selecting tokens to defer before the query starts executing (as part
121166 ** of the xFilter() method). There is one element in the array for each
121167 ** token in the FTS expression.
121168 **
121169 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
121170 ** to phrases that are connected only by AND and NEAR operators (not OR or
121171 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
121172 ** separately. The root of a tokens AND/NEAR cluster is stored in 
121173 ** Fts3TokenAndCost.pRoot.
121174 */
121175 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
121176 struct Fts3TokenAndCost {
121177   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
121178   int iToken;                     /* Position of token in phrase */
121179   Fts3PhraseToken *pToken;        /* The token itself */
121180   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
121181   int nOvfl;                      /* Number of overflow pages to load doclist */
121182   int iCol;                       /* The column the token must match */
121183 };
121184
121185 /*
121186 ** This function is used to populate an allocated Fts3TokenAndCost array.
121187 **
121188 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121189 ** Otherwise, if an error occurs during execution, *pRc is set to an
121190 ** SQLite error code.
121191 */
121192 static void fts3EvalTokenCosts(
121193   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121194   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
121195   Fts3Expr *pExpr,                /* Expression to consider */
121196   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
121197   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
121198   int *pRc                        /* IN/OUT: Error code */
121199 ){
121200   if( *pRc==SQLITE_OK ){
121201     if( pExpr->eType==FTSQUERY_PHRASE ){
121202       Fts3Phrase *pPhrase = pExpr->pPhrase;
121203       int i;
121204       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
121205         Fts3TokenAndCost *pTC = (*ppTC)++;
121206         pTC->pPhrase = pPhrase;
121207         pTC->iToken = i;
121208         pTC->pRoot = pRoot;
121209         pTC->pToken = &pPhrase->aToken[i];
121210         pTC->iCol = pPhrase->iColumn;
121211         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
121212       }
121213     }else if( pExpr->eType!=FTSQUERY_NOT ){
121214       assert( pExpr->eType==FTSQUERY_OR
121215            || pExpr->eType==FTSQUERY_AND
121216            || pExpr->eType==FTSQUERY_NEAR
121217       );
121218       assert( pExpr->pLeft && pExpr->pRight );
121219       if( pExpr->eType==FTSQUERY_OR ){
121220         pRoot = pExpr->pLeft;
121221         **ppOr = pRoot;
121222         (*ppOr)++;
121223       }
121224       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
121225       if( pExpr->eType==FTSQUERY_OR ){
121226         pRoot = pExpr->pRight;
121227         **ppOr = pRoot;
121228         (*ppOr)++;
121229       }
121230       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
121231     }
121232   }
121233 }
121234
121235 /*
121236 ** Determine the average document (row) size in pages. If successful,
121237 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
121238 ** an SQLite error code.
121239 **
121240 ** The average document size in pages is calculated by first calculating 
121241 ** determining the average size in bytes, B. If B is less than the amount
121242 ** of data that will fit on a single leaf page of an intkey table in
121243 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
121244 ** the number of overflow pages consumed by a record B bytes in size.
121245 */
121246 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
121247   if( pCsr->nRowAvg==0 ){
121248     /* The average document size, which is required to calculate the cost
121249     ** of each doclist, has not yet been determined. Read the required 
121250     ** data from the %_stat table to calculate it.
121251     **
121252     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
121253     ** varints, where nCol is the number of columns in the FTS3 table.
121254     ** The first varint is the number of documents currently stored in
121255     ** the table. The following nCol varints contain the total amount of
121256     ** data stored in all rows of each column of the table, from left
121257     ** to right.
121258     */
121259     int rc;
121260     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
121261     sqlite3_stmt *pStmt;
121262     sqlite3_int64 nDoc = 0;
121263     sqlite3_int64 nByte = 0;
121264     const char *pEnd;
121265     const char *a;
121266
121267     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
121268     if( rc!=SQLITE_OK ) return rc;
121269     a = sqlite3_column_blob(pStmt, 0);
121270     assert( a );
121271
121272     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
121273     a += sqlite3Fts3GetVarint(a, &nDoc);
121274     while( a<pEnd ){
121275       a += sqlite3Fts3GetVarint(a, &nByte);
121276     }
121277     if( nDoc==0 || nByte==0 ){
121278       sqlite3_reset(pStmt);
121279       return FTS_CORRUPT_VTAB;
121280     }
121281
121282     pCsr->nDoc = nDoc;
121283     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
121284     assert( pCsr->nRowAvg>0 ); 
121285     rc = sqlite3_reset(pStmt);
121286     if( rc!=SQLITE_OK ) return rc;
121287   }
121288
121289   *pnPage = pCsr->nRowAvg;
121290   return SQLITE_OK;
121291 }
121292
121293 /*
121294 ** This function is called to select the tokens (if any) that will be 
121295 ** deferred. The array aTC[] has already been populated when this is
121296 ** called.
121297 **
121298 ** This function is called once for each AND/NEAR cluster in the 
121299 ** expression. Each invocation determines which tokens to defer within
121300 ** the cluster with root node pRoot. See comments above the definition
121301 ** of struct Fts3TokenAndCost for more details.
121302 **
121303 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
121304 ** called on each token to defer. Otherwise, an SQLite error code is
121305 ** returned.
121306 */
121307 static int fts3EvalSelectDeferred(
121308   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121309   Fts3Expr *pRoot,                /* Consider tokens with this root node */
121310   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
121311   int nTC                         /* Number of entries in aTC[] */
121312 ){
121313   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121314   int nDocSize = 0;               /* Number of pages per doc loaded */
121315   int rc = SQLITE_OK;             /* Return code */
121316   int ii;                         /* Iterator variable for various purposes */
121317   int nOvfl = 0;                  /* Total overflow pages used by doclists */
121318   int nToken = 0;                 /* Total number of tokens in cluster */
121319
121320   int nMinEst = 0;                /* The minimum count for any phrase so far. */
121321   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
121322
121323   /* Tokens are never deferred for FTS tables created using the content=xxx
121324   ** option. The reason being that it is not guaranteed that the content
121325   ** table actually contains the same data as the index. To prevent this from
121326   ** causing any problems, the deferred token optimization is completely
121327   ** disabled for content=xxx tables. */
121328   if( pTab->zContentTbl ){
121329     return SQLITE_OK;
121330   }
121331
121332   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
121333   ** associated with the tokens spill onto overflow pages, or if there is
121334   ** only 1 token, exit early. No tokens to defer in this case. */
121335   for(ii=0; ii<nTC; ii++){
121336     if( aTC[ii].pRoot==pRoot ){
121337       nOvfl += aTC[ii].nOvfl;
121338       nToken++;
121339     }
121340   }
121341   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
121342
121343   /* Obtain the average docsize (in pages). */
121344   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
121345   assert( rc!=SQLITE_OK || nDocSize>0 );
121346
121347
121348   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
121349   ** of the number of overflow pages that will be loaded by the pager layer 
121350   ** to retrieve the entire doclist for the token from the full-text index.
121351   ** Load the doclists for tokens that are either:
121352   **
121353   **   a. The cheapest token in the entire query (i.e. the one visited by the
121354   **      first iteration of this loop), or
121355   **
121356   **   b. Part of a multi-token phrase.
121357   **
121358   ** After each token doclist is loaded, merge it with the others from the
121359   ** same phrase and count the number of documents that the merged doclist
121360   ** contains. Set variable "nMinEst" to the smallest number of documents in 
121361   ** any phrase doclist for which 1 or more token doclists have been loaded.
121362   ** Let nOther be the number of other phrases for which it is certain that
121363   ** one or more tokens will not be deferred.
121364   **
121365   ** Then, for each token, defer it if loading the doclist would result in
121366   ** loading N or more overflow pages into memory, where N is computed as:
121367   **
121368   **    (nMinEst + 4^nOther - 1) / (4^nOther)
121369   */
121370   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
121371     int iTC;                      /* Used to iterate through aTC[] array. */
121372     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
121373
121374     /* Set pTC to point to the cheapest remaining token. */
121375     for(iTC=0; iTC<nTC; iTC++){
121376       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
121377        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
121378       ){
121379         pTC = &aTC[iTC];
121380       }
121381     }
121382     assert( pTC );
121383
121384     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
121385       /* The number of overflow pages to load for this (and therefore all
121386       ** subsequent) tokens is greater than the estimated number of pages 
121387       ** that will be loaded if all subsequent tokens are deferred.
121388       */
121389       Fts3PhraseToken *pToken = pTC->pToken;
121390       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
121391       fts3SegReaderCursorFree(pToken->pSegcsr);
121392       pToken->pSegcsr = 0;
121393     }else{
121394       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
121395       ** for-loop. Except, limit the value to 2^24 to prevent it from 
121396       ** overflowing the 32-bit integer it is stored in. */
121397       if( ii<12 ) nLoad4 = nLoad4*4;
121398
121399       if( ii==0 || pTC->pPhrase->nToken>1 ){
121400         /* Either this is the cheapest token in the entire query, or it is
121401         ** part of a multi-token phrase. Either way, the entire doclist will
121402         ** (eventually) be loaded into memory. It may as well be now. */
121403         Fts3PhraseToken *pToken = pTC->pToken;
121404         int nList = 0;
121405         char *pList = 0;
121406         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
121407         assert( rc==SQLITE_OK || pList==0 );
121408         if( rc==SQLITE_OK ){
121409           int nCount;
121410           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
121411           nCount = fts3DoclistCountDocids(
121412               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
121413           );
121414           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
121415         }
121416       }
121417     }
121418     pTC->pToken = 0;
121419   }
121420
121421   return rc;
121422 }
121423
121424 /*
121425 ** This function is called from within the xFilter method. It initializes
121426 ** the full-text query currently stored in pCsr->pExpr. To iterate through
121427 ** the results of a query, the caller does:
121428 **
121429 **    fts3EvalStart(pCsr);
121430 **    while( 1 ){
121431 **      fts3EvalNext(pCsr);
121432 **      if( pCsr->bEof ) break;
121433 **      ... return row pCsr->iPrevId to the caller ...
121434 **    }
121435 */
121436 static int fts3EvalStart(Fts3Cursor *pCsr){
121437   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121438   int rc = SQLITE_OK;
121439   int nToken = 0;
121440   int nOr = 0;
121441
121442   /* Allocate a MultiSegReader for each token in the expression. */
121443   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
121444
121445   /* Determine which, if any, tokens in the expression should be deferred. */
121446 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
121447   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
121448     Fts3TokenAndCost *aTC;
121449     Fts3Expr **apOr;
121450     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
121451         sizeof(Fts3TokenAndCost) * nToken
121452       + sizeof(Fts3Expr *) * nOr * 2
121453     );
121454     apOr = (Fts3Expr **)&aTC[nToken];
121455
121456     if( !aTC ){
121457       rc = SQLITE_NOMEM;
121458     }else{
121459       int ii;
121460       Fts3TokenAndCost *pTC = aTC;
121461       Fts3Expr **ppOr = apOr;
121462
121463       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
121464       nToken = (int)(pTC-aTC);
121465       nOr = (int)(ppOr-apOr);
121466
121467       if( rc==SQLITE_OK ){
121468         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
121469         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
121470           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
121471         }
121472       }
121473
121474       sqlite3_free(aTC);
121475     }
121476   }
121477 #endif
121478
121479   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
121480   return rc;
121481 }
121482
121483 /*
121484 ** Invalidate the current position list for phrase pPhrase.
121485 */
121486 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
121487   if( pPhrase->doclist.bFreeList ){
121488     sqlite3_free(pPhrase->doclist.pList);
121489   }
121490   pPhrase->doclist.pList = 0;
121491   pPhrase->doclist.nList = 0;
121492   pPhrase->doclist.bFreeList = 0;
121493 }
121494
121495 /*
121496 ** This function is called to edit the position list associated with
121497 ** the phrase object passed as the fifth argument according to a NEAR
121498 ** condition. For example:
121499 **
121500 **     abc NEAR/5 "def ghi"
121501 **
121502 ** Parameter nNear is passed the NEAR distance of the expression (5 in
121503 ** the example above). When this function is called, *paPoslist points to
121504 ** the position list, and *pnToken is the number of phrase tokens in, the
121505 ** phrase on the other side of the NEAR operator to pPhrase. For example,
121506 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
121507 ** the position list associated with phrase "abc".
121508 **
121509 ** All positions in the pPhrase position list that are not sufficiently
121510 ** close to a position in the *paPoslist position list are removed. If this
121511 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
121512 **
121513 ** Before returning, *paPoslist is set to point to the position lsit 
121514 ** associated with pPhrase. And *pnToken is set to the number of tokens in
121515 ** pPhrase.
121516 */
121517 static int fts3EvalNearTrim(
121518   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
121519   char *aTmp,                     /* Temporary space to use */
121520   char **paPoslist,               /* IN/OUT: Position list */
121521   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
121522   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
121523 ){
121524   int nParam1 = nNear + pPhrase->nToken;
121525   int nParam2 = nNear + *pnToken;
121526   int nNew;
121527   char *p2; 
121528   char *pOut; 
121529   int res;
121530
121531   assert( pPhrase->doclist.pList );
121532
121533   p2 = pOut = pPhrase->doclist.pList;
121534   res = fts3PoslistNearMerge(
121535     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
121536   );
121537   if( res ){
121538     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
121539     assert( pPhrase->doclist.pList[nNew]=='\0' );
121540     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
121541     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
121542     pPhrase->doclist.nList = nNew;
121543     *paPoslist = pPhrase->doclist.pList;
121544     *pnToken = pPhrase->nToken;
121545   }
121546
121547   return res;
121548 }
121549
121550 /*
121551 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
121552 ** Otherwise, it advances the expression passed as the second argument to
121553 ** point to the next matching row in the database. Expressions iterate through
121554 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
121555 ** or descending if it is non-zero.
121556 **
121557 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
121558 ** successful, the following variables in pExpr are set:
121559 **
121560 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
121561 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
121562 **
121563 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
121564 ** at EOF, then the following variables are populated with the position list
121565 ** for the phrase for the visited row:
121566 **
121567 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
121568 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
121569 **
121570 ** It says above that this function advances the expression to the next
121571 ** matching row. This is usually true, but there are the following exceptions:
121572 **
121573 **   1. Deferred tokens are not taken into account. If a phrase consists
121574 **      entirely of deferred tokens, it is assumed to match every row in
121575 **      the db. In this case the position-list is not populated at all. 
121576 **
121577 **      Or, if a phrase contains one or more deferred tokens and one or
121578 **      more non-deferred tokens, then the expression is advanced to the 
121579 **      next possible match, considering only non-deferred tokens. In other
121580 **      words, if the phrase is "A B C", and "B" is deferred, the expression
121581 **      is advanced to the next row that contains an instance of "A * C", 
121582 **      where "*" may match any single token. The position list in this case
121583 **      is populated as for "A * C" before returning.
121584 **
121585 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
121586 **      advanced to point to the next row that matches "x AND y".
121587 ** 
121588 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
121589 ** really a match, taking into account deferred tokens and NEAR operators.
121590 */
121591 static void fts3EvalNextRow(
121592   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121593   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
121594   int *pRc                        /* IN/OUT: Error code */
121595 ){
121596   if( *pRc==SQLITE_OK ){
121597     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
121598     assert( pExpr->bEof==0 );
121599     pExpr->bStart = 1;
121600
121601     switch( pExpr->eType ){
121602       case FTSQUERY_NEAR:
121603       case FTSQUERY_AND: {
121604         Fts3Expr *pLeft = pExpr->pLeft;
121605         Fts3Expr *pRight = pExpr->pRight;
121606         assert( !pLeft->bDeferred || !pRight->bDeferred );
121607
121608         if( pLeft->bDeferred ){
121609           /* LHS is entirely deferred. So we assume it matches every row.
121610           ** Advance the RHS iterator to find the next row visited. */
121611           fts3EvalNextRow(pCsr, pRight, pRc);
121612           pExpr->iDocid = pRight->iDocid;
121613           pExpr->bEof = pRight->bEof;
121614         }else if( pRight->bDeferred ){
121615           /* RHS is entirely deferred. So we assume it matches every row.
121616           ** Advance the LHS iterator to find the next row visited. */
121617           fts3EvalNextRow(pCsr, pLeft, pRc);
121618           pExpr->iDocid = pLeft->iDocid;
121619           pExpr->bEof = pLeft->bEof;
121620         }else{
121621           /* Neither the RHS or LHS are deferred. */
121622           fts3EvalNextRow(pCsr, pLeft, pRc);
121623           fts3EvalNextRow(pCsr, pRight, pRc);
121624           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
121625             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121626             if( iDiff==0 ) break;
121627             if( iDiff<0 ){
121628               fts3EvalNextRow(pCsr, pLeft, pRc);
121629             }else{
121630               fts3EvalNextRow(pCsr, pRight, pRc);
121631             }
121632           }
121633           pExpr->iDocid = pLeft->iDocid;
121634           pExpr->bEof = (pLeft->bEof || pRight->bEof);
121635         }
121636         break;
121637       }
121638   
121639       case FTSQUERY_OR: {
121640         Fts3Expr *pLeft = pExpr->pLeft;
121641         Fts3Expr *pRight = pExpr->pRight;
121642         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121643
121644         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
121645         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
121646
121647         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
121648           fts3EvalNextRow(pCsr, pLeft, pRc);
121649         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
121650           fts3EvalNextRow(pCsr, pRight, pRc);
121651         }else{
121652           fts3EvalNextRow(pCsr, pLeft, pRc);
121653           fts3EvalNextRow(pCsr, pRight, pRc);
121654         }
121655
121656         pExpr->bEof = (pLeft->bEof && pRight->bEof);
121657         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121658         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
121659           pExpr->iDocid = pLeft->iDocid;
121660         }else{
121661           pExpr->iDocid = pRight->iDocid;
121662         }
121663
121664         break;
121665       }
121666
121667       case FTSQUERY_NOT: {
121668         Fts3Expr *pLeft = pExpr->pLeft;
121669         Fts3Expr *pRight = pExpr->pRight;
121670
121671         if( pRight->bStart==0 ){
121672           fts3EvalNextRow(pCsr, pRight, pRc);
121673           assert( *pRc!=SQLITE_OK || pRight->bStart );
121674         }
121675
121676         fts3EvalNextRow(pCsr, pLeft, pRc);
121677         if( pLeft->bEof==0 ){
121678           while( !*pRc 
121679               && !pRight->bEof 
121680               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
121681           ){
121682             fts3EvalNextRow(pCsr, pRight, pRc);
121683           }
121684         }
121685         pExpr->iDocid = pLeft->iDocid;
121686         pExpr->bEof = pLeft->bEof;
121687         break;
121688       }
121689
121690       default: {
121691         Fts3Phrase *pPhrase = pExpr->pPhrase;
121692         fts3EvalInvalidatePoslist(pPhrase);
121693         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
121694         pExpr->iDocid = pPhrase->doclist.iDocid;
121695         break;
121696       }
121697     }
121698   }
121699 }
121700
121701 /*
121702 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
121703 ** cluster, then this function returns 1 immediately.
121704 **
121705 ** Otherwise, it checks if the current row really does match the NEAR 
121706 ** expression, using the data currently stored in the position lists 
121707 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
121708 **
121709 ** If the current row is a match, the position list associated with each
121710 ** phrase in the NEAR expression is edited in place to contain only those
121711 ** phrase instances sufficiently close to their peers to satisfy all NEAR
121712 ** constraints. In this case it returns 1. If the NEAR expression does not 
121713 ** match the current row, 0 is returned. The position lists may or may not
121714 ** be edited if 0 is returned.
121715 */
121716 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
121717   int res = 1;
121718
121719   /* The following block runs if pExpr is the root of a NEAR query.
121720   ** For example, the query:
121721   **
121722   **         "w" NEAR "x" NEAR "y" NEAR "z"
121723   **
121724   ** which is represented in tree form as:
121725   **
121726   **                               |
121727   **                          +--NEAR--+      <-- root of NEAR query
121728   **                          |        |
121729   **                     +--NEAR--+   "z"
121730   **                     |        |
121731   **                +--NEAR--+   "y"
121732   **                |        |
121733   **               "w"      "x"
121734   **
121735   ** The right-hand child of a NEAR node is always a phrase. The 
121736   ** left-hand child may be either a phrase or a NEAR node. There are
121737   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
121738   */
121739   if( *pRc==SQLITE_OK 
121740    && pExpr->eType==FTSQUERY_NEAR 
121741    && pExpr->bEof==0
121742    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121743   ){
121744     Fts3Expr *p; 
121745     int nTmp = 0;                 /* Bytes of temp space */
121746     char *aTmp;                   /* Temp space for PoslistNearMerge() */
121747
121748     /* Allocate temporary working space. */
121749     for(p=pExpr; p->pLeft; p=p->pLeft){
121750       nTmp += p->pRight->pPhrase->doclist.nList;
121751     }
121752     nTmp += p->pPhrase->doclist.nList;
121753     if( nTmp==0 ){
121754       res = 0;
121755     }else{
121756       aTmp = sqlite3_malloc(nTmp*2);
121757       if( !aTmp ){
121758         *pRc = SQLITE_NOMEM;
121759         res = 0;
121760       }else{
121761         char *aPoslist = p->pPhrase->doclist.pList;
121762         int nToken = p->pPhrase->nToken;
121763
121764         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
121765           Fts3Phrase *pPhrase = p->pRight->pPhrase;
121766           int nNear = p->nNear;
121767           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121768         }
121769
121770         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
121771         nToken = pExpr->pRight->pPhrase->nToken;
121772         for(p=pExpr->pLeft; p && res; p=p->pLeft){
121773           int nNear;
121774           Fts3Phrase *pPhrase;
121775           assert( p->pParent && p->pParent->pLeft==p );
121776           nNear = p->pParent->nNear;
121777           pPhrase = (
121778               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
121779               );
121780           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121781         }
121782       }
121783
121784       sqlite3_free(aTmp);
121785     }
121786   }
121787
121788   return res;
121789 }
121790
121791 /*
121792 ** This function is a helper function for fts3EvalTestDeferredAndNear().
121793 ** Assuming no error occurs or has occurred, It returns non-zero if the
121794 ** expression passed as the second argument matches the row that pCsr 
121795 ** currently points to, or zero if it does not.
121796 **
121797 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121798 ** If an error occurs during execution of this function, *pRc is set to 
121799 ** the appropriate SQLite error code. In this case the returned value is 
121800 ** undefined.
121801 */
121802 static int fts3EvalTestExpr(
121803   Fts3Cursor *pCsr,               /* FTS cursor handle */
121804   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
121805   int *pRc                        /* IN/OUT: Error code */
121806 ){
121807   int bHit = 1;                   /* Return value */
121808   if( *pRc==SQLITE_OK ){
121809     switch( pExpr->eType ){
121810       case FTSQUERY_NEAR:
121811       case FTSQUERY_AND:
121812         bHit = (
121813             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121814          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121815          && fts3EvalNearTest(pExpr, pRc)
121816         );
121817
121818         /* If the NEAR expression does not match any rows, zero the doclist for 
121819         ** all phrases involved in the NEAR. This is because the snippet(),
121820         ** offsets() and matchinfo() functions are not supposed to recognize 
121821         ** any instances of phrases that are part of unmatched NEAR queries. 
121822         ** For example if this expression:
121823         **
121824         **    ... MATCH 'a OR (b NEAR c)'
121825         **
121826         ** is matched against a row containing:
121827         **
121828         **        'a b d e'
121829         **
121830         ** then any snippet() should ony highlight the "a" term, not the "b"
121831         ** (as "b" is part of a non-matching NEAR clause).
121832         */
121833         if( bHit==0 
121834          && pExpr->eType==FTSQUERY_NEAR 
121835          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121836         ){
121837           Fts3Expr *p;
121838           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
121839             if( p->pRight->iDocid==pCsr->iPrevId ){
121840               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
121841             }
121842           }
121843           if( p->iDocid==pCsr->iPrevId ){
121844             fts3EvalInvalidatePoslist(p->pPhrase);
121845           }
121846         }
121847
121848         break;
121849
121850       case FTSQUERY_OR: {
121851         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
121852         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
121853         bHit = bHit1 || bHit2;
121854         break;
121855       }
121856
121857       case FTSQUERY_NOT:
121858         bHit = (
121859             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121860          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121861         );
121862         break;
121863
121864       default: {
121865 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
121866         if( pCsr->pDeferred 
121867          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
121868         ){
121869           Fts3Phrase *pPhrase = pExpr->pPhrase;
121870           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
121871           if( pExpr->bDeferred ){
121872             fts3EvalInvalidatePoslist(pPhrase);
121873           }
121874           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
121875           bHit = (pPhrase->doclist.pList!=0);
121876           pExpr->iDocid = pCsr->iPrevId;
121877         }else
121878 #endif
121879         {
121880           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
121881         }
121882         break;
121883       }
121884     }
121885   }
121886   return bHit;
121887 }
121888
121889 /*
121890 ** This function is called as the second part of each xNext operation when
121891 ** iterating through the results of a full-text query. At this point the
121892 ** cursor points to a row that matches the query expression, with the
121893 ** following caveats:
121894 **
121895 **   * Up until this point, "NEAR" operators in the expression have been
121896 **     treated as "AND".
121897 **
121898 **   * Deferred tokens have not yet been considered.
121899 **
121900 ** If *pRc is not SQLITE_OK when this function is called, it immediately
121901 ** returns 0. Otherwise, it tests whether or not after considering NEAR
121902 ** operators and deferred tokens the current row is still a match for the
121903 ** expression. It returns 1 if both of the following are true:
121904 **
121905 **   1. *pRc is SQLITE_OK when this function returns, and
121906 **
121907 **   2. After scanning the current FTS table row for the deferred tokens,
121908 **      it is determined that the row does *not* match the query.
121909 **
121910 ** Or, if no error occurs and it seems the current row does match the FTS
121911 ** query, return 0.
121912 */
121913 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
121914   int rc = *pRc;
121915   int bMiss = 0;
121916   if( rc==SQLITE_OK ){
121917
121918     /* If there are one or more deferred tokens, load the current row into
121919     ** memory and scan it to determine the position list for each deferred
121920     ** token. Then, see if this row is really a match, considering deferred
121921     ** tokens and NEAR operators (neither of which were taken into account
121922     ** earlier, by fts3EvalNextRow()). 
121923     */
121924     if( pCsr->pDeferred ){
121925       rc = fts3CursorSeek(0, pCsr);
121926       if( rc==SQLITE_OK ){
121927         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
121928       }
121929     }
121930     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
121931
121932     /* Free the position-lists accumulated for each deferred token above. */
121933     sqlite3Fts3FreeDeferredDoclists(pCsr);
121934     *pRc = rc;
121935   }
121936   return (rc==SQLITE_OK && bMiss);
121937 }
121938
121939 /*
121940 ** Advance to the next document that matches the FTS expression in
121941 ** Fts3Cursor.pExpr.
121942 */
121943 static int fts3EvalNext(Fts3Cursor *pCsr){
121944   int rc = SQLITE_OK;             /* Return Code */
121945   Fts3Expr *pExpr = pCsr->pExpr;
121946   assert( pCsr->isEof==0 );
121947   if( pExpr==0 ){
121948     pCsr->isEof = 1;
121949   }else{
121950     do {
121951       if( pCsr->isRequireSeek==0 ){
121952         sqlite3_reset(pCsr->pStmt);
121953       }
121954       assert( sqlite3_data_count(pCsr->pStmt)==0 );
121955       fts3EvalNextRow(pCsr, pExpr, &rc);
121956       pCsr->isEof = pExpr->bEof;
121957       pCsr->isRequireSeek = 1;
121958       pCsr->isMatchinfoNeeded = 1;
121959       pCsr->iPrevId = pExpr->iDocid;
121960     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
121961   }
121962   return rc;
121963 }
121964
121965 /*
121966 ** Restart interation for expression pExpr so that the next call to
121967 ** fts3EvalNext() visits the first row. Do not allow incremental 
121968 ** loading or merging of phrase doclists for this iteration.
121969 **
121970 ** If *pRc is other than SQLITE_OK when this function is called, it is
121971 ** a no-op. If an error occurs within this function, *pRc is set to an
121972 ** SQLite error code before returning.
121973 */
121974 static void fts3EvalRestart(
121975   Fts3Cursor *pCsr,
121976   Fts3Expr *pExpr,
121977   int *pRc
121978 ){
121979   if( pExpr && *pRc==SQLITE_OK ){
121980     Fts3Phrase *pPhrase = pExpr->pPhrase;
121981
121982     if( pPhrase ){
121983       fts3EvalInvalidatePoslist(pPhrase);
121984       if( pPhrase->bIncr ){
121985         assert( pPhrase->nToken==1 );
121986         assert( pPhrase->aToken[0].pSegcsr );
121987         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
121988         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
121989       }
121990
121991       pPhrase->doclist.pNextDocid = 0;
121992       pPhrase->doclist.iDocid = 0;
121993     }
121994
121995     pExpr->iDocid = 0;
121996     pExpr->bEof = 0;
121997     pExpr->bStart = 0;
121998
121999     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
122000     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
122001   }
122002 }
122003
122004 /*
122005 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
122006 ** expression rooted at pExpr, the cursor iterates through all rows matched
122007 ** by pExpr, calling this function for each row. This function increments
122008 ** the values in Fts3Expr.aMI[] according to the position-list currently
122009 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
122010 ** expression nodes.
122011 */
122012 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
122013   if( pExpr ){
122014     Fts3Phrase *pPhrase = pExpr->pPhrase;
122015     if( pPhrase && pPhrase->doclist.pList ){
122016       int iCol = 0;
122017       char *p = pPhrase->doclist.pList;
122018
122019       assert( *p );
122020       while( 1 ){
122021         u8 c = 0;
122022         int iCnt = 0;
122023         while( 0xFE & (*p | c) ){
122024           if( (c&0x80)==0 ) iCnt++;
122025           c = *p++ & 0x80;
122026         }
122027
122028         /* aMI[iCol*3 + 1] = Number of occurrences
122029         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
122030         */
122031         pExpr->aMI[iCol*3 + 1] += iCnt;
122032         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
122033         if( *p==0x00 ) break;
122034         p++;
122035         p += sqlite3Fts3GetVarint32(p, &iCol);
122036       }
122037     }
122038
122039     fts3EvalUpdateCounts(pExpr->pLeft);
122040     fts3EvalUpdateCounts(pExpr->pRight);
122041   }
122042 }
122043
122044 /*
122045 ** Expression pExpr must be of type FTSQUERY_PHRASE.
122046 **
122047 ** If it is not already allocated and populated, this function allocates and
122048 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
122049 ** of a NEAR expression, then it also allocates and populates the same array
122050 ** for all other phrases that are part of the NEAR expression.
122051 **
122052 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
122053 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
122054 */
122055 static int fts3EvalGatherStats(
122056   Fts3Cursor *pCsr,               /* Cursor object */
122057   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
122058 ){
122059   int rc = SQLITE_OK;             /* Return code */
122060
122061   assert( pExpr->eType==FTSQUERY_PHRASE );
122062   if( pExpr->aMI==0 ){
122063     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122064     Fts3Expr *pRoot;                /* Root of NEAR expression */
122065     Fts3Expr *p;                    /* Iterator used for several purposes */
122066
122067     sqlite3_int64 iPrevId = pCsr->iPrevId;
122068     sqlite3_int64 iDocid;
122069     u8 bEof;
122070
122071     /* Find the root of the NEAR expression */
122072     pRoot = pExpr;
122073     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
122074       pRoot = pRoot->pParent;
122075     }
122076     iDocid = pRoot->iDocid;
122077     bEof = pRoot->bEof;
122078     assert( pRoot->bStart );
122079
122080     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
122081     for(p=pRoot; p; p=p->pLeft){
122082       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
122083       assert( pE->aMI==0 );
122084       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
122085       if( !pE->aMI ) return SQLITE_NOMEM;
122086       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
122087     }
122088
122089     fts3EvalRestart(pCsr, pRoot, &rc);
122090
122091     while( pCsr->isEof==0 && rc==SQLITE_OK ){
122092
122093       do {
122094         /* Ensure the %_content statement is reset. */
122095         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
122096         assert( sqlite3_data_count(pCsr->pStmt)==0 );
122097
122098         /* Advance to the next document */
122099         fts3EvalNextRow(pCsr, pRoot, &rc);
122100         pCsr->isEof = pRoot->bEof;
122101         pCsr->isRequireSeek = 1;
122102         pCsr->isMatchinfoNeeded = 1;
122103         pCsr->iPrevId = pRoot->iDocid;
122104       }while( pCsr->isEof==0 
122105            && pRoot->eType==FTSQUERY_NEAR 
122106            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
122107       );
122108
122109       if( rc==SQLITE_OK && pCsr->isEof==0 ){
122110         fts3EvalUpdateCounts(pRoot);
122111       }
122112     }
122113
122114     pCsr->isEof = 0;
122115     pCsr->iPrevId = iPrevId;
122116
122117     if( bEof ){
122118       pRoot->bEof = bEof;
122119     }else{
122120       /* Caution: pRoot may iterate through docids in ascending or descending
122121       ** order. For this reason, even though it seems more defensive, the 
122122       ** do loop can not be written:
122123       **
122124       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
122125       */
122126       fts3EvalRestart(pCsr, pRoot, &rc);
122127       do {
122128         fts3EvalNextRow(pCsr, pRoot, &rc);
122129         assert( pRoot->bEof==0 );
122130       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
122131       fts3EvalTestDeferredAndNear(pCsr, &rc);
122132     }
122133   }
122134   return rc;
122135 }
122136
122137 /*
122138 ** This function is used by the matchinfo() module to query a phrase 
122139 ** expression node for the following information:
122140 **
122141 **   1. The total number of occurrences of the phrase in each column of 
122142 **      the FTS table (considering all rows), and
122143 **
122144 **   2. For each column, the number of rows in the table for which the
122145 **      column contains at least one instance of the phrase.
122146 **
122147 ** If no error occurs, SQLITE_OK is returned and the values for each column
122148 ** written into the array aiOut as follows:
122149 **
122150 **   aiOut[iCol*3 + 1] = Number of occurrences
122151 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
122152 **
122153 ** Caveats:
122154 **
122155 **   * If a phrase consists entirely of deferred tokens, then all output 
122156 **     values are set to the number of documents in the table. In other
122157 **     words we assume that very common tokens occur exactly once in each 
122158 **     column of each row of the table.
122159 **
122160 **   * If a phrase contains some deferred tokens (and some non-deferred 
122161 **     tokens), count the potential occurrence identified by considering
122162 **     the non-deferred tokens instead of actual phrase occurrences.
122163 **
122164 **   * If the phrase is part of a NEAR expression, then only phrase instances
122165 **     that meet the NEAR constraint are included in the counts.
122166 */
122167 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
122168   Fts3Cursor *pCsr,               /* FTS cursor handle */
122169   Fts3Expr *pExpr,                /* Phrase expression */
122170   u32 *aiOut                      /* Array to write results into (see above) */
122171 ){
122172   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122173   int rc = SQLITE_OK;
122174   int iCol;
122175
122176   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
122177     assert( pCsr->nDoc>0 );
122178     for(iCol=0; iCol<pTab->nColumn; iCol++){
122179       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
122180       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
122181     }
122182   }else{
122183     rc = fts3EvalGatherStats(pCsr, pExpr);
122184     if( rc==SQLITE_OK ){
122185       assert( pExpr->aMI );
122186       for(iCol=0; iCol<pTab->nColumn; iCol++){
122187         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
122188         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
122189       }
122190     }
122191   }
122192
122193   return rc;
122194 }
122195
122196 /*
122197 ** The expression pExpr passed as the second argument to this function
122198 ** must be of type FTSQUERY_PHRASE. 
122199 **
122200 ** The returned value is either NULL or a pointer to a buffer containing
122201 ** a position-list indicating the occurrences of the phrase in column iCol
122202 ** of the current row. 
122203 **
122204 ** More specifically, the returned buffer contains 1 varint for each 
122205 ** occurence of the phrase in the column, stored using the normal (delta+2) 
122206 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
122207 ** if the requested column contains "a b X c d X X" and the position-list
122208 ** for 'X' is requested, the buffer returned may contain:
122209 **
122210 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
122211 **
122212 ** This function works regardless of whether or not the phrase is deferred,
122213 ** incremental, or neither.
122214 */
122215 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
122216   Fts3Cursor *pCsr,               /* FTS3 cursor object */
122217   Fts3Expr *pExpr,                /* Phrase to return doclist for */
122218   int iCol,                       /* Column to return position list for */
122219   char **ppOut                    /* OUT: Pointer to position list */
122220 ){
122221   Fts3Phrase *pPhrase = pExpr->pPhrase;
122222   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122223   char *pIter;
122224   int iThis;
122225   sqlite3_int64 iDocid;
122226
122227   /* If this phrase is applies specifically to some column other than 
122228   ** column iCol, return a NULL pointer.  */
122229   *ppOut = 0;
122230   assert( iCol>=0 && iCol<pTab->nColumn );
122231   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
122232     return SQLITE_OK;
122233   }
122234
122235   iDocid = pExpr->iDocid;
122236   pIter = pPhrase->doclist.pList;
122237   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
122238     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
122239     int bOr = 0;
122240     u8 bEof = 0;
122241     Fts3Expr *p;
122242
122243     /* Check if this phrase descends from an OR expression node. If not, 
122244     ** return NULL. Otherwise, the entry that corresponds to docid 
122245     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
122246     for(p=pExpr->pParent; p; p=p->pParent){
122247       if( p->eType==FTSQUERY_OR ) bOr = 1;
122248     }
122249     if( bOr==0 ) return SQLITE_OK;
122250
122251     /* This is the descendent of an OR node. In this case we cannot use
122252     ** an incremental phrase. Load the entire doclist for the phrase
122253     ** into memory in this case.  */
122254     if( pPhrase->bIncr ){
122255       int rc = SQLITE_OK;
122256       int bEofSave = pExpr->bEof;
122257       fts3EvalRestart(pCsr, pExpr, &rc);
122258       while( rc==SQLITE_OK && !pExpr->bEof ){
122259         fts3EvalNextRow(pCsr, pExpr, &rc);
122260         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
122261       }
122262       pIter = pPhrase->doclist.pList;
122263       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
122264       if( rc!=SQLITE_OK ) return rc;
122265     }
122266
122267     if( pExpr->bEof ){
122268       pIter = 0;
122269       iDocid = 0;
122270     }
122271     bEof = (pPhrase->doclist.nAll==0);
122272     assert( bDescDoclist==0 || bDescDoclist==1 );
122273     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
122274
122275     if( pCsr->bDesc==bDescDoclist ){
122276       int dummy;
122277       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
122278         sqlite3Fts3DoclistPrev(
122279             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
122280             &pIter, &iDocid, &dummy, &bEof
122281         );
122282       }
122283     }else{
122284       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
122285         sqlite3Fts3DoclistNext(
122286             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
122287             &pIter, &iDocid, &bEof
122288         );
122289       }
122290     }
122291
122292     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
122293   }
122294   if( pIter==0 ) return SQLITE_OK;
122295
122296   if( *pIter==0x01 ){
122297     pIter++;
122298     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122299   }else{
122300     iThis = 0;
122301   }
122302   while( iThis<iCol ){
122303     fts3ColumnlistCopy(0, &pIter);
122304     if( *pIter==0x00 ) return 0;
122305     pIter++;
122306     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122307   }
122308
122309   *ppOut = ((iCol==iThis)?pIter:0);
122310   return SQLITE_OK;
122311 }
122312
122313 /*
122314 ** Free all components of the Fts3Phrase structure that were allocated by
122315 ** the eval module. Specifically, this means to free:
122316 **
122317 **   * the contents of pPhrase->doclist, and
122318 **   * any Fts3MultiSegReader objects held by phrase tokens.
122319 */
122320 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
122321   if( pPhrase ){
122322     int i;
122323     sqlite3_free(pPhrase->doclist.aAll);
122324     fts3EvalInvalidatePoslist(pPhrase);
122325     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
122326     for(i=0; i<pPhrase->nToken; i++){
122327       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
122328       pPhrase->aToken[i].pSegcsr = 0;
122329     }
122330   }
122331 }
122332
122333
122334 /*
122335 ** Return SQLITE_CORRUPT_VTAB.
122336 */
122337 #ifdef SQLITE_DEBUG
122338 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
122339   return SQLITE_CORRUPT_VTAB;
122340 }
122341 #endif
122342
122343 #if !SQLITE_CORE
122344 /*
122345 ** Initialize API pointer table, if required.
122346 */
122347 SQLITE_API int sqlite3_extension_init(
122348   sqlite3 *db, 
122349   char **pzErrMsg,
122350   const sqlite3_api_routines *pApi
122351 ){
122352   SQLITE_EXTENSION_INIT2(pApi)
122353   return sqlite3Fts3Init(db);
122354 }
122355 #endif
122356
122357 #endif
122358
122359 /************** End of fts3.c ************************************************/
122360 /************** Begin file fts3_aux.c ****************************************/
122361 /*
122362 ** 2011 Jan 27
122363 **
122364 ** The author disclaims copyright to this source code.  In place of
122365 ** a legal notice, here is a blessing:
122366 **
122367 **    May you do good and not evil.
122368 **    May you find forgiveness for yourself and forgive others.
122369 **    May you share freely, never taking more than you give.
122370 **
122371 ******************************************************************************
122372 **
122373 */
122374 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122375
122376 /* #include <string.h> */
122377 /* #include <assert.h> */
122378
122379 typedef struct Fts3auxTable Fts3auxTable;
122380 typedef struct Fts3auxCursor Fts3auxCursor;
122381
122382 struct Fts3auxTable {
122383   sqlite3_vtab base;              /* Base class used by SQLite core */
122384   Fts3Table *pFts3Tab;
122385 };
122386
122387 struct Fts3auxCursor {
122388   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
122389   Fts3MultiSegReader csr;        /* Must be right after "base" */
122390   Fts3SegFilter filter;
122391   char *zStop;
122392   int nStop;                      /* Byte-length of string zStop */
122393   int isEof;                      /* True if cursor is at EOF */
122394   sqlite3_int64 iRowid;           /* Current rowid */
122395
122396   int iCol;                       /* Current value of 'col' column */
122397   int nStat;                      /* Size of aStat[] array */
122398   struct Fts3auxColstats {
122399     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
122400     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
122401   } *aStat;
122402 };
122403
122404 /*
122405 ** Schema of the terms table.
122406 */
122407 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
122408
122409 /*
122410 ** This function does all the work for both the xConnect and xCreate methods.
122411 ** These tables have no persistent representation of their own, so xConnect
122412 ** and xCreate are identical operations.
122413 */
122414 static int fts3auxConnectMethod(
122415   sqlite3 *db,                    /* Database connection */
122416   void *pUnused,                  /* Unused */
122417   int argc,                       /* Number of elements in argv array */
122418   const char * const *argv,       /* xCreate/xConnect argument array */
122419   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
122420   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
122421 ){
122422   char const *zDb;                /* Name of database (e.g. "main") */
122423   char const *zFts3;              /* Name of fts3 table */
122424   int nDb;                        /* Result of strlen(zDb) */
122425   int nFts3;                      /* Result of strlen(zFts3) */
122426   int nByte;                      /* Bytes of space to allocate here */
122427   int rc;                         /* value returned by declare_vtab() */
122428   Fts3auxTable *p;                /* Virtual table object to return */
122429
122430   UNUSED_PARAMETER(pUnused);
122431
122432   /* The user should specify a single argument - the name of an fts3 table. */
122433   if( argc!=4 ){
122434     *pzErr = sqlite3_mprintf(
122435         "wrong number of arguments to fts4aux constructor"
122436     );
122437     return SQLITE_ERROR;
122438   }
122439
122440   zDb = argv[1]; 
122441   nDb = (int)strlen(zDb);
122442   zFts3 = argv[3];
122443   nFts3 = (int)strlen(zFts3);
122444
122445   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
122446   if( rc!=SQLITE_OK ) return rc;
122447
122448   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
122449   p = (Fts3auxTable *)sqlite3_malloc(nByte);
122450   if( !p ) return SQLITE_NOMEM;
122451   memset(p, 0, nByte);
122452
122453   p->pFts3Tab = (Fts3Table *)&p[1];
122454   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
122455   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
122456   p->pFts3Tab->db = db;
122457   p->pFts3Tab->nIndex = 1;
122458
122459   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
122460   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
122461   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
122462
122463   *ppVtab = (sqlite3_vtab *)p;
122464   return SQLITE_OK;
122465 }
122466
122467 /*
122468 ** This function does the work for both the xDisconnect and xDestroy methods.
122469 ** These tables have no persistent representation of their own, so xDisconnect
122470 ** and xDestroy are identical operations.
122471 */
122472 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
122473   Fts3auxTable *p = (Fts3auxTable *)pVtab;
122474   Fts3Table *pFts3 = p->pFts3Tab;
122475   int i;
122476
122477   /* Free any prepared statements held */
122478   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
122479     sqlite3_finalize(pFts3->aStmt[i]);
122480   }
122481   sqlite3_free(pFts3->zSegmentsTbl);
122482   sqlite3_free(p);
122483   return SQLITE_OK;
122484 }
122485
122486 #define FTS4AUX_EQ_CONSTRAINT 1
122487 #define FTS4AUX_GE_CONSTRAINT 2
122488 #define FTS4AUX_LE_CONSTRAINT 4
122489
122490 /*
122491 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
122492 */
122493 static int fts3auxBestIndexMethod(
122494   sqlite3_vtab *pVTab, 
122495   sqlite3_index_info *pInfo
122496 ){
122497   int i;
122498   int iEq = -1;
122499   int iGe = -1;
122500   int iLe = -1;
122501
122502   UNUSED_PARAMETER(pVTab);
122503
122504   /* This vtab delivers always results in "ORDER BY term ASC" order. */
122505   if( pInfo->nOrderBy==1 
122506    && pInfo->aOrderBy[0].iColumn==0 
122507    && pInfo->aOrderBy[0].desc==0
122508   ){
122509     pInfo->orderByConsumed = 1;
122510   }
122511
122512   /* Search for equality and range constraints on the "term" column. */
122513   for(i=0; i<pInfo->nConstraint; i++){
122514     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
122515       int op = pInfo->aConstraint[i].op;
122516       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
122517       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
122518       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
122519       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
122520       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
122521     }
122522   }
122523
122524   if( iEq>=0 ){
122525     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
122526     pInfo->aConstraintUsage[iEq].argvIndex = 1;
122527     pInfo->estimatedCost = 5;
122528   }else{
122529     pInfo->idxNum = 0;
122530     pInfo->estimatedCost = 20000;
122531     if( iGe>=0 ){
122532       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
122533       pInfo->aConstraintUsage[iGe].argvIndex = 1;
122534       pInfo->estimatedCost /= 2;
122535     }
122536     if( iLe>=0 ){
122537       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
122538       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
122539       pInfo->estimatedCost /= 2;
122540     }
122541   }
122542
122543   return SQLITE_OK;
122544 }
122545
122546 /*
122547 ** xOpen - Open a cursor.
122548 */
122549 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
122550   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
122551
122552   UNUSED_PARAMETER(pVTab);
122553
122554   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
122555   if( !pCsr ) return SQLITE_NOMEM;
122556   memset(pCsr, 0, sizeof(Fts3auxCursor));
122557
122558   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
122559   return SQLITE_OK;
122560 }
122561
122562 /*
122563 ** xClose - Close a cursor.
122564 */
122565 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
122566   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122567   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122568
122569   sqlite3Fts3SegmentsClose(pFts3);
122570   sqlite3Fts3SegReaderFinish(&pCsr->csr);
122571   sqlite3_free((void *)pCsr->filter.zTerm);
122572   sqlite3_free(pCsr->zStop);
122573   sqlite3_free(pCsr->aStat);
122574   sqlite3_free(pCsr);
122575   return SQLITE_OK;
122576 }
122577
122578 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
122579   if( nSize>pCsr->nStat ){
122580     struct Fts3auxColstats *aNew;
122581     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
122582         sizeof(struct Fts3auxColstats) * nSize
122583     );
122584     if( aNew==0 ) return SQLITE_NOMEM;
122585     memset(&aNew[pCsr->nStat], 0, 
122586         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
122587     );
122588     pCsr->aStat = aNew;
122589     pCsr->nStat = nSize;
122590   }
122591   return SQLITE_OK;
122592 }
122593
122594 /*
122595 ** xNext - Advance the cursor to the next row, if any.
122596 */
122597 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
122598   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122599   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122600   int rc;
122601
122602   /* Increment our pretend rowid value. */
122603   pCsr->iRowid++;
122604
122605   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
122606     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
122607   }
122608
122609   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
122610   if( rc==SQLITE_ROW ){
122611     int i = 0;
122612     int nDoclist = pCsr->csr.nDoclist;
122613     char *aDoclist = pCsr->csr.aDoclist;
122614     int iCol;
122615
122616     int eState = 0;
122617
122618     if( pCsr->zStop ){
122619       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
122620       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
122621       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
122622         pCsr->isEof = 1;
122623         return SQLITE_OK;
122624       }
122625     }
122626
122627     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
122628     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
122629     iCol = 0;
122630
122631     while( i<nDoclist ){
122632       sqlite3_int64 v = 0;
122633
122634       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
122635       switch( eState ){
122636         /* State 0. In this state the integer just read was a docid. */
122637         case 0:
122638           pCsr->aStat[0].nDoc++;
122639           eState = 1;
122640           iCol = 0;
122641           break;
122642
122643         /* State 1. In this state we are expecting either a 1, indicating
122644         ** that the following integer will be a column number, or the
122645         ** start of a position list for column 0.  
122646         ** 
122647         ** The only difference between state 1 and state 2 is that if the
122648         ** integer encountered in state 1 is not 0 or 1, then we need to
122649         ** increment the column 0 "nDoc" count for this term.
122650         */
122651         case 1:
122652           assert( iCol==0 );
122653           if( v>1 ){
122654             pCsr->aStat[1].nDoc++;
122655           }
122656           eState = 2;
122657           /* fall through */
122658
122659         case 2:
122660           if( v==0 ){       /* 0x00. Next integer will be a docid. */
122661             eState = 0;
122662           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
122663             eState = 3;
122664           }else{            /* 2 or greater. A position. */
122665             pCsr->aStat[iCol+1].nOcc++;
122666             pCsr->aStat[0].nOcc++;
122667           }
122668           break;
122669
122670         /* State 3. The integer just read is a column number. */
122671         default: assert( eState==3 );
122672           iCol = (int)v;
122673           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
122674           pCsr->aStat[iCol+1].nDoc++;
122675           eState = 2;
122676           break;
122677       }
122678     }
122679
122680     pCsr->iCol = 0;
122681     rc = SQLITE_OK;
122682   }else{
122683     pCsr->isEof = 1;
122684   }
122685   return rc;
122686 }
122687
122688 /*
122689 ** xFilter - Initialize a cursor to point at the start of its data.
122690 */
122691 static int fts3auxFilterMethod(
122692   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
122693   int idxNum,                     /* Strategy index */
122694   const char *idxStr,             /* Unused */
122695   int nVal,                       /* Number of elements in apVal */
122696   sqlite3_value **apVal           /* Arguments for the indexing scheme */
122697 ){
122698   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122699   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122700   int rc;
122701   int isScan;
122702
122703   UNUSED_PARAMETER(nVal);
122704   UNUSED_PARAMETER(idxStr);
122705
122706   assert( idxStr==0 );
122707   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
122708        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
122709        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
122710   );
122711   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
122712
122713   /* In case this cursor is being reused, close and zero it. */
122714   testcase(pCsr->filter.zTerm);
122715   sqlite3Fts3SegReaderFinish(&pCsr->csr);
122716   sqlite3_free((void *)pCsr->filter.zTerm);
122717   sqlite3_free(pCsr->aStat);
122718   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
122719
122720   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
122721   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
122722
122723   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
122724     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
122725     if( zStr ){
122726       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
122727       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
122728       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
122729     }
122730   }
122731   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
122732     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
122733     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
122734     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
122735     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
122736   }
122737
122738   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
122739       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
122740   );
122741   if( rc==SQLITE_OK ){
122742     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
122743   }
122744
122745   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
122746   return rc;
122747 }
122748
122749 /*
122750 ** xEof - Return true if the cursor is at EOF, or false otherwise.
122751 */
122752 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
122753   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122754   return pCsr->isEof;
122755 }
122756
122757 /*
122758 ** xColumn - Return a column value.
122759 */
122760 static int fts3auxColumnMethod(
122761   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122762   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
122763   int iCol                        /* Index of column to read value from */
122764 ){
122765   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
122766
122767   assert( p->isEof==0 );
122768   if( iCol==0 ){        /* Column "term" */
122769     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
122770   }else if( iCol==1 ){  /* Column "col" */
122771     if( p->iCol ){
122772       sqlite3_result_int(pContext, p->iCol-1);
122773     }else{
122774       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
122775     }
122776   }else if( iCol==2 ){  /* Column "documents" */
122777     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
122778   }else{                /* Column "occurrences" */
122779     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
122780   }
122781
122782   return SQLITE_OK;
122783 }
122784
122785 /*
122786 ** xRowid - Return the current rowid for the cursor.
122787 */
122788 static int fts3auxRowidMethod(
122789   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122790   sqlite_int64 *pRowid            /* OUT: Rowid value */
122791 ){
122792   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122793   *pRowid = pCsr->iRowid;
122794   return SQLITE_OK;
122795 }
122796
122797 /*
122798 ** Register the fts3aux module with database connection db. Return SQLITE_OK
122799 ** if successful or an error code if sqlite3_create_module() fails.
122800 */
122801 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
122802   static const sqlite3_module fts3aux_module = {
122803      0,                           /* iVersion      */
122804      fts3auxConnectMethod,        /* xCreate       */
122805      fts3auxConnectMethod,        /* xConnect      */
122806      fts3auxBestIndexMethod,      /* xBestIndex    */
122807      fts3auxDisconnectMethod,     /* xDisconnect   */
122808      fts3auxDisconnectMethod,     /* xDestroy      */
122809      fts3auxOpenMethod,           /* xOpen         */
122810      fts3auxCloseMethod,          /* xClose        */
122811      fts3auxFilterMethod,         /* xFilter       */
122812      fts3auxNextMethod,           /* xNext         */
122813      fts3auxEofMethod,            /* xEof          */
122814      fts3auxColumnMethod,         /* xColumn       */
122815      fts3auxRowidMethod,          /* xRowid        */
122816      0,                           /* xUpdate       */
122817      0,                           /* xBegin        */
122818      0,                           /* xSync         */
122819      0,                           /* xCommit       */
122820      0,                           /* xRollback     */
122821      0,                           /* xFindFunction */
122822      0,                           /* xRename       */
122823      0,                           /* xSavepoint    */
122824      0,                           /* xRelease      */
122825      0                            /* xRollbackTo   */
122826   };
122827   int rc;                         /* Return code */
122828
122829   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
122830   return rc;
122831 }
122832
122833 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122834
122835 /************** End of fts3_aux.c ********************************************/
122836 /************** Begin file fts3_expr.c ***************************************/
122837 /*
122838 ** 2008 Nov 28
122839 **
122840 ** The author disclaims copyright to this source code.  In place of
122841 ** a legal notice, here is a blessing:
122842 **
122843 **    May you do good and not evil.
122844 **    May you find forgiveness for yourself and forgive others.
122845 **    May you share freely, never taking more than you give.
122846 **
122847 ******************************************************************************
122848 **
122849 ** This module contains code that implements a parser for fts3 query strings
122850 ** (the right-hand argument to the MATCH operator). Because the supported 
122851 ** syntax is relatively simple, the whole tokenizer/parser system is
122852 ** hand-coded. 
122853 */
122854 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122855
122856 /*
122857 ** By default, this module parses the legacy syntax that has been 
122858 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
122859 ** is defined, then it uses the new syntax. The differences between
122860 ** the new and the old syntaxes are:
122861 **
122862 **  a) The new syntax supports parenthesis. The old does not.
122863 **
122864 **  b) The new syntax supports the AND and NOT operators. The old does not.
122865 **
122866 **  c) The old syntax supports the "-" token qualifier. This is not 
122867 **     supported by the new syntax (it is replaced by the NOT operator).
122868 **
122869 **  d) When using the old syntax, the OR operator has a greater precedence
122870 **     than an implicit AND. When using the new, both implicity and explicit
122871 **     AND operators have a higher precedence than OR.
122872 **
122873 ** If compiled with SQLITE_TEST defined, then this module exports the
122874 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
122875 ** to zero causes the module to use the old syntax. If it is set to 
122876 ** non-zero the new syntax is activated. This is so both syntaxes can
122877 ** be tested using a single build of testfixture.
122878 **
122879 ** The following describes the syntax supported by the fts3 MATCH
122880 ** operator in a similar format to that used by the lemon parser
122881 ** generator. This module does not use actually lemon, it uses a
122882 ** custom parser.
122883 **
122884 **   query ::= andexpr (OR andexpr)*.
122885 **
122886 **   andexpr ::= notexpr (AND? notexpr)*.
122887 **
122888 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
122889 **   notexpr ::= LP query RP.
122890 **
122891 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
122892 **
122893 **   distance_opt ::= .
122894 **   distance_opt ::= / INTEGER.
122895 **
122896 **   phrase ::= TOKEN.
122897 **   phrase ::= COLUMN:TOKEN.
122898 **   phrase ::= "TOKEN TOKEN TOKEN...".
122899 */
122900
122901 #ifdef SQLITE_TEST
122902 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
122903 #else
122904 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
122905 #  define sqlite3_fts3_enable_parentheses 1
122906 # else
122907 #  define sqlite3_fts3_enable_parentheses 0
122908 # endif
122909 #endif
122910
122911 /*
122912 ** Default span for NEAR operators.
122913 */
122914 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
122915
122916 /* #include <string.h> */
122917 /* #include <assert.h> */
122918
122919 /*
122920 ** isNot:
122921 **   This variable is used by function getNextNode(). When getNextNode() is
122922 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
122923 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
122924 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
122925 **   zero.
122926 */
122927 typedef struct ParseContext ParseContext;
122928 struct ParseContext {
122929   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
122930   int iLangid;                        /* Language id used with tokenizer */
122931   const char **azCol;                 /* Array of column names for fts3 table */
122932   int bFts4;                          /* True to allow FTS4-only syntax */
122933   int nCol;                           /* Number of entries in azCol[] */
122934   int iDefaultCol;                    /* Default column to query */
122935   int isNot;                          /* True if getNextNode() sees a unary - */
122936   sqlite3_context *pCtx;              /* Write error message here */
122937   int nNest;                          /* Number of nested brackets */
122938 };
122939
122940 /*
122941 ** This function is equivalent to the standard isspace() function. 
122942 **
122943 ** The standard isspace() can be awkward to use safely, because although it
122944 ** is defined to accept an argument of type int, its behaviour when passed
122945 ** an integer that falls outside of the range of the unsigned char type
122946 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
122947 ** is defined to accept an argument of type char, and always returns 0 for
122948 ** any values that fall outside of the range of the unsigned char type (i.e.
122949 ** negative values).
122950 */
122951 static int fts3isspace(char c){
122952   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
122953 }
122954
122955 /*
122956 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
122957 ** zero the memory before returning a pointer to it. If unsuccessful, 
122958 ** return NULL.
122959 */
122960 static void *fts3MallocZero(int nByte){
122961   void *pRet = sqlite3_malloc(nByte);
122962   if( pRet ) memset(pRet, 0, nByte);
122963   return pRet;
122964 }
122965
122966 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
122967   sqlite3_tokenizer *pTokenizer,
122968   int iLangid,
122969   const char *z,
122970   int n,
122971   sqlite3_tokenizer_cursor **ppCsr
122972 ){
122973   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122974   sqlite3_tokenizer_cursor *pCsr = 0;
122975   int rc;
122976
122977   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
122978   assert( rc==SQLITE_OK || pCsr==0 );
122979   if( rc==SQLITE_OK ){
122980     pCsr->pTokenizer = pTokenizer;
122981     if( pModule->iVersion>=1 ){
122982       rc = pModule->xLanguageid(pCsr, iLangid);
122983       if( rc!=SQLITE_OK ){
122984         pModule->xClose(pCsr);
122985         pCsr = 0;
122986       }
122987     }
122988   }
122989   *ppCsr = pCsr;
122990   return rc;
122991 }
122992
122993
122994 /*
122995 ** Extract the next token from buffer z (length n) using the tokenizer
122996 ** and other information (column names etc.) in pParse. Create an Fts3Expr
122997 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
122998 ** single token and set *ppExpr to point to it. If the end of the buffer is
122999 ** reached before a token is found, set *ppExpr to zero. It is the
123000 ** responsibility of the caller to eventually deallocate the allocated 
123001 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
123002 **
123003 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
123004 ** fails.
123005 */
123006 static int getNextToken(
123007   ParseContext *pParse,                   /* fts3 query parse context */
123008   int iCol,                               /* Value for Fts3Phrase.iColumn */
123009   const char *z, int n,                   /* Input string */
123010   Fts3Expr **ppExpr,                      /* OUT: expression */
123011   int *pnConsumed                         /* OUT: Number of bytes consumed */
123012 ){
123013   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123014   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123015   int rc;
123016   sqlite3_tokenizer_cursor *pCursor;
123017   Fts3Expr *pRet = 0;
123018   int nConsumed = 0;
123019
123020   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
123021   if( rc==SQLITE_OK ){
123022     const char *zToken;
123023     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
123024     int nByte;                               /* total space to allocate */
123025
123026     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
123027     if( rc==SQLITE_OK ){
123028       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
123029       pRet = (Fts3Expr *)fts3MallocZero(nByte);
123030       if( !pRet ){
123031         rc = SQLITE_NOMEM;
123032       }else{
123033         pRet->eType = FTSQUERY_PHRASE;
123034         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
123035         pRet->pPhrase->nToken = 1;
123036         pRet->pPhrase->iColumn = iCol;
123037         pRet->pPhrase->aToken[0].n = nToken;
123038         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
123039         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
123040
123041         if( iEnd<n && z[iEnd]=='*' ){
123042           pRet->pPhrase->aToken[0].isPrefix = 1;
123043           iEnd++;
123044         }
123045
123046         while( 1 ){
123047           if( !sqlite3_fts3_enable_parentheses 
123048            && iStart>0 && z[iStart-1]=='-' 
123049           ){
123050             pParse->isNot = 1;
123051             iStart--;
123052           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
123053             pRet->pPhrase->aToken[0].bFirst = 1;
123054             iStart--;
123055           }else{
123056             break;
123057           }
123058         }
123059
123060       }
123061       nConsumed = iEnd;
123062     }
123063
123064     pModule->xClose(pCursor);
123065   }
123066   
123067   *pnConsumed = nConsumed;
123068   *ppExpr = pRet;
123069   return rc;
123070 }
123071
123072
123073 /*
123074 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
123075 ** then free the old allocation.
123076 */
123077 static void *fts3ReallocOrFree(void *pOrig, int nNew){
123078   void *pRet = sqlite3_realloc(pOrig, nNew);
123079   if( !pRet ){
123080     sqlite3_free(pOrig);
123081   }
123082   return pRet;
123083 }
123084
123085 /*
123086 ** Buffer zInput, length nInput, contains the contents of a quoted string
123087 ** that appeared as part of an fts3 query expression. Neither quote character
123088 ** is included in the buffer. This function attempts to tokenize the entire
123089 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
123090 ** containing the results.
123091 **
123092 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
123093 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
123094 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
123095 ** to 0.
123096 */
123097 static int getNextString(
123098   ParseContext *pParse,                   /* fts3 query parse context */
123099   const char *zInput, int nInput,         /* Input string */
123100   Fts3Expr **ppExpr                       /* OUT: expression */
123101 ){
123102   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123103   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123104   int rc;
123105   Fts3Expr *p = 0;
123106   sqlite3_tokenizer_cursor *pCursor = 0;
123107   char *zTemp = 0;
123108   int nTemp = 0;
123109
123110   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
123111   int nToken = 0;
123112
123113   /* The final Fts3Expr data structure, including the Fts3Phrase,
123114   ** Fts3PhraseToken structures token buffers are all stored as a single 
123115   ** allocation so that the expression can be freed with a single call to
123116   ** sqlite3_free(). Setting this up requires a two pass approach.
123117   **
123118   ** The first pass, in the block below, uses a tokenizer cursor to iterate
123119   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
123120   ** to assemble data in two dynamic buffers:
123121   **
123122   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
123123   **             structure, followed by the array of Fts3PhraseToken 
123124   **             structures. This pass only populates the Fts3PhraseToken array.
123125   **
123126   **   Buffer zTemp: Contains copies of all tokens.
123127   **
123128   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
123129   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
123130   ** structures.
123131   */
123132   rc = sqlite3Fts3OpenTokenizer(
123133       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
123134   if( rc==SQLITE_OK ){
123135     int ii;
123136     for(ii=0; rc==SQLITE_OK; ii++){
123137       const char *zByte;
123138       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
123139       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
123140       if( rc==SQLITE_OK ){
123141         Fts3PhraseToken *pToken;
123142
123143         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
123144         if( !p ) goto no_mem;
123145
123146         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
123147         if( !zTemp ) goto no_mem;
123148
123149         assert( nToken==ii );
123150         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
123151         memset(pToken, 0, sizeof(Fts3PhraseToken));
123152
123153         memcpy(&zTemp[nTemp], zByte, nByte);
123154         nTemp += nByte;
123155
123156         pToken->n = nByte;
123157         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
123158         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
123159         nToken = ii+1;
123160       }
123161     }
123162
123163     pModule->xClose(pCursor);
123164     pCursor = 0;
123165   }
123166
123167   if( rc==SQLITE_DONE ){
123168     int jj;
123169     char *zBuf = 0;
123170
123171     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
123172     if( !p ) goto no_mem;
123173     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
123174     p->eType = FTSQUERY_PHRASE;
123175     p->pPhrase = (Fts3Phrase *)&p[1];
123176     p->pPhrase->iColumn = pParse->iDefaultCol;
123177     p->pPhrase->nToken = nToken;
123178
123179     zBuf = (char *)&p->pPhrase->aToken[nToken];
123180     if( zTemp ){
123181       memcpy(zBuf, zTemp, nTemp);
123182       sqlite3_free(zTemp);
123183     }else{
123184       assert( nTemp==0 );
123185     }
123186
123187     for(jj=0; jj<p->pPhrase->nToken; jj++){
123188       p->pPhrase->aToken[jj].z = zBuf;
123189       zBuf += p->pPhrase->aToken[jj].n;
123190     }
123191     rc = SQLITE_OK;
123192   }
123193
123194   *ppExpr = p;
123195   return rc;
123196 no_mem:
123197
123198   if( pCursor ){
123199     pModule->xClose(pCursor);
123200   }
123201   sqlite3_free(zTemp);
123202   sqlite3_free(p);
123203   *ppExpr = 0;
123204   return SQLITE_NOMEM;
123205 }
123206
123207 /*
123208 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
123209 ** call fts3ExprParse(). So this forward declaration is required.
123210 */
123211 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
123212
123213 /*
123214 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
123215 ** structure, or set to 0 if the end of the input buffer is reached.
123216 **
123217 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
123218 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
123219 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
123220 */
123221 static int getNextNode(
123222   ParseContext *pParse,                   /* fts3 query parse context */
123223   const char *z, int n,                   /* Input string */
123224   Fts3Expr **ppExpr,                      /* OUT: expression */
123225   int *pnConsumed                         /* OUT: Number of bytes consumed */
123226 ){
123227   static const struct Fts3Keyword {
123228     char *z;                              /* Keyword text */
123229     unsigned char n;                      /* Length of the keyword */
123230     unsigned char parenOnly;              /* Only valid in paren mode */
123231     unsigned char eType;                  /* Keyword code */
123232   } aKeyword[] = {
123233     { "OR" ,  2, 0, FTSQUERY_OR   },
123234     { "AND",  3, 1, FTSQUERY_AND  },
123235     { "NOT",  3, 1, FTSQUERY_NOT  },
123236     { "NEAR", 4, 0, FTSQUERY_NEAR }
123237   };
123238   int ii;
123239   int iCol;
123240   int iColLen;
123241   int rc;
123242   Fts3Expr *pRet = 0;
123243
123244   const char *zInput = z;
123245   int nInput = n;
123246
123247   pParse->isNot = 0;
123248
123249   /* Skip over any whitespace before checking for a keyword, an open or
123250   ** close bracket, or a quoted string. 
123251   */
123252   while( nInput>0 && fts3isspace(*zInput) ){
123253     nInput--;
123254     zInput++;
123255   }
123256   if( nInput==0 ){
123257     return SQLITE_DONE;
123258   }
123259
123260   /* See if we are dealing with a keyword. */
123261   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
123262     const struct Fts3Keyword *pKey = &aKeyword[ii];
123263
123264     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
123265       continue;
123266     }
123267
123268     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
123269       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
123270       int nKey = pKey->n;
123271       char cNext;
123272
123273       /* If this is a "NEAR" keyword, check for an explicit nearness. */
123274       if( pKey->eType==FTSQUERY_NEAR ){
123275         assert( nKey==4 );
123276         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
123277           nNear = 0;
123278           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
123279             nNear = nNear * 10 + (zInput[nKey] - '0');
123280           }
123281         }
123282       }
123283
123284       /* At this point this is probably a keyword. But for that to be true,
123285       ** the next byte must contain either whitespace, an open or close
123286       ** parenthesis, a quote character, or EOF. 
123287       */
123288       cNext = zInput[nKey];
123289       if( fts3isspace(cNext) 
123290        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
123291       ){
123292         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
123293         if( !pRet ){
123294           return SQLITE_NOMEM;
123295         }
123296         pRet->eType = pKey->eType;
123297         pRet->nNear = nNear;
123298         *ppExpr = pRet;
123299         *pnConsumed = (int)((zInput - z) + nKey);
123300         return SQLITE_OK;
123301       }
123302
123303       /* Turns out that wasn't a keyword after all. This happens if the
123304       ** user has supplied a token such as "ORacle". Continue.
123305       */
123306     }
123307   }
123308
123309   /* Check for an open bracket. */
123310   if( sqlite3_fts3_enable_parentheses ){
123311     if( *zInput=='(' ){
123312       int nConsumed;
123313       pParse->nNest++;
123314       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
123315       if( rc==SQLITE_OK && !*ppExpr ){
123316         rc = SQLITE_DONE;
123317       }
123318       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
123319       return rc;
123320     }
123321   
123322     /* Check for a close bracket. */
123323     if( *zInput==')' ){
123324       pParse->nNest--;
123325       *pnConsumed = (int)((zInput - z) + 1);
123326       return SQLITE_DONE;
123327     }
123328   }
123329
123330   /* See if we are dealing with a quoted phrase. If this is the case, then
123331   ** search for the closing quote and pass the whole string to getNextString()
123332   ** for processing. This is easy to do, as fts3 has no syntax for escaping
123333   ** a quote character embedded in a string.
123334   */
123335   if( *zInput=='"' ){
123336     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
123337     *pnConsumed = (int)((zInput - z) + ii + 1);
123338     if( ii==nInput ){
123339       return SQLITE_ERROR;
123340     }
123341     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
123342   }
123343
123344
123345   /* If control flows to this point, this must be a regular token, or 
123346   ** the end of the input. Read a regular token using the sqlite3_tokenizer
123347   ** interface. Before doing so, figure out if there is an explicit
123348   ** column specifier for the token. 
123349   **
123350   ** TODO: Strangely, it is not possible to associate a column specifier
123351   ** with a quoted phrase, only with a single token. Not sure if this was
123352   ** an implementation artifact or an intentional decision when fts3 was
123353   ** first implemented. Whichever it was, this module duplicates the 
123354   ** limitation.
123355   */
123356   iCol = pParse->iDefaultCol;
123357   iColLen = 0;
123358   for(ii=0; ii<pParse->nCol; ii++){
123359     const char *zStr = pParse->azCol[ii];
123360     int nStr = (int)strlen(zStr);
123361     if( nInput>nStr && zInput[nStr]==':' 
123362      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
123363     ){
123364       iCol = ii;
123365       iColLen = (int)((zInput - z) + nStr + 1);
123366       break;
123367     }
123368   }
123369   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
123370   *pnConsumed += iColLen;
123371   return rc;
123372 }
123373
123374 /*
123375 ** The argument is an Fts3Expr structure for a binary operator (any type
123376 ** except an FTSQUERY_PHRASE). Return an integer value representing the
123377 ** precedence of the operator. Lower values have a higher precedence (i.e.
123378 ** group more tightly). For example, in the C language, the == operator
123379 ** groups more tightly than ||, and would therefore have a higher precedence.
123380 **
123381 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
123382 ** is defined), the order of the operators in precedence from highest to
123383 ** lowest is:
123384 **
123385 **   NEAR
123386 **   NOT
123387 **   AND (including implicit ANDs)
123388 **   OR
123389 **
123390 ** Note that when using the old query syntax, the OR operator has a higher
123391 ** precedence than the AND operator.
123392 */
123393 static int opPrecedence(Fts3Expr *p){
123394   assert( p->eType!=FTSQUERY_PHRASE );
123395   if( sqlite3_fts3_enable_parentheses ){
123396     return p->eType;
123397   }else if( p->eType==FTSQUERY_NEAR ){
123398     return 1;
123399   }else if( p->eType==FTSQUERY_OR ){
123400     return 2;
123401   }
123402   assert( p->eType==FTSQUERY_AND );
123403   return 3;
123404 }
123405
123406 /*
123407 ** Argument ppHead contains a pointer to the current head of a query 
123408 ** expression tree being parsed. pPrev is the expression node most recently
123409 ** inserted into the tree. This function adds pNew, which is always a binary
123410 ** operator node, into the expression tree based on the relative precedence
123411 ** of pNew and the existing nodes of the tree. This may result in the head
123412 ** of the tree changing, in which case *ppHead is set to the new root node.
123413 */
123414 static void insertBinaryOperator(
123415   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
123416   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
123417   Fts3Expr *pNew           /* New binary node to insert into expression tree */
123418 ){
123419   Fts3Expr *pSplit = pPrev;
123420   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
123421     pSplit = pSplit->pParent;
123422   }
123423
123424   if( pSplit->pParent ){
123425     assert( pSplit->pParent->pRight==pSplit );
123426     pSplit->pParent->pRight = pNew;
123427     pNew->pParent = pSplit->pParent;
123428   }else{
123429     *ppHead = pNew;
123430   }
123431   pNew->pLeft = pSplit;
123432   pSplit->pParent = pNew;
123433 }
123434
123435 /*
123436 ** Parse the fts3 query expression found in buffer z, length n. This function
123437 ** returns either when the end of the buffer is reached or an unmatched 
123438 ** closing bracket - ')' - is encountered.
123439 **
123440 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
123441 ** parsed form of the expression and *pnConsumed is set to the number of
123442 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
123443 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
123444 */
123445 static int fts3ExprParse(
123446   ParseContext *pParse,                   /* fts3 query parse context */
123447   const char *z, int n,                   /* Text of MATCH query */
123448   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
123449   int *pnConsumed                         /* OUT: Number of bytes consumed */
123450 ){
123451   Fts3Expr *pRet = 0;
123452   Fts3Expr *pPrev = 0;
123453   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
123454   int nIn = n;
123455   const char *zIn = z;
123456   int rc = SQLITE_OK;
123457   int isRequirePhrase = 1;
123458
123459   while( rc==SQLITE_OK ){
123460     Fts3Expr *p = 0;
123461     int nByte = 0;
123462     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
123463     if( rc==SQLITE_OK ){
123464       int isPhrase;
123465
123466       if( !sqlite3_fts3_enable_parentheses 
123467        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
123468       ){
123469         /* Create an implicit NOT operator. */
123470         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
123471         if( !pNot ){
123472           sqlite3Fts3ExprFree(p);
123473           rc = SQLITE_NOMEM;
123474           goto exprparse_out;
123475         }
123476         pNot->eType = FTSQUERY_NOT;
123477         pNot->pRight = p;
123478         if( pNotBranch ){
123479           pNot->pLeft = pNotBranch;
123480         }
123481         pNotBranch = pNot;
123482         p = pPrev;
123483       }else{
123484         int eType = p->eType;
123485         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
123486
123487         /* The isRequirePhrase variable is set to true if a phrase or
123488         ** an expression contained in parenthesis is required. If a
123489         ** binary operator (AND, OR, NOT or NEAR) is encounted when
123490         ** isRequirePhrase is set, this is a syntax error.
123491         */
123492         if( !isPhrase && isRequirePhrase ){
123493           sqlite3Fts3ExprFree(p);
123494           rc = SQLITE_ERROR;
123495           goto exprparse_out;
123496         }
123497   
123498         if( isPhrase && !isRequirePhrase ){
123499           /* Insert an implicit AND operator. */
123500           Fts3Expr *pAnd;
123501           assert( pRet && pPrev );
123502           pAnd = fts3MallocZero(sizeof(Fts3Expr));
123503           if( !pAnd ){
123504             sqlite3Fts3ExprFree(p);
123505             rc = SQLITE_NOMEM;
123506             goto exprparse_out;
123507           }
123508           pAnd->eType = FTSQUERY_AND;
123509           insertBinaryOperator(&pRet, pPrev, pAnd);
123510           pPrev = pAnd;
123511         }
123512
123513         /* This test catches attempts to make either operand of a NEAR
123514         ** operator something other than a phrase. For example, either of
123515         ** the following:
123516         **
123517         **    (bracketed expression) NEAR phrase
123518         **    phrase NEAR (bracketed expression)
123519         **
123520         ** Return an error in either case.
123521         */
123522         if( pPrev && (
123523             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
123524          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
123525         )){
123526           sqlite3Fts3ExprFree(p);
123527           rc = SQLITE_ERROR;
123528           goto exprparse_out;
123529         }
123530   
123531         if( isPhrase ){
123532           if( pRet ){
123533             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
123534             pPrev->pRight = p;
123535             p->pParent = pPrev;
123536           }else{
123537             pRet = p;
123538           }
123539         }else{
123540           insertBinaryOperator(&pRet, pPrev, p);
123541         }
123542         isRequirePhrase = !isPhrase;
123543       }
123544       assert( nByte>0 );
123545     }
123546     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
123547     nIn -= nByte;
123548     zIn += nByte;
123549     pPrev = p;
123550   }
123551
123552   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
123553     rc = SQLITE_ERROR;
123554   }
123555
123556   if( rc==SQLITE_DONE ){
123557     rc = SQLITE_OK;
123558     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
123559       if( !pRet ){
123560         rc = SQLITE_ERROR;
123561       }else{
123562         Fts3Expr *pIter = pNotBranch;
123563         while( pIter->pLeft ){
123564           pIter = pIter->pLeft;
123565         }
123566         pIter->pLeft = pRet;
123567         pRet = pNotBranch;
123568       }
123569     }
123570   }
123571   *pnConsumed = n - nIn;
123572
123573 exprparse_out:
123574   if( rc!=SQLITE_OK ){
123575     sqlite3Fts3ExprFree(pRet);
123576     sqlite3Fts3ExprFree(pNotBranch);
123577     pRet = 0;
123578   }
123579   *ppExpr = pRet;
123580   return rc;
123581 }
123582
123583 /*
123584 ** Parameters z and n contain a pointer to and length of a buffer containing
123585 ** an fts3 query expression, respectively. This function attempts to parse the
123586 ** query expression and create a tree of Fts3Expr structures representing the
123587 ** parsed expression. If successful, *ppExpr is set to point to the head
123588 ** of the parsed expression tree and SQLITE_OK is returned. If an error
123589 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
123590 ** error) is returned and *ppExpr is set to 0.
123591 **
123592 ** If parameter n is a negative number, then z is assumed to point to a
123593 ** nul-terminated string and the length is determined using strlen().
123594 **
123595 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
123596 ** use to normalize query tokens while parsing the expression. The azCol[]
123597 ** array, which is assumed to contain nCol entries, should contain the names
123598 ** of each column in the target fts3 table, in order from left to right. 
123599 ** Column names must be nul-terminated strings.
123600 **
123601 ** The iDefaultCol parameter should be passed the index of the table column
123602 ** that appears on the left-hand-side of the MATCH operator (the default
123603 ** column to match against for tokens for which a column name is not explicitly
123604 ** specified as part of the query string), or -1 if tokens may by default
123605 ** match any table column.
123606 */
123607 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
123608   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
123609   int iLangid,                        /* Language id for tokenizer */
123610   char **azCol,                       /* Array of column names for fts3 table */
123611   int bFts4,                          /* True to allow FTS4-only syntax */
123612   int nCol,                           /* Number of entries in azCol[] */
123613   int iDefaultCol,                    /* Default column to query */
123614   const char *z, int n,               /* Text of MATCH query */
123615   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
123616 ){
123617   int nParsed;
123618   int rc;
123619   ParseContext sParse;
123620
123621   memset(&sParse, 0, sizeof(ParseContext));
123622   sParse.pTokenizer = pTokenizer;
123623   sParse.iLangid = iLangid;
123624   sParse.azCol = (const char **)azCol;
123625   sParse.nCol = nCol;
123626   sParse.iDefaultCol = iDefaultCol;
123627   sParse.bFts4 = bFts4;
123628   if( z==0 ){
123629     *ppExpr = 0;
123630     return SQLITE_OK;
123631   }
123632   if( n<0 ){
123633     n = (int)strlen(z);
123634   }
123635   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
123636
123637   /* Check for mismatched parenthesis */
123638   if( rc==SQLITE_OK && sParse.nNest ){
123639     rc = SQLITE_ERROR;
123640     sqlite3Fts3ExprFree(*ppExpr);
123641     *ppExpr = 0;
123642   }
123643
123644   return rc;
123645 }
123646
123647 /*
123648 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
123649 */
123650 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
123651   if( p ){
123652     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
123653     sqlite3Fts3ExprFree(p->pLeft);
123654     sqlite3Fts3ExprFree(p->pRight);
123655     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
123656     sqlite3_free(p->aMI);
123657     sqlite3_free(p);
123658   }
123659 }
123660
123661 /****************************************************************************
123662 *****************************************************************************
123663 ** Everything after this point is just test code.
123664 */
123665
123666 #ifdef SQLITE_TEST
123667
123668 /* #include <stdio.h> */
123669
123670 /*
123671 ** Function to query the hash-table of tokenizers (see README.tokenizers).
123672 */
123673 static int queryTestTokenizer(
123674   sqlite3 *db, 
123675   const char *zName,  
123676   const sqlite3_tokenizer_module **pp
123677 ){
123678   int rc;
123679   sqlite3_stmt *pStmt;
123680   const char zSql[] = "SELECT fts3_tokenizer(?)";
123681
123682   *pp = 0;
123683   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
123684   if( rc!=SQLITE_OK ){
123685     return rc;
123686   }
123687
123688   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
123689   if( SQLITE_ROW==sqlite3_step(pStmt) ){
123690     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
123691       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
123692     }
123693   }
123694
123695   return sqlite3_finalize(pStmt);
123696 }
123697
123698 /*
123699 ** Return a pointer to a buffer containing a text representation of the
123700 ** expression passed as the first argument. The buffer is obtained from
123701 ** sqlite3_malloc(). It is the responsibility of the caller to use 
123702 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
123703 ** NULL is returned.
123704 **
123705 ** If the second argument is not NULL, then its contents are prepended to 
123706 ** the returned expression text and then freed using sqlite3_free().
123707 */
123708 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
123709   switch( pExpr->eType ){
123710     case FTSQUERY_PHRASE: {
123711       Fts3Phrase *pPhrase = pExpr->pPhrase;
123712       int i;
123713       zBuf = sqlite3_mprintf(
123714           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
123715       for(i=0; zBuf && i<pPhrase->nToken; i++){
123716         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
123717             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
123718             (pPhrase->aToken[i].isPrefix?"+":"")
123719         );
123720       }
123721       return zBuf;
123722     }
123723
123724     case FTSQUERY_NEAR:
123725       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
123726       break;
123727     case FTSQUERY_NOT:
123728       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
123729       break;
123730     case FTSQUERY_AND:
123731       zBuf = sqlite3_mprintf("%zAND ", zBuf);
123732       break;
123733     case FTSQUERY_OR:
123734       zBuf = sqlite3_mprintf("%zOR ", zBuf);
123735       break;
123736   }
123737
123738   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
123739   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
123740   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
123741
123742   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
123743   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
123744
123745   return zBuf;
123746 }
123747
123748 /*
123749 ** This is the implementation of a scalar SQL function used to test the 
123750 ** expression parser. It should be called as follows:
123751 **
123752 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
123753 **
123754 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
123755 ** to parse the query expression (see README.tokenizers). The second argument
123756 ** is the query expression to parse. Each subsequent argument is the name
123757 ** of a column of the fts3 table that the query expression may refer to.
123758 ** For example:
123759 **
123760 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
123761 */
123762 static void fts3ExprTest(
123763   sqlite3_context *context,
123764   int argc,
123765   sqlite3_value **argv
123766 ){
123767   sqlite3_tokenizer_module const *pModule = 0;
123768   sqlite3_tokenizer *pTokenizer = 0;
123769   int rc;
123770   char **azCol = 0;
123771   const char *zExpr;
123772   int nExpr;
123773   int nCol;
123774   int ii;
123775   Fts3Expr *pExpr;
123776   char *zBuf = 0;
123777   sqlite3 *db = sqlite3_context_db_handle(context);
123778
123779   if( argc<3 ){
123780     sqlite3_result_error(context, 
123781         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
123782     );
123783     return;
123784   }
123785
123786   rc = queryTestTokenizer(db,
123787                           (const char *)sqlite3_value_text(argv[0]), &pModule);
123788   if( rc==SQLITE_NOMEM ){
123789     sqlite3_result_error_nomem(context);
123790     goto exprtest_out;
123791   }else if( !pModule ){
123792     sqlite3_result_error(context, "No such tokenizer module", -1);
123793     goto exprtest_out;
123794   }
123795
123796   rc = pModule->xCreate(0, 0, &pTokenizer);
123797   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
123798   if( rc==SQLITE_NOMEM ){
123799     sqlite3_result_error_nomem(context);
123800     goto exprtest_out;
123801   }
123802   pTokenizer->pModule = pModule;
123803
123804   zExpr = (const char *)sqlite3_value_text(argv[1]);
123805   nExpr = sqlite3_value_bytes(argv[1]);
123806   nCol = argc-2;
123807   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
123808   if( !azCol ){
123809     sqlite3_result_error_nomem(context);
123810     goto exprtest_out;
123811   }
123812   for(ii=0; ii<nCol; ii++){
123813     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
123814   }
123815
123816   rc = sqlite3Fts3ExprParse(
123817       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
123818   );
123819   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
123820     sqlite3_result_error(context, "Error parsing expression", -1);
123821   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
123822     sqlite3_result_error_nomem(context);
123823   }else{
123824     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
123825     sqlite3_free(zBuf);
123826   }
123827
123828   sqlite3Fts3ExprFree(pExpr);
123829
123830 exprtest_out:
123831   if( pModule && pTokenizer ){
123832     rc = pModule->xDestroy(pTokenizer);
123833   }
123834   sqlite3_free(azCol);
123835 }
123836
123837 /*
123838 ** Register the query expression parser test function fts3_exprtest() 
123839 ** with database connection db. 
123840 */
123841 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
123842   return sqlite3_create_function(
123843       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
123844   );
123845 }
123846
123847 #endif
123848 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123849
123850 /************** End of fts3_expr.c *******************************************/
123851 /************** Begin file fts3_hash.c ***************************************/
123852 /*
123853 ** 2001 September 22
123854 **
123855 ** The author disclaims copyright to this source code.  In place of
123856 ** a legal notice, here is a blessing:
123857 **
123858 **    May you do good and not evil.
123859 **    May you find forgiveness for yourself and forgive others.
123860 **    May you share freely, never taking more than you give.
123861 **
123862 *************************************************************************
123863 ** This is the implementation of generic hash-tables used in SQLite.
123864 ** We've modified it slightly to serve as a standalone hash table
123865 ** implementation for the full-text indexing module.
123866 */
123867
123868 /*
123869 ** The code in this file is only compiled if:
123870 **
123871 **     * The FTS3 module is being built as an extension
123872 **       (in which case SQLITE_CORE is not defined), or
123873 **
123874 **     * The FTS3 module is being built into the core of
123875 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123876 */
123877 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123878
123879 /* #include <assert.h> */
123880 /* #include <stdlib.h> */
123881 /* #include <string.h> */
123882
123883
123884 /*
123885 ** Malloc and Free functions
123886 */
123887 static void *fts3HashMalloc(int n){
123888   void *p = sqlite3_malloc(n);
123889   if( p ){
123890     memset(p, 0, n);
123891   }
123892   return p;
123893 }
123894 static void fts3HashFree(void *p){
123895   sqlite3_free(p);
123896 }
123897
123898 /* Turn bulk memory into a hash table object by initializing the
123899 ** fields of the Hash structure.
123900 **
123901 ** "pNew" is a pointer to the hash table that is to be initialized.
123902 ** keyClass is one of the constants 
123903 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
123904 ** determines what kind of key the hash table will use.  "copyKey" is
123905 ** true if the hash table should make its own private copy of keys and
123906 ** false if it should just use the supplied pointer.
123907 */
123908 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
123909   assert( pNew!=0 );
123910   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
123911   pNew->keyClass = keyClass;
123912   pNew->copyKey = copyKey;
123913   pNew->first = 0;
123914   pNew->count = 0;
123915   pNew->htsize = 0;
123916   pNew->ht = 0;
123917 }
123918
123919 /* Remove all entries from a hash table.  Reclaim all memory.
123920 ** Call this routine to delete a hash table or to reset a hash table
123921 ** to the empty state.
123922 */
123923 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
123924   Fts3HashElem *elem;         /* For looping over all elements of the table */
123925
123926   assert( pH!=0 );
123927   elem = pH->first;
123928   pH->first = 0;
123929   fts3HashFree(pH->ht);
123930   pH->ht = 0;
123931   pH->htsize = 0;
123932   while( elem ){
123933     Fts3HashElem *next_elem = elem->next;
123934     if( pH->copyKey && elem->pKey ){
123935       fts3HashFree(elem->pKey);
123936     }
123937     fts3HashFree(elem);
123938     elem = next_elem;
123939   }
123940   pH->count = 0;
123941 }
123942
123943 /*
123944 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
123945 */
123946 static int fts3StrHash(const void *pKey, int nKey){
123947   const char *z = (const char *)pKey;
123948   int h = 0;
123949   if( nKey<=0 ) nKey = (int) strlen(z);
123950   while( nKey > 0  ){
123951     h = (h<<3) ^ h ^ *z++;
123952     nKey--;
123953   }
123954   return h & 0x7fffffff;
123955 }
123956 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123957   if( n1!=n2 ) return 1;
123958   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
123959 }
123960
123961 /*
123962 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
123963 */
123964 static int fts3BinHash(const void *pKey, int nKey){
123965   int h = 0;
123966   const char *z = (const char *)pKey;
123967   while( nKey-- > 0 ){
123968     h = (h<<3) ^ h ^ *(z++);
123969   }
123970   return h & 0x7fffffff;
123971 }
123972 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123973   if( n1!=n2 ) return 1;
123974   return memcmp(pKey1,pKey2,n1);
123975 }
123976
123977 /*
123978 ** Return a pointer to the appropriate hash function given the key class.
123979 **
123980 ** The C syntax in this function definition may be unfamilar to some 
123981 ** programmers, so we provide the following additional explanation:
123982 **
123983 ** The name of the function is "ftsHashFunction".  The function takes a
123984 ** single parameter "keyClass".  The return value of ftsHashFunction()
123985 ** is a pointer to another function.  Specifically, the return value
123986 ** of ftsHashFunction() is a pointer to a function that takes two parameters
123987 ** with types "const void*" and "int" and returns an "int".
123988 */
123989 static int (*ftsHashFunction(int keyClass))(const void*,int){
123990   if( keyClass==FTS3_HASH_STRING ){
123991     return &fts3StrHash;
123992   }else{
123993     assert( keyClass==FTS3_HASH_BINARY );
123994     return &fts3BinHash;
123995   }
123996 }
123997
123998 /*
123999 ** Return a pointer to the appropriate hash function given the key class.
124000 **
124001 ** For help in interpreted the obscure C code in the function definition,
124002 ** see the header comment on the previous function.
124003 */
124004 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
124005   if( keyClass==FTS3_HASH_STRING ){
124006     return &fts3StrCompare;
124007   }else{
124008     assert( keyClass==FTS3_HASH_BINARY );
124009     return &fts3BinCompare;
124010   }
124011 }
124012
124013 /* Link an element into the hash table
124014 */
124015 static void fts3HashInsertElement(
124016   Fts3Hash *pH,            /* The complete hash table */
124017   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
124018   Fts3HashElem *pNew       /* The element to be inserted */
124019 ){
124020   Fts3HashElem *pHead;     /* First element already in pEntry */
124021   pHead = pEntry->chain;
124022   if( pHead ){
124023     pNew->next = pHead;
124024     pNew->prev = pHead->prev;
124025     if( pHead->prev ){ pHead->prev->next = pNew; }
124026     else             { pH->first = pNew; }
124027     pHead->prev = pNew;
124028   }else{
124029     pNew->next = pH->first;
124030     if( pH->first ){ pH->first->prev = pNew; }
124031     pNew->prev = 0;
124032     pH->first = pNew;
124033   }
124034   pEntry->count++;
124035   pEntry->chain = pNew;
124036 }
124037
124038
124039 /* Resize the hash table so that it cantains "new_size" buckets.
124040 ** "new_size" must be a power of 2.  The hash table might fail 
124041 ** to resize if sqliteMalloc() fails.
124042 **
124043 ** Return non-zero if a memory allocation error occurs.
124044 */
124045 static int fts3Rehash(Fts3Hash *pH, int new_size){
124046   struct _fts3ht *new_ht;          /* The new hash table */
124047   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
124048   int (*xHash)(const void*,int);   /* The hash function */
124049
124050   assert( (new_size & (new_size-1))==0 );
124051   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
124052   if( new_ht==0 ) return 1;
124053   fts3HashFree(pH->ht);
124054   pH->ht = new_ht;
124055   pH->htsize = new_size;
124056   xHash = ftsHashFunction(pH->keyClass);
124057   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
124058     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
124059     next_elem = elem->next;
124060     fts3HashInsertElement(pH, &new_ht[h], elem);
124061   }
124062   return 0;
124063 }
124064
124065 /* This function (for internal use only) locates an element in an
124066 ** hash table that matches the given key.  The hash for this key has
124067 ** already been computed and is passed as the 4th parameter.
124068 */
124069 static Fts3HashElem *fts3FindElementByHash(
124070   const Fts3Hash *pH, /* The pH to be searched */
124071   const void *pKey,   /* The key we are searching for */
124072   int nKey,
124073   int h               /* The hash for this key. */
124074 ){
124075   Fts3HashElem *elem;            /* Used to loop thru the element list */
124076   int count;                     /* Number of elements left to test */
124077   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
124078
124079   if( pH->ht ){
124080     struct _fts3ht *pEntry = &pH->ht[h];
124081     elem = pEntry->chain;
124082     count = pEntry->count;
124083     xCompare = ftsCompareFunction(pH->keyClass);
124084     while( count-- && elem ){
124085       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
124086         return elem;
124087       }
124088       elem = elem->next;
124089     }
124090   }
124091   return 0;
124092 }
124093
124094 /* Remove a single entry from the hash table given a pointer to that
124095 ** element and a hash on the element's key.
124096 */
124097 static void fts3RemoveElementByHash(
124098   Fts3Hash *pH,         /* The pH containing "elem" */
124099   Fts3HashElem* elem,   /* The element to be removed from the pH */
124100   int h                 /* Hash value for the element */
124101 ){
124102   struct _fts3ht *pEntry;
124103   if( elem->prev ){
124104     elem->prev->next = elem->next; 
124105   }else{
124106     pH->first = elem->next;
124107   }
124108   if( elem->next ){
124109     elem->next->prev = elem->prev;
124110   }
124111   pEntry = &pH->ht[h];
124112   if( pEntry->chain==elem ){
124113     pEntry->chain = elem->next;
124114   }
124115   pEntry->count--;
124116   if( pEntry->count<=0 ){
124117     pEntry->chain = 0;
124118   }
124119   if( pH->copyKey && elem->pKey ){
124120     fts3HashFree(elem->pKey);
124121   }
124122   fts3HashFree( elem );
124123   pH->count--;
124124   if( pH->count<=0 ){
124125     assert( pH->first==0 );
124126     assert( pH->count==0 );
124127     fts3HashClear(pH);
124128   }
124129 }
124130
124131 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
124132   const Fts3Hash *pH, 
124133   const void *pKey, 
124134   int nKey
124135 ){
124136   int h;                          /* A hash on key */
124137   int (*xHash)(const void*,int);  /* The hash function */
124138
124139   if( pH==0 || pH->ht==0 ) return 0;
124140   xHash = ftsHashFunction(pH->keyClass);
124141   assert( xHash!=0 );
124142   h = (*xHash)(pKey,nKey);
124143   assert( (pH->htsize & (pH->htsize-1))==0 );
124144   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
124145 }
124146
124147 /* 
124148 ** Attempt to locate an element of the hash table pH with a key
124149 ** that matches pKey,nKey.  Return the data for this element if it is
124150 ** found, or NULL if there is no match.
124151 */
124152 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
124153   Fts3HashElem *pElem;            /* The element that matches key (if any) */
124154
124155   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
124156   return pElem ? pElem->data : 0;
124157 }
124158
124159 /* Insert an element into the hash table pH.  The key is pKey,nKey
124160 ** and the data is "data".
124161 **
124162 ** If no element exists with a matching key, then a new
124163 ** element is created.  A copy of the key is made if the copyKey
124164 ** flag is set.  NULL is returned.
124165 **
124166 ** If another element already exists with the same key, then the
124167 ** new data replaces the old data and the old data is returned.
124168 ** The key is not copied in this instance.  If a malloc fails, then
124169 ** the new data is returned and the hash table is unchanged.
124170 **
124171 ** If the "data" parameter to this function is NULL, then the
124172 ** element corresponding to "key" is removed from the hash table.
124173 */
124174 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
124175   Fts3Hash *pH,        /* The hash table to insert into */
124176   const void *pKey,    /* The key */
124177   int nKey,            /* Number of bytes in the key */
124178   void *data           /* The data */
124179 ){
124180   int hraw;                 /* Raw hash value of the key */
124181   int h;                    /* the hash of the key modulo hash table size */
124182   Fts3HashElem *elem;       /* Used to loop thru the element list */
124183   Fts3HashElem *new_elem;   /* New element added to the pH */
124184   int (*xHash)(const void*,int);  /* The hash function */
124185
124186   assert( pH!=0 );
124187   xHash = ftsHashFunction(pH->keyClass);
124188   assert( xHash!=0 );
124189   hraw = (*xHash)(pKey, nKey);
124190   assert( (pH->htsize & (pH->htsize-1))==0 );
124191   h = hraw & (pH->htsize-1);
124192   elem = fts3FindElementByHash(pH,pKey,nKey,h);
124193   if( elem ){
124194     void *old_data = elem->data;
124195     if( data==0 ){
124196       fts3RemoveElementByHash(pH,elem,h);
124197     }else{
124198       elem->data = data;
124199     }
124200     return old_data;
124201   }
124202   if( data==0 ) return 0;
124203   if( (pH->htsize==0 && fts3Rehash(pH,8))
124204    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
124205   ){
124206     pH->count = 0;
124207     return data;
124208   }
124209   assert( pH->htsize>0 );
124210   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
124211   if( new_elem==0 ) return data;
124212   if( pH->copyKey && pKey!=0 ){
124213     new_elem->pKey = fts3HashMalloc( nKey );
124214     if( new_elem->pKey==0 ){
124215       fts3HashFree(new_elem);
124216       return data;
124217     }
124218     memcpy((void*)new_elem->pKey, pKey, nKey);
124219   }else{
124220     new_elem->pKey = (void*)pKey;
124221   }
124222   new_elem->nKey = nKey;
124223   pH->count++;
124224   assert( pH->htsize>0 );
124225   assert( (pH->htsize & (pH->htsize-1))==0 );
124226   h = hraw & (pH->htsize-1);
124227   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
124228   new_elem->data = data;
124229   return 0;
124230 }
124231
124232 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124233
124234 /************** End of fts3_hash.c *******************************************/
124235 /************** Begin file fts3_porter.c *************************************/
124236 /*
124237 ** 2006 September 30
124238 **
124239 ** The author disclaims copyright to this source code.  In place of
124240 ** a legal notice, here is a blessing:
124241 **
124242 **    May you do good and not evil.
124243 **    May you find forgiveness for yourself and forgive others.
124244 **    May you share freely, never taking more than you give.
124245 **
124246 *************************************************************************
124247 ** Implementation of the full-text-search tokenizer that implements
124248 ** a Porter stemmer.
124249 */
124250
124251 /*
124252 ** The code in this file is only compiled if:
124253 **
124254 **     * The FTS3 module is being built as an extension
124255 **       (in which case SQLITE_CORE is not defined), or
124256 **
124257 **     * The FTS3 module is being built into the core of
124258 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124259 */
124260 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124261
124262 /* #include <assert.h> */
124263 /* #include <stdlib.h> */
124264 /* #include <stdio.h> */
124265 /* #include <string.h> */
124266
124267
124268 /*
124269 ** Class derived from sqlite3_tokenizer
124270 */
124271 typedef struct porter_tokenizer {
124272   sqlite3_tokenizer base;      /* Base class */
124273 } porter_tokenizer;
124274
124275 /*
124276 ** Class derived from sqlite3_tokenizer_cursor
124277 */
124278 typedef struct porter_tokenizer_cursor {
124279   sqlite3_tokenizer_cursor base;
124280   const char *zInput;          /* input we are tokenizing */
124281   int nInput;                  /* size of the input */
124282   int iOffset;                 /* current position in zInput */
124283   int iToken;                  /* index of next token to be returned */
124284   char *zToken;                /* storage for current token */
124285   int nAllocated;              /* space allocated to zToken buffer */
124286 } porter_tokenizer_cursor;
124287
124288
124289 /*
124290 ** Create a new tokenizer instance.
124291 */
124292 static int porterCreate(
124293   int argc, const char * const *argv,
124294   sqlite3_tokenizer **ppTokenizer
124295 ){
124296   porter_tokenizer *t;
124297
124298   UNUSED_PARAMETER(argc);
124299   UNUSED_PARAMETER(argv);
124300
124301   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
124302   if( t==NULL ) return SQLITE_NOMEM;
124303   memset(t, 0, sizeof(*t));
124304   *ppTokenizer = &t->base;
124305   return SQLITE_OK;
124306 }
124307
124308 /*
124309 ** Destroy a tokenizer
124310 */
124311 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
124312   sqlite3_free(pTokenizer);
124313   return SQLITE_OK;
124314 }
124315
124316 /*
124317 ** Prepare to begin tokenizing a particular string.  The input
124318 ** string to be tokenized is zInput[0..nInput-1].  A cursor
124319 ** used to incrementally tokenize this string is returned in 
124320 ** *ppCursor.
124321 */
124322 static int porterOpen(
124323   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
124324   const char *zInput, int nInput,        /* String to be tokenized */
124325   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124326 ){
124327   porter_tokenizer_cursor *c;
124328
124329   UNUSED_PARAMETER(pTokenizer);
124330
124331   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
124332   if( c==NULL ) return SQLITE_NOMEM;
124333
124334   c->zInput = zInput;
124335   if( zInput==0 ){
124336     c->nInput = 0;
124337   }else if( nInput<0 ){
124338     c->nInput = (int)strlen(zInput);
124339   }else{
124340     c->nInput = nInput;
124341   }
124342   c->iOffset = 0;                 /* start tokenizing at the beginning */
124343   c->iToken = 0;
124344   c->zToken = NULL;               /* no space allocated, yet. */
124345   c->nAllocated = 0;
124346
124347   *ppCursor = &c->base;
124348   return SQLITE_OK;
124349 }
124350
124351 /*
124352 ** Close a tokenization cursor previously opened by a call to
124353 ** porterOpen() above.
124354 */
124355 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
124356   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
124357   sqlite3_free(c->zToken);
124358   sqlite3_free(c);
124359   return SQLITE_OK;
124360 }
124361 /*
124362 ** Vowel or consonant
124363 */
124364 static const char cType[] = {
124365    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
124366    1, 1, 1, 2, 1
124367 };
124368
124369 /*
124370 ** isConsonant() and isVowel() determine if their first character in
124371 ** the string they point to is a consonant or a vowel, according
124372 ** to Porter ruls.  
124373 **
124374 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
124375 ** 'Y' is a consonant unless it follows another consonant,
124376 ** in which case it is a vowel.
124377 **
124378 ** In these routine, the letters are in reverse order.  So the 'y' rule
124379 ** is that 'y' is a consonant unless it is followed by another
124380 ** consonent.
124381 */
124382 static int isVowel(const char*);
124383 static int isConsonant(const char *z){
124384   int j;
124385   char x = *z;
124386   if( x==0 ) return 0;
124387   assert( x>='a' && x<='z' );
124388   j = cType[x-'a'];
124389   if( j<2 ) return j;
124390   return z[1]==0 || isVowel(z + 1);
124391 }
124392 static int isVowel(const char *z){
124393   int j;
124394   char x = *z;
124395   if( x==0 ) return 0;
124396   assert( x>='a' && x<='z' );
124397   j = cType[x-'a'];
124398   if( j<2 ) return 1-j;
124399   return isConsonant(z + 1);
124400 }
124401
124402 /*
124403 ** Let any sequence of one or more vowels be represented by V and let
124404 ** C be sequence of one or more consonants.  Then every word can be
124405 ** represented as:
124406 **
124407 **           [C] (VC){m} [V]
124408 **
124409 ** In prose:  A word is an optional consonant followed by zero or
124410 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
124411 ** number of vowel consonant pairs.  This routine computes the value
124412 ** of m for the first i bytes of a word.
124413 **
124414 ** Return true if the m-value for z is 1 or more.  In other words,
124415 ** return true if z contains at least one vowel that is followed
124416 ** by a consonant.
124417 **
124418 ** In this routine z[] is in reverse order.  So we are really looking
124419 ** for an instance of of a consonant followed by a vowel.
124420 */
124421 static int m_gt_0(const char *z){
124422   while( isVowel(z) ){ z++; }
124423   if( *z==0 ) return 0;
124424   while( isConsonant(z) ){ z++; }
124425   return *z!=0;
124426 }
124427
124428 /* Like mgt0 above except we are looking for a value of m which is
124429 ** exactly 1
124430 */
124431 static int m_eq_1(const char *z){
124432   while( isVowel(z) ){ z++; }
124433   if( *z==0 ) return 0;
124434   while( isConsonant(z) ){ z++; }
124435   if( *z==0 ) return 0;
124436   while( isVowel(z) ){ z++; }
124437   if( *z==0 ) return 1;
124438   while( isConsonant(z) ){ z++; }
124439   return *z==0;
124440 }
124441
124442 /* Like mgt0 above except we are looking for a value of m>1 instead
124443 ** or m>0
124444 */
124445 static int m_gt_1(const char *z){
124446   while( isVowel(z) ){ z++; }
124447   if( *z==0 ) return 0;
124448   while( isConsonant(z) ){ z++; }
124449   if( *z==0 ) return 0;
124450   while( isVowel(z) ){ z++; }
124451   if( *z==0 ) return 0;
124452   while( isConsonant(z) ){ z++; }
124453   return *z!=0;
124454 }
124455
124456 /*
124457 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
124458 */
124459 static int hasVowel(const char *z){
124460   while( isConsonant(z) ){ z++; }
124461   return *z!=0;
124462 }
124463
124464 /*
124465 ** Return TRUE if the word ends in a double consonant.
124466 **
124467 ** The text is reversed here. So we are really looking at
124468 ** the first two characters of z[].
124469 */
124470 static int doubleConsonant(const char *z){
124471   return isConsonant(z) && z[0]==z[1];
124472 }
124473
124474 /*
124475 ** Return TRUE if the word ends with three letters which
124476 ** are consonant-vowel-consonent and where the final consonant
124477 ** is not 'w', 'x', or 'y'.
124478 **
124479 ** The word is reversed here.  So we are really checking the
124480 ** first three letters and the first one cannot be in [wxy].
124481 */
124482 static int star_oh(const char *z){
124483   return
124484     isConsonant(z) &&
124485     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
124486     isVowel(z+1) &&
124487     isConsonant(z+2);
124488 }
124489
124490 /*
124491 ** If the word ends with zFrom and xCond() is true for the stem
124492 ** of the word that preceeds the zFrom ending, then change the 
124493 ** ending to zTo.
124494 **
124495 ** The input word *pz and zFrom are both in reverse order.  zTo
124496 ** is in normal order. 
124497 **
124498 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
124499 ** match.  Not that TRUE is returned even if xCond() fails and
124500 ** no substitution occurs.
124501 */
124502 static int stem(
124503   char **pz,             /* The word being stemmed (Reversed) */
124504   const char *zFrom,     /* If the ending matches this... (Reversed) */
124505   const char *zTo,       /* ... change the ending to this (not reversed) */
124506   int (*xCond)(const char*)   /* Condition that must be true */
124507 ){
124508   char *z = *pz;
124509   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
124510   if( *zFrom!=0 ) return 0;
124511   if( xCond && !xCond(z) ) return 1;
124512   while( *zTo ){
124513     *(--z) = *(zTo++);
124514   }
124515   *pz = z;
124516   return 1;
124517 }
124518
124519 /*
124520 ** This is the fallback stemmer used when the porter stemmer is
124521 ** inappropriate.  The input word is copied into the output with
124522 ** US-ASCII case folding.  If the input word is too long (more
124523 ** than 20 bytes if it contains no digits or more than 6 bytes if
124524 ** it contains digits) then word is truncated to 20 or 6 bytes
124525 ** by taking 10 or 3 bytes from the beginning and end.
124526 */
124527 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
124528   int i, mx, j;
124529   int hasDigit = 0;
124530   for(i=0; i<nIn; i++){
124531     char c = zIn[i];
124532     if( c>='A' && c<='Z' ){
124533       zOut[i] = c - 'A' + 'a';
124534     }else{
124535       if( c>='0' && c<='9' ) hasDigit = 1;
124536       zOut[i] = c;
124537     }
124538   }
124539   mx = hasDigit ? 3 : 10;
124540   if( nIn>mx*2 ){
124541     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
124542       zOut[j] = zOut[i];
124543     }
124544     i = j;
124545   }
124546   zOut[i] = 0;
124547   *pnOut = i;
124548 }
124549
124550
124551 /*
124552 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
124553 ** zOut is at least big enough to hold nIn bytes.  Write the actual
124554 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
124555 **
124556 ** Any upper-case characters in the US-ASCII character set ([A-Z])
124557 ** are converted to lower case.  Upper-case UTF characters are
124558 ** unchanged.
124559 **
124560 ** Words that are longer than about 20 bytes are stemmed by retaining
124561 ** a few bytes from the beginning and the end of the word.  If the
124562 ** word contains digits, 3 bytes are taken from the beginning and
124563 ** 3 bytes from the end.  For long words without digits, 10 bytes
124564 ** are taken from each end.  US-ASCII case folding still applies.
124565 ** 
124566 ** If the input word contains not digits but does characters not 
124567 ** in [a-zA-Z] then no stemming is attempted and this routine just 
124568 ** copies the input into the input into the output with US-ASCII
124569 ** case folding.
124570 **
124571 ** Stemming never increases the length of the word.  So there is
124572 ** no chance of overflowing the zOut buffer.
124573 */
124574 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
124575   int i, j;
124576   char zReverse[28];
124577   char *z, *z2;
124578   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
124579     /* The word is too big or too small for the porter stemmer.
124580     ** Fallback to the copy stemmer */
124581     copy_stemmer(zIn, nIn, zOut, pnOut);
124582     return;
124583   }
124584   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
124585     char c = zIn[i];
124586     if( c>='A' && c<='Z' ){
124587       zReverse[j] = c + 'a' - 'A';
124588     }else if( c>='a' && c<='z' ){
124589       zReverse[j] = c;
124590     }else{
124591       /* The use of a character not in [a-zA-Z] means that we fallback
124592       ** to the copy stemmer */
124593       copy_stemmer(zIn, nIn, zOut, pnOut);
124594       return;
124595     }
124596   }
124597   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
124598   z = &zReverse[j+1];
124599
124600
124601   /* Step 1a */
124602   if( z[0]=='s' ){
124603     if(
124604      !stem(&z, "sess", "ss", 0) &&
124605      !stem(&z, "sei", "i", 0)  &&
124606      !stem(&z, "ss", "ss", 0)
124607     ){
124608       z++;
124609     }
124610   }
124611
124612   /* Step 1b */  
124613   z2 = z;
124614   if( stem(&z, "dee", "ee", m_gt_0) ){
124615     /* Do nothing.  The work was all in the test */
124616   }else if( 
124617      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
124618       && z!=z2
124619   ){
124620      if( stem(&z, "ta", "ate", 0) ||
124621          stem(&z, "lb", "ble", 0) ||
124622          stem(&z, "zi", "ize", 0) ){
124623        /* Do nothing.  The work was all in the test */
124624      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
124625        z++;
124626      }else if( m_eq_1(z) && star_oh(z) ){
124627        *(--z) = 'e';
124628      }
124629   }
124630
124631   /* Step 1c */
124632   if( z[0]=='y' && hasVowel(z+1) ){
124633     z[0] = 'i';
124634   }
124635
124636   /* Step 2 */
124637   switch( z[1] ){
124638    case 'a':
124639      stem(&z, "lanoita", "ate", m_gt_0) ||
124640      stem(&z, "lanoit", "tion", m_gt_0);
124641      break;
124642    case 'c':
124643      stem(&z, "icne", "ence", m_gt_0) ||
124644      stem(&z, "icna", "ance", m_gt_0);
124645      break;
124646    case 'e':
124647      stem(&z, "rezi", "ize", m_gt_0);
124648      break;
124649    case 'g':
124650      stem(&z, "igol", "log", m_gt_0);
124651      break;
124652    case 'l':
124653      stem(&z, "ilb", "ble", m_gt_0) ||
124654      stem(&z, "illa", "al", m_gt_0) ||
124655      stem(&z, "iltne", "ent", m_gt_0) ||
124656      stem(&z, "ile", "e", m_gt_0) ||
124657      stem(&z, "ilsuo", "ous", m_gt_0);
124658      break;
124659    case 'o':
124660      stem(&z, "noitazi", "ize", m_gt_0) ||
124661      stem(&z, "noita", "ate", m_gt_0) ||
124662      stem(&z, "rota", "ate", m_gt_0);
124663      break;
124664    case 's':
124665      stem(&z, "msila", "al", m_gt_0) ||
124666      stem(&z, "ssenevi", "ive", m_gt_0) ||
124667      stem(&z, "ssenluf", "ful", m_gt_0) ||
124668      stem(&z, "ssensuo", "ous", m_gt_0);
124669      break;
124670    case 't':
124671      stem(&z, "itila", "al", m_gt_0) ||
124672      stem(&z, "itivi", "ive", m_gt_0) ||
124673      stem(&z, "itilib", "ble", m_gt_0);
124674      break;
124675   }
124676
124677   /* Step 3 */
124678   switch( z[0] ){
124679    case 'e':
124680      stem(&z, "etaci", "ic", m_gt_0) ||
124681      stem(&z, "evita", "", m_gt_0)   ||
124682      stem(&z, "ezila", "al", m_gt_0);
124683      break;
124684    case 'i':
124685      stem(&z, "itici", "ic", m_gt_0);
124686      break;
124687    case 'l':
124688      stem(&z, "laci", "ic", m_gt_0) ||
124689      stem(&z, "luf", "", m_gt_0);
124690      break;
124691    case 's':
124692      stem(&z, "ssen", "", m_gt_0);
124693      break;
124694   }
124695
124696   /* Step 4 */
124697   switch( z[1] ){
124698    case 'a':
124699      if( z[0]=='l' && m_gt_1(z+2) ){
124700        z += 2;
124701      }
124702      break;
124703    case 'c':
124704      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
124705        z += 4;
124706      }
124707      break;
124708    case 'e':
124709      if( z[0]=='r' && m_gt_1(z+2) ){
124710        z += 2;
124711      }
124712      break;
124713    case 'i':
124714      if( z[0]=='c' && m_gt_1(z+2) ){
124715        z += 2;
124716      }
124717      break;
124718    case 'l':
124719      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
124720        z += 4;
124721      }
124722      break;
124723    case 'n':
124724      if( z[0]=='t' ){
124725        if( z[2]=='a' ){
124726          if( m_gt_1(z+3) ){
124727            z += 3;
124728          }
124729        }else if( z[2]=='e' ){
124730          stem(&z, "tneme", "", m_gt_1) ||
124731          stem(&z, "tnem", "", m_gt_1) ||
124732          stem(&z, "tne", "", m_gt_1);
124733        }
124734      }
124735      break;
124736    case 'o':
124737      if( z[0]=='u' ){
124738        if( m_gt_1(z+2) ){
124739          z += 2;
124740        }
124741      }else if( z[3]=='s' || z[3]=='t' ){
124742        stem(&z, "noi", "", m_gt_1);
124743      }
124744      break;
124745    case 's':
124746      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
124747        z += 3;
124748      }
124749      break;
124750    case 't':
124751      stem(&z, "eta", "", m_gt_1) ||
124752      stem(&z, "iti", "", m_gt_1);
124753      break;
124754    case 'u':
124755      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
124756        z += 3;
124757      }
124758      break;
124759    case 'v':
124760    case 'z':
124761      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
124762        z += 3;
124763      }
124764      break;
124765   }
124766
124767   /* Step 5a */
124768   if( z[0]=='e' ){
124769     if( m_gt_1(z+1) ){
124770       z++;
124771     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
124772       z++;
124773     }
124774   }
124775
124776   /* Step 5b */
124777   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
124778     z++;
124779   }
124780
124781   /* z[] is now the stemmed word in reverse order.  Flip it back
124782   ** around into forward order and return.
124783   */
124784   *pnOut = i = (int)strlen(z);
124785   zOut[i] = 0;
124786   while( *z ){
124787     zOut[--i] = *(z++);
124788   }
124789 }
124790
124791 /*
124792 ** Characters that can be part of a token.  We assume any character
124793 ** whose value is greater than 0x80 (any UTF character) can be
124794 ** part of a token.  In other words, delimiters all must have
124795 ** values of 0x7f or lower.
124796 */
124797 static const char porterIdChar[] = {
124798 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124799     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124800     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124801     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124802     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124803     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124804 };
124805 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
124806
124807 /*
124808 ** Extract the next token from a tokenization cursor.  The cursor must
124809 ** have been opened by a prior call to porterOpen().
124810 */
124811 static int porterNext(
124812   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
124813   const char **pzToken,               /* OUT: *pzToken is the token text */
124814   int *pnBytes,                       /* OUT: Number of bytes in token */
124815   int *piStartOffset,                 /* OUT: Starting offset of token */
124816   int *piEndOffset,                   /* OUT: Ending offset of token */
124817   int *piPosition                     /* OUT: Position integer of token */
124818 ){
124819   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
124820   const char *z = c->zInput;
124821
124822   while( c->iOffset<c->nInput ){
124823     int iStartOffset, ch;
124824
124825     /* Scan past delimiter characters */
124826     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
124827       c->iOffset++;
124828     }
124829
124830     /* Count non-delimiter characters. */
124831     iStartOffset = c->iOffset;
124832     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
124833       c->iOffset++;
124834     }
124835
124836     if( c->iOffset>iStartOffset ){
124837       int n = c->iOffset-iStartOffset;
124838       if( n>c->nAllocated ){
124839         char *pNew;
124840         c->nAllocated = n+20;
124841         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
124842         if( !pNew ) return SQLITE_NOMEM;
124843         c->zToken = pNew;
124844       }
124845       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
124846       *pzToken = c->zToken;
124847       *piStartOffset = iStartOffset;
124848       *piEndOffset = c->iOffset;
124849       *piPosition = c->iToken++;
124850       return SQLITE_OK;
124851     }
124852   }
124853   return SQLITE_DONE;
124854 }
124855
124856 /*
124857 ** The set of routines that implement the porter-stemmer tokenizer
124858 */
124859 static const sqlite3_tokenizer_module porterTokenizerModule = {
124860   0,
124861   porterCreate,
124862   porterDestroy,
124863   porterOpen,
124864   porterClose,
124865   porterNext,
124866   0
124867 };
124868
124869 /*
124870 ** Allocate a new porter tokenizer.  Return a pointer to the new
124871 ** tokenizer in *ppModule
124872 */
124873 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
124874   sqlite3_tokenizer_module const**ppModule
124875 ){
124876   *ppModule = &porterTokenizerModule;
124877 }
124878
124879 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124880
124881 /************** End of fts3_porter.c *****************************************/
124882 /************** Begin file fts3_tokenizer.c **********************************/
124883 /*
124884 ** 2007 June 22
124885 **
124886 ** The author disclaims copyright to this source code.  In place of
124887 ** a legal notice, here is a blessing:
124888 **
124889 **    May you do good and not evil.
124890 **    May you find forgiveness for yourself and forgive others.
124891 **    May you share freely, never taking more than you give.
124892 **
124893 ******************************************************************************
124894 **
124895 ** This is part of an SQLite module implementing full-text search.
124896 ** This particular file implements the generic tokenizer interface.
124897 */
124898
124899 /*
124900 ** The code in this file is only compiled if:
124901 **
124902 **     * The FTS3 module is being built as an extension
124903 **       (in which case SQLITE_CORE is not defined), or
124904 **
124905 **     * The FTS3 module is being built into the core of
124906 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124907 */
124908 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124909
124910 /* #include <assert.h> */
124911 /* #include <string.h> */
124912
124913 /*
124914 ** Implementation of the SQL scalar function for accessing the underlying 
124915 ** hash table. This function may be called as follows:
124916 **
124917 **   SELECT <function-name>(<key-name>);
124918 **   SELECT <function-name>(<key-name>, <pointer>);
124919 **
124920 ** where <function-name> is the name passed as the second argument
124921 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
124922 **
124923 ** If the <pointer> argument is specified, it must be a blob value
124924 ** containing a pointer to be stored as the hash data corresponding
124925 ** to the string <key-name>. If <pointer> is not specified, then
124926 ** the string <key-name> must already exist in the has table. Otherwise,
124927 ** an error is returned.
124928 **
124929 ** Whether or not the <pointer> argument is specified, the value returned
124930 ** is a blob containing the pointer stored as the hash data corresponding
124931 ** to string <key-name> (after the hash-table is updated, if applicable).
124932 */
124933 static void scalarFunc(
124934   sqlite3_context *context,
124935   int argc,
124936   sqlite3_value **argv
124937 ){
124938   Fts3Hash *pHash;
124939   void *pPtr = 0;
124940   const unsigned char *zName;
124941   int nName;
124942
124943   assert( argc==1 || argc==2 );
124944
124945   pHash = (Fts3Hash *)sqlite3_user_data(context);
124946
124947   zName = sqlite3_value_text(argv[0]);
124948   nName = sqlite3_value_bytes(argv[0])+1;
124949
124950   if( argc==2 ){
124951     void *pOld;
124952     int n = sqlite3_value_bytes(argv[1]);
124953     if( n!=sizeof(pPtr) ){
124954       sqlite3_result_error(context, "argument type mismatch", -1);
124955       return;
124956     }
124957     pPtr = *(void **)sqlite3_value_blob(argv[1]);
124958     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
124959     if( pOld==pPtr ){
124960       sqlite3_result_error(context, "out of memory", -1);
124961       return;
124962     }
124963   }else{
124964     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
124965     if( !pPtr ){
124966       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124967       sqlite3_result_error(context, zErr, -1);
124968       sqlite3_free(zErr);
124969       return;
124970     }
124971   }
124972
124973   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
124974 }
124975
124976 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
124977   static const char isFtsIdChar[] = {
124978       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
124979       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
124980       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
124981       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124982       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124983       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124984       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124985       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124986   };
124987   return (c&0x80 || isFtsIdChar[(int)(c)]);
124988 }
124989
124990 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
124991   const char *z1;
124992   const char *z2 = 0;
124993
124994   /* Find the start of the next token. */
124995   z1 = zStr;
124996   while( z2==0 ){
124997     char c = *z1;
124998     switch( c ){
124999       case '\0': return 0;        /* No more tokens here */
125000       case '\'':
125001       case '"':
125002       case '`': {
125003         z2 = z1;
125004         while( *++z2 && (*z2!=c || *++z2==c) );
125005         break;
125006       }
125007       case '[':
125008         z2 = &z1[1];
125009         while( *z2 && z2[0]!=']' ) z2++;
125010         if( *z2 ) z2++;
125011         break;
125012
125013       default:
125014         if( sqlite3Fts3IsIdChar(*z1) ){
125015           z2 = &z1[1];
125016           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
125017         }else{
125018           z1++;
125019         }
125020     }
125021   }
125022
125023   *pn = (int)(z2-z1);
125024   return z1;
125025 }
125026
125027 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
125028   Fts3Hash *pHash,                /* Tokenizer hash table */
125029   const char *zArg,               /* Tokenizer name */
125030   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
125031   char **pzErr                    /* OUT: Set to malloced error message */
125032 ){
125033   int rc;
125034   char *z = (char *)zArg;
125035   int n = 0;
125036   char *zCopy;
125037   char *zEnd;                     /* Pointer to nul-term of zCopy */
125038   sqlite3_tokenizer_module *m;
125039
125040   zCopy = sqlite3_mprintf("%s", zArg);
125041   if( !zCopy ) return SQLITE_NOMEM;
125042   zEnd = &zCopy[strlen(zCopy)];
125043
125044   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
125045   z[n] = '\0';
125046   sqlite3Fts3Dequote(z);
125047
125048   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
125049   if( !m ){
125050     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
125051     rc = SQLITE_ERROR;
125052   }else{
125053     char const **aArg = 0;
125054     int iArg = 0;
125055     z = &z[n+1];
125056     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
125057       int nNew = sizeof(char *)*(iArg+1);
125058       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
125059       if( !aNew ){
125060         sqlite3_free(zCopy);
125061         sqlite3_free((void *)aArg);
125062         return SQLITE_NOMEM;
125063       }
125064       aArg = aNew;
125065       aArg[iArg++] = z;
125066       z[n] = '\0';
125067       sqlite3Fts3Dequote(z);
125068       z = &z[n+1];
125069     }
125070     rc = m->xCreate(iArg, aArg, ppTok);
125071     assert( rc!=SQLITE_OK || *ppTok );
125072     if( rc!=SQLITE_OK ){
125073       *pzErr = sqlite3_mprintf("unknown tokenizer");
125074     }else{
125075       (*ppTok)->pModule = m; 
125076     }
125077     sqlite3_free((void *)aArg);
125078   }
125079
125080   sqlite3_free(zCopy);
125081   return rc;
125082 }
125083
125084
125085 #ifdef SQLITE_TEST
125086
125087 /* #include <tcl.h> */
125088 /* #include <string.h> */
125089
125090 /*
125091 ** Implementation of a special SQL scalar function for testing tokenizers 
125092 ** designed to be used in concert with the Tcl testing framework. This
125093 ** function must be called with two or more arguments:
125094 **
125095 **   SELECT <function-name>(<key-name>, ..., <input-string>);
125096 **
125097 ** where <function-name> is the name passed as the second argument
125098 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
125099 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
125100 **
125101 ** The return value is a string that may be interpreted as a Tcl
125102 ** list. For each token in the <input-string>, three elements are
125103 ** added to the returned list. The first is the token position, the 
125104 ** second is the token text (folded, stemmed, etc.) and the third is the
125105 ** substring of <input-string> associated with the token. For example, 
125106 ** using the built-in "simple" tokenizer:
125107 **
125108 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
125109 **
125110 ** will return the string:
125111 **
125112 **   "{0 i I 1 dont don't 2 see see 3 how how}"
125113 **   
125114 */
125115 static void testFunc(
125116   sqlite3_context *context,
125117   int argc,
125118   sqlite3_value **argv
125119 ){
125120   Fts3Hash *pHash;
125121   sqlite3_tokenizer_module *p;
125122   sqlite3_tokenizer *pTokenizer = 0;
125123   sqlite3_tokenizer_cursor *pCsr = 0;
125124
125125   const char *zErr = 0;
125126
125127   const char *zName;
125128   int nName;
125129   const char *zInput;
125130   int nInput;
125131
125132   const char *azArg[64];
125133
125134   const char *zToken;
125135   int nToken = 0;
125136   int iStart = 0;
125137   int iEnd = 0;
125138   int iPos = 0;
125139   int i;
125140
125141   Tcl_Obj *pRet;
125142
125143   if( argc<2 ){
125144     sqlite3_result_error(context, "insufficient arguments", -1);
125145     return;
125146   }
125147
125148   nName = sqlite3_value_bytes(argv[0]);
125149   zName = (const char *)sqlite3_value_text(argv[0]);
125150   nInput = sqlite3_value_bytes(argv[argc-1]);
125151   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
125152
125153   pHash = (Fts3Hash *)sqlite3_user_data(context);
125154   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
125155
125156   if( !p ){
125157     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125158     sqlite3_result_error(context, zErr, -1);
125159     sqlite3_free(zErr);
125160     return;
125161   }
125162
125163   pRet = Tcl_NewObj();
125164   Tcl_IncrRefCount(pRet);
125165
125166   for(i=1; i<argc-1; i++){
125167     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
125168   }
125169
125170   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
125171     zErr = "error in xCreate()";
125172     goto finish;
125173   }
125174   pTokenizer->pModule = p;
125175   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
125176     zErr = "error in xOpen()";
125177     goto finish;
125178   }
125179
125180   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
125181     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
125182     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125183     zToken = &zInput[iStart];
125184     nToken = iEnd-iStart;
125185     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125186   }
125187
125188   if( SQLITE_OK!=p->xClose(pCsr) ){
125189     zErr = "error in xClose()";
125190     goto finish;
125191   }
125192   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
125193     zErr = "error in xDestroy()";
125194     goto finish;
125195   }
125196
125197 finish:
125198   if( zErr ){
125199     sqlite3_result_error(context, zErr, -1);
125200   }else{
125201     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
125202   }
125203   Tcl_DecrRefCount(pRet);
125204 }
125205
125206 static
125207 int registerTokenizer(
125208   sqlite3 *db, 
125209   char *zName, 
125210   const sqlite3_tokenizer_module *p
125211 ){
125212   int rc;
125213   sqlite3_stmt *pStmt;
125214   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
125215
125216   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125217   if( rc!=SQLITE_OK ){
125218     return rc;
125219   }
125220
125221   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125222   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
125223   sqlite3_step(pStmt);
125224
125225   return sqlite3_finalize(pStmt);
125226 }
125227
125228 static
125229 int queryTokenizer(
125230   sqlite3 *db, 
125231   char *zName,  
125232   const sqlite3_tokenizer_module **pp
125233 ){
125234   int rc;
125235   sqlite3_stmt *pStmt;
125236   const char zSql[] = "SELECT fts3_tokenizer(?)";
125237
125238   *pp = 0;
125239   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125240   if( rc!=SQLITE_OK ){
125241     return rc;
125242   }
125243
125244   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125245   if( SQLITE_ROW==sqlite3_step(pStmt) ){
125246     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
125247       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
125248     }
125249   }
125250
125251   return sqlite3_finalize(pStmt);
125252 }
125253
125254 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
125255
125256 /*
125257 ** Implementation of the scalar function fts3_tokenizer_internal_test().
125258 ** This function is used for testing only, it is not included in the
125259 ** build unless SQLITE_TEST is defined.
125260 **
125261 ** The purpose of this is to test that the fts3_tokenizer() function
125262 ** can be used as designed by the C-code in the queryTokenizer and
125263 ** registerTokenizer() functions above. These two functions are repeated
125264 ** in the README.tokenizer file as an example, so it is important to
125265 ** test them.
125266 **
125267 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
125268 ** function with no arguments. An assert() will fail if a problem is
125269 ** detected. i.e.:
125270 **
125271 **     SELECT fts3_tokenizer_internal_test();
125272 **
125273 */
125274 static void intTestFunc(
125275   sqlite3_context *context,
125276   int argc,
125277   sqlite3_value **argv
125278 ){
125279   int rc;
125280   const sqlite3_tokenizer_module *p1;
125281   const sqlite3_tokenizer_module *p2;
125282   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
125283
125284   UNUSED_PARAMETER(argc);
125285   UNUSED_PARAMETER(argv);
125286
125287   /* Test the query function */
125288   sqlite3Fts3SimpleTokenizerModule(&p1);
125289   rc = queryTokenizer(db, "simple", &p2);
125290   assert( rc==SQLITE_OK );
125291   assert( p1==p2 );
125292   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125293   assert( rc==SQLITE_ERROR );
125294   assert( p2==0 );
125295   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
125296
125297   /* Test the storage function */
125298   rc = registerTokenizer(db, "nosuchtokenizer", p1);
125299   assert( rc==SQLITE_OK );
125300   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125301   assert( rc==SQLITE_OK );
125302   assert( p2==p1 );
125303
125304   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
125305 }
125306
125307 #endif
125308
125309 /*
125310 ** Set up SQL objects in database db used to access the contents of
125311 ** the hash table pointed to by argument pHash. The hash table must
125312 ** been initialised to use string keys, and to take a private copy 
125313 ** of the key when a value is inserted. i.e. by a call similar to:
125314 **
125315 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
125316 **
125317 ** This function adds a scalar function (see header comment above
125318 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
125319 ** defined at compilation time, a temporary virtual table (see header 
125320 ** comment above struct HashTableVtab) to the database schema. Both 
125321 ** provide read/write access to the contents of *pHash.
125322 **
125323 ** The third argument to this function, zName, is used as the name
125324 ** of both the scalar and, if created, the virtual table.
125325 */
125326 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
125327   sqlite3 *db, 
125328   Fts3Hash *pHash, 
125329   const char *zName
125330 ){
125331   int rc = SQLITE_OK;
125332   void *p = (void *)pHash;
125333   const int any = SQLITE_ANY;
125334
125335 #ifdef SQLITE_TEST
125336   char *zTest = 0;
125337   char *zTest2 = 0;
125338   void *pdb = (void *)db;
125339   zTest = sqlite3_mprintf("%s_test", zName);
125340   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
125341   if( !zTest || !zTest2 ){
125342     rc = SQLITE_NOMEM;
125343   }
125344 #endif
125345
125346   if( SQLITE_OK==rc ){
125347     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
125348   }
125349   if( SQLITE_OK==rc ){
125350     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
125351   }
125352 #ifdef SQLITE_TEST
125353   if( SQLITE_OK==rc ){
125354     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
125355   }
125356   if( SQLITE_OK==rc ){
125357     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
125358   }
125359 #endif
125360
125361 #ifdef SQLITE_TEST
125362   sqlite3_free(zTest);
125363   sqlite3_free(zTest2);
125364 #endif
125365
125366   return rc;
125367 }
125368
125369 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125370
125371 /************** End of fts3_tokenizer.c **************************************/
125372 /************** Begin file fts3_tokenizer1.c *********************************/
125373 /*
125374 ** 2006 Oct 10
125375 **
125376 ** The author disclaims copyright to this source code.  In place of
125377 ** a legal notice, here is a blessing:
125378 **
125379 **    May you do good and not evil.
125380 **    May you find forgiveness for yourself and forgive others.
125381 **    May you share freely, never taking more than you give.
125382 **
125383 ******************************************************************************
125384 **
125385 ** Implementation of the "simple" full-text-search tokenizer.
125386 */
125387
125388 /*
125389 ** The code in this file is only compiled if:
125390 **
125391 **     * The FTS3 module is being built as an extension
125392 **       (in which case SQLITE_CORE is not defined), or
125393 **
125394 **     * The FTS3 module is being built into the core of
125395 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125396 */
125397 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125398
125399 /* #include <assert.h> */
125400 /* #include <stdlib.h> */
125401 /* #include <stdio.h> */
125402 /* #include <string.h> */
125403
125404
125405 typedef struct simple_tokenizer {
125406   sqlite3_tokenizer base;
125407   char delim[128];             /* flag ASCII delimiters */
125408 } simple_tokenizer;
125409
125410 typedef struct simple_tokenizer_cursor {
125411   sqlite3_tokenizer_cursor base;
125412   const char *pInput;          /* input we are tokenizing */
125413   int nBytes;                  /* size of the input */
125414   int iOffset;                 /* current position in pInput */
125415   int iToken;                  /* index of next token to be returned */
125416   char *pToken;                /* storage for current token */
125417   int nTokenAllocated;         /* space allocated to zToken buffer */
125418 } simple_tokenizer_cursor;
125419
125420
125421 static int simpleDelim(simple_tokenizer *t, unsigned char c){
125422   return c<0x80 && t->delim[c];
125423 }
125424 static int fts3_isalnum(int x){
125425   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
125426 }
125427
125428 /*
125429 ** Create a new tokenizer instance.
125430 */
125431 static int simpleCreate(
125432   int argc, const char * const *argv,
125433   sqlite3_tokenizer **ppTokenizer
125434 ){
125435   simple_tokenizer *t;
125436
125437   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
125438   if( t==NULL ) return SQLITE_NOMEM;
125439   memset(t, 0, sizeof(*t));
125440
125441   /* TODO(shess) Delimiters need to remain the same from run to run,
125442   ** else we need to reindex.  One solution would be a meta-table to
125443   ** track such information in the database, then we'd only want this
125444   ** information on the initial create.
125445   */
125446   if( argc>1 ){
125447     int i, n = (int)strlen(argv[1]);
125448     for(i=0; i<n; i++){
125449       unsigned char ch = argv[1][i];
125450       /* We explicitly don't support UTF-8 delimiters for now. */
125451       if( ch>=0x80 ){
125452         sqlite3_free(t);
125453         return SQLITE_ERROR;
125454       }
125455       t->delim[ch] = 1;
125456     }
125457   } else {
125458     /* Mark non-alphanumeric ASCII characters as delimiters */
125459     int i;
125460     for(i=1; i<0x80; i++){
125461       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
125462     }
125463   }
125464
125465   *ppTokenizer = &t->base;
125466   return SQLITE_OK;
125467 }
125468
125469 /*
125470 ** Destroy a tokenizer
125471 */
125472 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
125473   sqlite3_free(pTokenizer);
125474   return SQLITE_OK;
125475 }
125476
125477 /*
125478 ** Prepare to begin tokenizing a particular string.  The input
125479 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
125480 ** used to incrementally tokenize this string is returned in 
125481 ** *ppCursor.
125482 */
125483 static int simpleOpen(
125484   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125485   const char *pInput, int nBytes,        /* String to be tokenized */
125486   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125487 ){
125488   simple_tokenizer_cursor *c;
125489
125490   UNUSED_PARAMETER(pTokenizer);
125491
125492   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
125493   if( c==NULL ) return SQLITE_NOMEM;
125494
125495   c->pInput = pInput;
125496   if( pInput==0 ){
125497     c->nBytes = 0;
125498   }else if( nBytes<0 ){
125499     c->nBytes = (int)strlen(pInput);
125500   }else{
125501     c->nBytes = nBytes;
125502   }
125503   c->iOffset = 0;                 /* start tokenizing at the beginning */
125504   c->iToken = 0;
125505   c->pToken = NULL;               /* no space allocated, yet. */
125506   c->nTokenAllocated = 0;
125507
125508   *ppCursor = &c->base;
125509   return SQLITE_OK;
125510 }
125511
125512 /*
125513 ** Close a tokenization cursor previously opened by a call to
125514 ** simpleOpen() above.
125515 */
125516 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
125517   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
125518   sqlite3_free(c->pToken);
125519   sqlite3_free(c);
125520   return SQLITE_OK;
125521 }
125522
125523 /*
125524 ** Extract the next token from a tokenization cursor.  The cursor must
125525 ** have been opened by a prior call to simpleOpen().
125526 */
125527 static int simpleNext(
125528   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
125529   const char **ppToken,               /* OUT: *ppToken is the token text */
125530   int *pnBytes,                       /* OUT: Number of bytes in token */
125531   int *piStartOffset,                 /* OUT: Starting offset of token */
125532   int *piEndOffset,                   /* OUT: Ending offset of token */
125533   int *piPosition                     /* OUT: Position integer of token */
125534 ){
125535   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
125536   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
125537   unsigned char *p = (unsigned char *)c->pInput;
125538
125539   while( c->iOffset<c->nBytes ){
125540     int iStartOffset;
125541
125542     /* Scan past delimiter characters */
125543     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
125544       c->iOffset++;
125545     }
125546
125547     /* Count non-delimiter characters. */
125548     iStartOffset = c->iOffset;
125549     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
125550       c->iOffset++;
125551     }
125552
125553     if( c->iOffset>iStartOffset ){
125554       int i, n = c->iOffset-iStartOffset;
125555       if( n>c->nTokenAllocated ){
125556         char *pNew;
125557         c->nTokenAllocated = n+20;
125558         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
125559         if( !pNew ) return SQLITE_NOMEM;
125560         c->pToken = pNew;
125561       }
125562       for(i=0; i<n; i++){
125563         /* TODO(shess) This needs expansion to handle UTF-8
125564         ** case-insensitivity.
125565         */
125566         unsigned char ch = p[iStartOffset+i];
125567         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
125568       }
125569       *ppToken = c->pToken;
125570       *pnBytes = n;
125571       *piStartOffset = iStartOffset;
125572       *piEndOffset = c->iOffset;
125573       *piPosition = c->iToken++;
125574
125575       return SQLITE_OK;
125576     }
125577   }
125578   return SQLITE_DONE;
125579 }
125580
125581 /*
125582 ** The set of routines that implement the simple tokenizer
125583 */
125584 static const sqlite3_tokenizer_module simpleTokenizerModule = {
125585   0,
125586   simpleCreate,
125587   simpleDestroy,
125588   simpleOpen,
125589   simpleClose,
125590   simpleNext,
125591   0,
125592 };
125593
125594 /*
125595 ** Allocate a new simple tokenizer.  Return a pointer to the new
125596 ** tokenizer in *ppModule
125597 */
125598 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
125599   sqlite3_tokenizer_module const**ppModule
125600 ){
125601   *ppModule = &simpleTokenizerModule;
125602 }
125603
125604 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125605
125606 /************** End of fts3_tokenizer1.c *************************************/
125607 /************** Begin file fts3_write.c **************************************/
125608 /*
125609 ** 2009 Oct 23
125610 **
125611 ** The author disclaims copyright to this source code.  In place of
125612 ** a legal notice, here is a blessing:
125613 **
125614 **    May you do good and not evil.
125615 **    May you find forgiveness for yourself and forgive others.
125616 **    May you share freely, never taking more than you give.
125617 **
125618 ******************************************************************************
125619 **
125620 ** This file is part of the SQLite FTS3 extension module. Specifically,
125621 ** this file contains code to insert, update and delete rows from FTS3
125622 ** tables. It also contains code to merge FTS3 b-tree segments. Some
125623 ** of the sub-routines used to merge segments are also used by the query 
125624 ** code in fts3.c.
125625 */
125626
125627 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125628
125629 /* #include <string.h> */
125630 /* #include <assert.h> */
125631 /* #include <stdlib.h> */
125632
125633
125634 #define FTS_MAX_APPENDABLE_HEIGHT 16
125635
125636 /*
125637 ** When full-text index nodes are loaded from disk, the buffer that they
125638 ** are loaded into has the following number of bytes of padding at the end 
125639 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
125640 ** of 920 bytes is allocated for it.
125641 **
125642 ** This means that if we have a pointer into a buffer containing node data,
125643 ** it is always safe to read up to two varints from it without risking an
125644 ** overread, even if the node data is corrupted.
125645 */
125646 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
125647
125648 /*
125649 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
125650 ** memory incrementally instead of all at once. This can be a big performance
125651 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
125652 ** method before retrieving all query results (as may happen, for example,
125653 ** if a query has a LIMIT clause).
125654 **
125655 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
125656 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
125657 ** The code is written so that the hard lower-limit for each of these values 
125658 ** is 1. Clearly such small values would be inefficient, but can be useful 
125659 ** for testing purposes.
125660 **
125661 ** If this module is built with SQLITE_TEST defined, these constants may
125662 ** be overridden at runtime for testing purposes. File fts3_test.c contains
125663 ** a Tcl interface to read and write the values.
125664 */
125665 #ifdef SQLITE_TEST
125666 int test_fts3_node_chunksize = (4*1024);
125667 int test_fts3_node_chunk_threshold = (4*1024)*4;
125668 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
125669 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
125670 #else
125671 # define FTS3_NODE_CHUNKSIZE (4*1024) 
125672 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
125673 #endif
125674
125675 /*
125676 ** The two values that may be meaningfully bound to the :1 parameter in
125677 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
125678 */
125679 #define FTS_STAT_DOCTOTAL      0
125680 #define FTS_STAT_INCRMERGEHINT 1
125681 #define FTS_STAT_AUTOINCRMERGE 2
125682
125683 /*
125684 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
125685 ** and incremental merge operation that takes place. This is used for 
125686 ** debugging FTS only, it should not usually be turned on in production
125687 ** systems.
125688 */
125689 #ifdef FTS3_LOG_MERGES
125690 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
125691   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
125692 }
125693 #else
125694 #define fts3LogMerge(x, y)
125695 #endif
125696
125697
125698 typedef struct PendingList PendingList;
125699 typedef struct SegmentNode SegmentNode;
125700 typedef struct SegmentWriter SegmentWriter;
125701
125702 /*
125703 ** An instance of the following data structure is used to build doclists
125704 ** incrementally. See function fts3PendingListAppend() for details.
125705 */
125706 struct PendingList {
125707   int nData;
125708   char *aData;
125709   int nSpace;
125710   sqlite3_int64 iLastDocid;
125711   sqlite3_int64 iLastCol;
125712   sqlite3_int64 iLastPos;
125713 };
125714
125715
125716 /*
125717 ** Each cursor has a (possibly empty) linked list of the following objects.
125718 */
125719 struct Fts3DeferredToken {
125720   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
125721   int iCol;                       /* Column token must occur in */
125722   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
125723   PendingList *pList;             /* Doclist is assembled here */
125724 };
125725
125726 /*
125727 ** An instance of this structure is used to iterate through the terms on
125728 ** a contiguous set of segment b-tree leaf nodes. Although the details of
125729 ** this structure are only manipulated by code in this file, opaque handles
125730 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
125731 ** terms when querying the full-text index. See functions:
125732 **
125733 **   sqlite3Fts3SegReaderNew()
125734 **   sqlite3Fts3SegReaderFree()
125735 **   sqlite3Fts3SegReaderIterate()
125736 **
125737 ** Methods used to manipulate Fts3SegReader structures:
125738 **
125739 **   fts3SegReaderNext()
125740 **   fts3SegReaderFirstDocid()
125741 **   fts3SegReaderNextDocid()
125742 */
125743 struct Fts3SegReader {
125744   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
125745   u8 bLookup;                     /* True for a lookup only */
125746   u8 rootOnly;                    /* True for a root-only reader */
125747
125748   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
125749   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
125750   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
125751   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
125752
125753   char *aNode;                    /* Pointer to node data (or NULL) */
125754   int nNode;                      /* Size of buffer at aNode (or 0) */
125755   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
125756   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
125757
125758   Fts3HashElem **ppNextElem;
125759
125760   /* Variables set by fts3SegReaderNext(). These may be read directly
125761   ** by the caller. They are valid from the time SegmentReaderNew() returns
125762   ** until SegmentReaderNext() returns something other than SQLITE_OK
125763   ** (i.e. SQLITE_DONE).
125764   */
125765   int nTerm;                      /* Number of bytes in current term */
125766   char *zTerm;                    /* Pointer to current term */
125767   int nTermAlloc;                 /* Allocated size of zTerm buffer */
125768   char *aDoclist;                 /* Pointer to doclist of current entry */
125769   int nDoclist;                   /* Size of doclist in current entry */
125770
125771   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
125772   ** through the current doclist (aDoclist/nDoclist).
125773   */
125774   char *pOffsetList;
125775   int nOffsetList;                /* For descending pending seg-readers only */
125776   sqlite3_int64 iDocid;
125777 };
125778
125779 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
125780 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
125781
125782 /*
125783 ** An instance of this structure is used to create a segment b-tree in the
125784 ** database. The internal details of this type are only accessed by the
125785 ** following functions:
125786 **
125787 **   fts3SegWriterAdd()
125788 **   fts3SegWriterFlush()
125789 **   fts3SegWriterFree()
125790 */
125791 struct SegmentWriter {
125792   SegmentNode *pTree;             /* Pointer to interior tree structure */
125793   sqlite3_int64 iFirst;           /* First slot in %_segments written */
125794   sqlite3_int64 iFree;            /* Next free slot in %_segments */
125795   char *zTerm;                    /* Pointer to previous term buffer */
125796   int nTerm;                      /* Number of bytes in zTerm */
125797   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125798   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125799   int nSize;                      /* Size of allocation at aData */
125800   int nData;                      /* Bytes of data in aData */
125801   char *aData;                    /* Pointer to block from malloc() */
125802 };
125803
125804 /*
125805 ** Type SegmentNode is used by the following three functions to create
125806 ** the interior part of the segment b+-tree structures (everything except
125807 ** the leaf nodes). These functions and type are only ever used by code
125808 ** within the fts3SegWriterXXX() family of functions described above.
125809 **
125810 **   fts3NodeAddTerm()
125811 **   fts3NodeWrite()
125812 **   fts3NodeFree()
125813 **
125814 ** When a b+tree is written to the database (either as a result of a merge
125815 ** or the pending-terms table being flushed), leaves are written into the 
125816 ** database file as soon as they are completely populated. The interior of
125817 ** the tree is assembled in memory and written out only once all leaves have
125818 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
125819 ** very large, meaning that the interior of the tree consumes relatively 
125820 ** little memory.
125821 */
125822 struct SegmentNode {
125823   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
125824   SegmentNode *pRight;            /* Pointer to right-sibling */
125825   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
125826   int nEntry;                     /* Number of terms written to node so far */
125827   char *zTerm;                    /* Pointer to previous term buffer */
125828   int nTerm;                      /* Number of bytes in zTerm */
125829   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125830   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125831   int nData;                      /* Bytes of valid data so far */
125832   char *aData;                    /* Node data */
125833 };
125834
125835 /*
125836 ** Valid values for the second argument to fts3SqlStmt().
125837 */
125838 #define SQL_DELETE_CONTENT             0
125839 #define SQL_IS_EMPTY                   1
125840 #define SQL_DELETE_ALL_CONTENT         2 
125841 #define SQL_DELETE_ALL_SEGMENTS        3
125842 #define SQL_DELETE_ALL_SEGDIR          4
125843 #define SQL_DELETE_ALL_DOCSIZE         5
125844 #define SQL_DELETE_ALL_STAT            6
125845 #define SQL_SELECT_CONTENT_BY_ROWID    7
125846 #define SQL_NEXT_SEGMENT_INDEX         8
125847 #define SQL_INSERT_SEGMENTS            9
125848 #define SQL_NEXT_SEGMENTS_ID          10
125849 #define SQL_INSERT_SEGDIR             11
125850 #define SQL_SELECT_LEVEL              12
125851 #define SQL_SELECT_LEVEL_RANGE        13
125852 #define SQL_SELECT_LEVEL_COUNT        14
125853 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
125854 #define SQL_DELETE_SEGDIR_LEVEL       16
125855 #define SQL_DELETE_SEGMENTS_RANGE     17
125856 #define SQL_CONTENT_INSERT            18
125857 #define SQL_DELETE_DOCSIZE            19
125858 #define SQL_REPLACE_DOCSIZE           20
125859 #define SQL_SELECT_DOCSIZE            21
125860 #define SQL_SELECT_STAT               22
125861 #define SQL_REPLACE_STAT              23
125862
125863 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
125864 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
125865 #define SQL_DELETE_SEGDIR_RANGE       26
125866 #define SQL_SELECT_ALL_LANGID         27
125867 #define SQL_FIND_MERGE_LEVEL          28
125868 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
125869 #define SQL_DELETE_SEGDIR_ENTRY       30
125870 #define SQL_SHIFT_SEGDIR_ENTRY        31
125871 #define SQL_SELECT_SEGDIR             32
125872 #define SQL_CHOMP_SEGDIR              33
125873 #define SQL_SEGMENT_IS_APPENDABLE     34
125874 #define SQL_SELECT_INDEXES            35
125875 #define SQL_SELECT_MXLEVEL            36
125876
125877 /*
125878 ** This function is used to obtain an SQLite prepared statement handle
125879 ** for the statement identified by the second argument. If successful,
125880 ** *pp is set to the requested statement handle and SQLITE_OK returned.
125881 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
125882 **
125883 ** If argument apVal is not NULL, then it must point to an array with
125884 ** at least as many entries as the requested statement has bound 
125885 ** parameters. The values are bound to the statements parameters before
125886 ** returning.
125887 */
125888 static int fts3SqlStmt(
125889   Fts3Table *p,                   /* Virtual table handle */
125890   int eStmt,                      /* One of the SQL_XXX constants above */
125891   sqlite3_stmt **pp,              /* OUT: Statement handle */
125892   sqlite3_value **apVal           /* Values to bind to statement */
125893 ){
125894   const char *azSql[] = {
125895 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
125896 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
125897 /* 2  */  "DELETE FROM %Q.'%q_content'",
125898 /* 3  */  "DELETE FROM %Q.'%q_segments'",
125899 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
125900 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
125901 /* 6  */  "DELETE FROM %Q.'%q_stat'",
125902 /* 7  */  "SELECT %s WHERE rowid=?",
125903 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
125904 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
125905 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
125906 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
125907
125908           /* Return segments in order from oldest to newest.*/ 
125909 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125910             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
125911 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125912             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
125913             "ORDER BY level DESC, idx ASC",
125914
125915 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
125916 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125917
125918 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
125919 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
125920 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
125921 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
125922 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
125923 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
125924 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
125925 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
125926 /* 24 */  "",
125927 /* 25 */  "",
125928
125929 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125930 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
125931
125932 /* This statement is used to determine which level to read the input from
125933 ** when performing an incremental merge. It returns the absolute level number
125934 ** of the oldest level in the db that contains at least ? segments. Or,
125935 ** if no level in the FTS index contains more than ? segments, the statement
125936 ** returns zero rows.  */
125937 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
125938          "  ORDER BY (level %% 1024) ASC LIMIT 1",
125939
125940 /* Estimate the upper limit on the number of leaf nodes in a new segment
125941 ** created by merging the oldest :2 segments from absolute level :1. See 
125942 ** function sqlite3Fts3Incrmerge() for details.  */
125943 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
125944          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
125945
125946 /* SQL_DELETE_SEGDIR_ENTRY
125947 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
125948 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
125949
125950 /* SQL_SHIFT_SEGDIR_ENTRY
125951 **   Modify the idx value for the segment with idx=:3 on absolute level :2
125952 **   to :1.  */
125953 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
125954
125955 /* SQL_SELECT_SEGDIR
125956 **   Read a single entry from the %_segdir table. The entry from absolute 
125957 **   level :1 with index value :2.  */
125958 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125959             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
125960
125961 /* SQL_CHOMP_SEGDIR
125962 **   Update the start_block (:1) and root (:2) fields of the %_segdir
125963 **   entry located on absolute level :3 with index :4.  */
125964 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
125965             "WHERE level = ? AND idx = ?",
125966
125967 /* SQL_SEGMENT_IS_APPENDABLE
125968 **   Return a single row if the segment with end_block=? is appendable. Or
125969 **   no rows otherwise.  */
125970 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
125971
125972 /* SQL_SELECT_INDEXES
125973 **   Return the list of valid segment indexes for absolute level ?  */
125974 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
125975
125976 /* SQL_SELECT_MXLEVEL
125977 **   Return the largest relative level in the FTS index or indexes.  */
125978 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
125979   };
125980   int rc = SQLITE_OK;
125981   sqlite3_stmt *pStmt;
125982
125983   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
125984   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
125985   
125986   pStmt = p->aStmt[eStmt];
125987   if( !pStmt ){
125988     char *zSql;
125989     if( eStmt==SQL_CONTENT_INSERT ){
125990       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
125991     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
125992       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
125993     }else{
125994       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
125995     }
125996     if( !zSql ){
125997       rc = SQLITE_NOMEM;
125998     }else{
125999       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
126000       sqlite3_free(zSql);
126001       assert( rc==SQLITE_OK || pStmt==0 );
126002       p->aStmt[eStmt] = pStmt;
126003     }
126004   }
126005   if( apVal ){
126006     int i;
126007     int nParam = sqlite3_bind_parameter_count(pStmt);
126008     for(i=0; rc==SQLITE_OK && i<nParam; i++){
126009       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
126010     }
126011   }
126012   *pp = pStmt;
126013   return rc;
126014 }
126015
126016
126017 static int fts3SelectDocsize(
126018   Fts3Table *pTab,                /* FTS3 table handle */
126019   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
126020   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126021 ){
126022   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
126023   int rc;                         /* Return code */
126024
126025   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
126026   if( rc==SQLITE_OK ){
126027     sqlite3_bind_int64(pStmt, 1, iDocid);
126028     rc = sqlite3_step(pStmt);
126029     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
126030       rc = sqlite3_reset(pStmt);
126031       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126032       pStmt = 0;
126033     }else{
126034       rc = SQLITE_OK;
126035     }
126036   }
126037
126038   *ppStmt = pStmt;
126039   return rc;
126040 }
126041
126042 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
126043   Fts3Table *pTab,                /* Fts3 table handle */
126044   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126045 ){
126046   sqlite3_stmt *pStmt = 0;
126047   int rc;
126048   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
126049   if( rc==SQLITE_OK ){
126050     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
126051     if( sqlite3_step(pStmt)!=SQLITE_ROW
126052      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
126053     ){
126054       rc = sqlite3_reset(pStmt);
126055       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126056       pStmt = 0;
126057     }
126058   }
126059   *ppStmt = pStmt;
126060   return rc;
126061 }
126062
126063 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
126064   Fts3Table *pTab,                /* Fts3 table handle */
126065   sqlite3_int64 iDocid,           /* Docid to read size data for */
126066   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126067 ){
126068   return fts3SelectDocsize(pTab, iDocid, ppStmt);
126069 }
126070
126071 /*
126072 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
126073 ** array apVal[] to the SQL statement identified by eStmt, the statement
126074 ** is executed.
126075 **
126076 ** Returns SQLITE_OK if the statement is successfully executed, or an
126077 ** SQLite error code otherwise.
126078 */
126079 static void fts3SqlExec(
126080   int *pRC,                /* Result code */
126081   Fts3Table *p,            /* The FTS3 table */
126082   int eStmt,               /* Index of statement to evaluate */
126083   sqlite3_value **apVal    /* Parameters to bind */
126084 ){
126085   sqlite3_stmt *pStmt;
126086   int rc;
126087   if( *pRC ) return;
126088   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
126089   if( rc==SQLITE_OK ){
126090     sqlite3_step(pStmt);
126091     rc = sqlite3_reset(pStmt);
126092   }
126093   *pRC = rc;
126094 }
126095
126096
126097 /*
126098 ** This function ensures that the caller has obtained a shared-cache
126099 ** table-lock on the %_content table. This is required before reading
126100 ** data from the fts3 table. If this lock is not acquired first, then
126101 ** the caller may end up holding read-locks on the %_segments and %_segdir
126102 ** tables, but no read-lock on the %_content table. If this happens 
126103 ** a second connection will be able to write to the fts3 table, but
126104 ** attempting to commit those writes might return SQLITE_LOCKED or
126105 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
126106 ** write-locks on the %_segments and %_segdir ** tables). 
126107 **
126108 ** We try to avoid this because if FTS3 returns any error when committing
126109 ** a transaction, the whole transaction will be rolled back. And this is
126110 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
126111 ** still happen if the user reads data directly from the %_segments or
126112 ** %_segdir tables instead of going through FTS3 though.
126113 **
126114 ** This reasoning does not apply to a content=xxx table.
126115 */
126116 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
126117   int rc;                         /* Return code */
126118   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
126119
126120   if( p->zContentTbl==0 ){
126121     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
126122     if( rc==SQLITE_OK ){
126123       sqlite3_bind_null(pStmt, 1);
126124       sqlite3_step(pStmt);
126125       rc = sqlite3_reset(pStmt);
126126     }
126127   }else{
126128     rc = SQLITE_OK;
126129   }
126130
126131   return rc;
126132 }
126133
126134 /*
126135 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
126136 ** Within each language id, a separate index is maintained to store the
126137 ** document terms, and each configured prefix size (configured the FTS 
126138 ** "prefix=" option). And each index consists of multiple levels ("relative
126139 ** levels").
126140 **
126141 ** All three of these values (the language id, the specific index and the
126142 ** level within the index) are encoded in 64-bit integer values stored
126143 ** in the %_segdir table on disk. This function is used to convert three
126144 ** separate component values into the single 64-bit integer value that
126145 ** can be used to query the %_segdir table.
126146 **
126147 ** Specifically, each language-id/index combination is allocated 1024 
126148 ** 64-bit integer level values ("absolute levels"). The main terms index
126149 ** for language-id 0 is allocate values 0-1023. The first prefix index
126150 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
126151 ** Language 1 indexes are allocated immediately following language 0.
126152 **
126153 ** So, for a system with nPrefix prefix indexes configured, the block of
126154 ** absolute levels that corresponds to language-id iLangid and index 
126155 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
126156 */
126157 static sqlite3_int64 getAbsoluteLevel(
126158   Fts3Table *p,                   /* FTS3 table handle */
126159   int iLangid,                    /* Language id */
126160   int iIndex,                     /* Index in p->aIndex[] */
126161   int iLevel                      /* Level of segments */
126162 ){
126163   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
126164   assert( iLangid>=0 );
126165   assert( p->nIndex>0 );
126166   assert( iIndex>=0 && iIndex<p->nIndex );
126167
126168   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
126169   return iBase + iLevel;
126170 }
126171
126172 /*
126173 ** Set *ppStmt to a statement handle that may be used to iterate through
126174 ** all rows in the %_segdir table, from oldest to newest. If successful,
126175 ** return SQLITE_OK. If an error occurs while preparing the statement, 
126176 ** return an SQLite error code.
126177 **
126178 ** There is only ever one instance of this SQL statement compiled for
126179 ** each FTS3 table.
126180 **
126181 ** The statement returns the following columns from the %_segdir table:
126182 **
126183 **   0: idx
126184 **   1: start_block
126185 **   2: leaves_end_block
126186 **   3: end_block
126187 **   4: root
126188 */
126189 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
126190   Fts3Table *p,                   /* FTS3 table */
126191   int iLangid,                    /* Language being queried */
126192   int iIndex,                     /* Index for p->aIndex[] */
126193   int iLevel,                     /* Level to select (relative level) */
126194   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
126195 ){
126196   int rc;
126197   sqlite3_stmt *pStmt = 0;
126198
126199   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
126200   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
126201   assert( iIndex>=0 && iIndex<p->nIndex );
126202
126203   if( iLevel<0 ){
126204     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
126205     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
126206     if( rc==SQLITE_OK ){ 
126207       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
126208       sqlite3_bind_int64(pStmt, 2, 
126209           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
126210       );
126211     }
126212   }else{
126213     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
126214     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
126215     if( rc==SQLITE_OK ){ 
126216       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
126217     }
126218   }
126219   *ppStmt = pStmt;
126220   return rc;
126221 }
126222
126223
126224 /*
126225 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
126226 ** if successful, or an SQLite error code otherwise.
126227 **
126228 ** This function also serves to allocate the PendingList structure itself.
126229 ** For example, to create a new PendingList structure containing two
126230 ** varints:
126231 **
126232 **   PendingList *p = 0;
126233 **   fts3PendingListAppendVarint(&p, 1);
126234 **   fts3PendingListAppendVarint(&p, 2);
126235 */
126236 static int fts3PendingListAppendVarint(
126237   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
126238   sqlite3_int64 i                 /* Value to append to data */
126239 ){
126240   PendingList *p = *pp;
126241
126242   /* Allocate or grow the PendingList as required. */
126243   if( !p ){
126244     p = sqlite3_malloc(sizeof(*p) + 100);
126245     if( !p ){
126246       return SQLITE_NOMEM;
126247     }
126248     p->nSpace = 100;
126249     p->aData = (char *)&p[1];
126250     p->nData = 0;
126251   }
126252   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
126253     int nNew = p->nSpace * 2;
126254     p = sqlite3_realloc(p, sizeof(*p) + nNew);
126255     if( !p ){
126256       sqlite3_free(*pp);
126257       *pp = 0;
126258       return SQLITE_NOMEM;
126259     }
126260     p->nSpace = nNew;
126261     p->aData = (char *)&p[1];
126262   }
126263
126264   /* Append the new serialized varint to the end of the list. */
126265   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
126266   p->aData[p->nData] = '\0';
126267   *pp = p;
126268   return SQLITE_OK;
126269 }
126270
126271 /*
126272 ** Add a docid/column/position entry to a PendingList structure. Non-zero
126273 ** is returned if the structure is sqlite3_realloced as part of adding
126274 ** the entry. Otherwise, zero.
126275 **
126276 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
126277 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
126278 ** it is set to SQLITE_OK.
126279 */
126280 static int fts3PendingListAppend(
126281   PendingList **pp,               /* IN/OUT: PendingList structure */
126282   sqlite3_int64 iDocid,           /* Docid for entry to add */
126283   sqlite3_int64 iCol,             /* Column for entry to add */
126284   sqlite3_int64 iPos,             /* Position of term for entry to add */
126285   int *pRc                        /* OUT: Return code */
126286 ){
126287   PendingList *p = *pp;
126288   int rc = SQLITE_OK;
126289
126290   assert( !p || p->iLastDocid<=iDocid );
126291
126292   if( !p || p->iLastDocid!=iDocid ){
126293     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
126294     if( p ){
126295       assert( p->nData<p->nSpace );
126296       assert( p->aData[p->nData]==0 );
126297       p->nData++;
126298     }
126299     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
126300       goto pendinglistappend_out;
126301     }
126302     p->iLastCol = -1;
126303     p->iLastPos = 0;
126304     p->iLastDocid = iDocid;
126305   }
126306   if( iCol>0 && p->iLastCol!=iCol ){
126307     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
126308      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
126309     ){
126310       goto pendinglistappend_out;
126311     }
126312     p->iLastCol = iCol;
126313     p->iLastPos = 0;
126314   }
126315   if( iCol>=0 ){
126316     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
126317     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
126318     if( rc==SQLITE_OK ){
126319       p->iLastPos = iPos;
126320     }
126321   }
126322
126323  pendinglistappend_out:
126324   *pRc = rc;
126325   if( p!=*pp ){
126326     *pp = p;
126327     return 1;
126328   }
126329   return 0;
126330 }
126331
126332 /*
126333 ** Free a PendingList object allocated by fts3PendingListAppend().
126334 */
126335 static void fts3PendingListDelete(PendingList *pList){
126336   sqlite3_free(pList);
126337 }
126338
126339 /*
126340 ** Add an entry to one of the pending-terms hash tables.
126341 */
126342 static int fts3PendingTermsAddOne(
126343   Fts3Table *p,
126344   int iCol,
126345   int iPos,
126346   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
126347   const char *zToken,
126348   int nToken
126349 ){
126350   PendingList *pList;
126351   int rc = SQLITE_OK;
126352
126353   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
126354   if( pList ){
126355     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
126356   }
126357   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
126358     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
126359       /* Malloc failed while inserting the new entry. This can only 
126360       ** happen if there was no previous entry for this token.
126361       */
126362       assert( 0==fts3HashFind(pHash, zToken, nToken) );
126363       sqlite3_free(pList);
126364       rc = SQLITE_NOMEM;
126365     }
126366   }
126367   if( rc==SQLITE_OK ){
126368     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
126369   }
126370   return rc;
126371 }
126372
126373 /*
126374 ** Tokenize the nul-terminated string zText and add all tokens to the
126375 ** pending-terms hash-table. The docid used is that currently stored in
126376 ** p->iPrevDocid, and the column is specified by argument iCol.
126377 **
126378 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
126379 */
126380 static int fts3PendingTermsAdd(
126381   Fts3Table *p,                   /* Table into which text will be inserted */
126382   int iLangid,                    /* Language id to use */
126383   const char *zText,              /* Text of document to be inserted */
126384   int iCol,                       /* Column into which text is being inserted */
126385   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
126386 ){
126387   int rc;
126388   int iStart = 0;
126389   int iEnd = 0;
126390   int iPos = 0;
126391   int nWord = 0;
126392
126393   char const *zToken;
126394   int nToken = 0;
126395
126396   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
126397   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
126398   sqlite3_tokenizer_cursor *pCsr;
126399   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
126400       const char**,int*,int*,int*,int*);
126401
126402   assert( pTokenizer && pModule );
126403
126404   /* If the user has inserted a NULL value, this function may be called with
126405   ** zText==0. In this case, add zero token entries to the hash table and 
126406   ** return early. */
126407   if( zText==0 ){
126408     *pnWord = 0;
126409     return SQLITE_OK;
126410   }
126411
126412   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
126413   if( rc!=SQLITE_OK ){
126414     return rc;
126415   }
126416
126417   xNext = pModule->xNext;
126418   while( SQLITE_OK==rc
126419       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
126420   ){
126421     int i;
126422     if( iPos>=nWord ) nWord = iPos+1;
126423
126424     /* Positions cannot be negative; we use -1 as a terminator internally.
126425     ** Tokens must have a non-zero length.
126426     */
126427     if( iPos<0 || !zToken || nToken<=0 ){
126428       rc = SQLITE_ERROR;
126429       break;
126430     }
126431
126432     /* Add the term to the terms index */
126433     rc = fts3PendingTermsAddOne(
126434         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
126435     );
126436     
126437     /* Add the term to each of the prefix indexes that it is not too 
126438     ** short for. */
126439     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
126440       struct Fts3Index *pIndex = &p->aIndex[i];
126441       if( nToken<pIndex->nPrefix ) continue;
126442       rc = fts3PendingTermsAddOne(
126443           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
126444       );
126445     }
126446   }
126447
126448   pModule->xClose(pCsr);
126449   *pnWord += nWord;
126450   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
126451 }
126452
126453 /* 
126454 ** Calling this function indicates that subsequent calls to 
126455 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
126456 ** contents of the document with docid iDocid.
126457 */
126458 static int fts3PendingTermsDocid(
126459   Fts3Table *p,                   /* Full-text table handle */
126460   int iLangid,                    /* Language id of row being written */
126461   sqlite_int64 iDocid             /* Docid of row being written */
126462 ){
126463   assert( iLangid>=0 );
126464
126465   /* TODO(shess) Explore whether partially flushing the buffer on
126466   ** forced-flush would provide better performance.  I suspect that if
126467   ** we ordered the doclists by size and flushed the largest until the
126468   ** buffer was half empty, that would let the less frequent terms
126469   ** generate longer doclists.
126470   */
126471   if( iDocid<=p->iPrevDocid 
126472    || p->iPrevLangid!=iLangid
126473    || p->nPendingData>p->nMaxPendingData 
126474   ){
126475     int rc = sqlite3Fts3PendingTermsFlush(p);
126476     if( rc!=SQLITE_OK ) return rc;
126477   }
126478   p->iPrevDocid = iDocid;
126479   p->iPrevLangid = iLangid;
126480   return SQLITE_OK;
126481 }
126482
126483 /*
126484 ** Discard the contents of the pending-terms hash tables. 
126485 */
126486 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
126487   int i;
126488   for(i=0; i<p->nIndex; i++){
126489     Fts3HashElem *pElem;
126490     Fts3Hash *pHash = &p->aIndex[i].hPending;
126491     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
126492       PendingList *pList = (PendingList *)fts3HashData(pElem);
126493       fts3PendingListDelete(pList);
126494     }
126495     fts3HashClear(pHash);
126496   }
126497   p->nPendingData = 0;
126498 }
126499
126500 /*
126501 ** This function is called by the xUpdate() method as part of an INSERT
126502 ** operation. It adds entries for each term in the new record to the
126503 ** pendingTerms hash table.
126504 **
126505 ** Argument apVal is the same as the similarly named argument passed to
126506 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
126507 */
126508 static int fts3InsertTerms(
126509   Fts3Table *p, 
126510   int iLangid, 
126511   sqlite3_value **apVal, 
126512   u32 *aSz
126513 ){
126514   int i;                          /* Iterator variable */
126515   for(i=2; i<p->nColumn+2; i++){
126516     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
126517     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
126518     if( rc!=SQLITE_OK ){
126519       return rc;
126520     }
126521     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
126522   }
126523   return SQLITE_OK;
126524 }
126525
126526 /*
126527 ** This function is called by the xUpdate() method for an INSERT operation.
126528 ** The apVal parameter is passed a copy of the apVal argument passed by
126529 ** SQLite to the xUpdate() method. i.e:
126530 **
126531 **   apVal[0]                Not used for INSERT.
126532 **   apVal[1]                rowid
126533 **   apVal[2]                Left-most user-defined column
126534 **   ...
126535 **   apVal[p->nColumn+1]     Right-most user-defined column
126536 **   apVal[p->nColumn+2]     Hidden column with same name as table
126537 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
126538 **   apVal[p->nColumn+4]     Hidden languageid column
126539 */
126540 static int fts3InsertData(
126541   Fts3Table *p,                   /* Full-text table */
126542   sqlite3_value **apVal,          /* Array of values to insert */
126543   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
126544 ){
126545   int rc;                         /* Return code */
126546   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
126547
126548   if( p->zContentTbl ){
126549     sqlite3_value *pRowid = apVal[p->nColumn+3];
126550     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
126551       pRowid = apVal[1];
126552     }
126553     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
126554       return SQLITE_CONSTRAINT;
126555     }
126556     *piDocid = sqlite3_value_int64(pRowid);
126557     return SQLITE_OK;
126558   }
126559
126560   /* Locate the statement handle used to insert data into the %_content
126561   ** table. The SQL for this statement is:
126562   **
126563   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
126564   **
126565   ** The statement features N '?' variables, where N is the number of user
126566   ** defined columns in the FTS3 table, plus one for the docid field.
126567   */
126568   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
126569   if( rc==SQLITE_OK && p->zLanguageid ){
126570     rc = sqlite3_bind_int(
126571         pContentInsert, p->nColumn+2, 
126572         sqlite3_value_int(apVal[p->nColumn+4])
126573     );
126574   }
126575   if( rc!=SQLITE_OK ) return rc;
126576
126577   /* There is a quirk here. The users INSERT statement may have specified
126578   ** a value for the "rowid" field, for the "docid" field, or for both.
126579   ** Which is a problem, since "rowid" and "docid" are aliases for the
126580   ** same value. For example:
126581   **
126582   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
126583   **
126584   ** In FTS3, this is an error. It is an error to specify non-NULL values
126585   ** for both docid and some other rowid alias.
126586   */
126587   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
126588     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
126589      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
126590     ){
126591       /* A rowid/docid conflict. */
126592       return SQLITE_ERROR;
126593     }
126594     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
126595     if( rc!=SQLITE_OK ) return rc;
126596   }
126597
126598   /* Execute the statement to insert the record. Set *piDocid to the 
126599   ** new docid value. 
126600   */
126601   sqlite3_step(pContentInsert);
126602   rc = sqlite3_reset(pContentInsert);
126603
126604   *piDocid = sqlite3_last_insert_rowid(p->db);
126605   return rc;
126606 }
126607
126608
126609
126610 /*
126611 ** Remove all data from the FTS3 table. Clear the hash table containing
126612 ** pending terms.
126613 */
126614 static int fts3DeleteAll(Fts3Table *p, int bContent){
126615   int rc = SQLITE_OK;             /* Return code */
126616
126617   /* Discard the contents of the pending-terms hash table. */
126618   sqlite3Fts3PendingTermsClear(p);
126619
126620   /* Delete everything from the shadow tables. Except, leave %_content as
126621   ** is if bContent is false.  */
126622   assert( p->zContentTbl==0 || bContent==0 );
126623   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
126624   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
126625   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
126626   if( p->bHasDocsize ){
126627     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
126628   }
126629   if( p->bHasStat ){
126630     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
126631   }
126632   return rc;
126633 }
126634
126635 /*
126636 **
126637 */
126638 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
126639   int iLangid = 0;
126640   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
126641   return iLangid;
126642 }
126643
126644 /*
126645 ** The first element in the apVal[] array is assumed to contain the docid
126646 ** (an integer) of a row about to be deleted. Remove all terms from the
126647 ** full-text index.
126648 */
126649 static void fts3DeleteTerms( 
126650   int *pRC,               /* Result code */
126651   Fts3Table *p,           /* The FTS table to delete from */
126652   sqlite3_value *pRowid,  /* The docid to be deleted */
126653   u32 *aSz,               /* Sizes of deleted document written here */
126654   int *pbFound            /* OUT: Set to true if row really does exist */
126655 ){
126656   int rc;
126657   sqlite3_stmt *pSelect;
126658
126659   assert( *pbFound==0 );
126660   if( *pRC ) return;
126661   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
126662   if( rc==SQLITE_OK ){
126663     if( SQLITE_ROW==sqlite3_step(pSelect) ){
126664       int i;
126665       int iLangid = langidFromSelect(p, pSelect);
126666       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
126667       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
126668         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
126669         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
126670         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
126671       }
126672       if( rc!=SQLITE_OK ){
126673         sqlite3_reset(pSelect);
126674         *pRC = rc;
126675         return;
126676       }
126677       *pbFound = 1;
126678     }
126679     rc = sqlite3_reset(pSelect);
126680   }else{
126681     sqlite3_reset(pSelect);
126682   }
126683   *pRC = rc;
126684 }
126685
126686 /*
126687 ** Forward declaration to account for the circular dependency between
126688 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
126689 */
126690 static int fts3SegmentMerge(Fts3Table *, int, int, int);
126691
126692 /* 
126693 ** This function allocates a new level iLevel index in the segdir table.
126694 ** Usually, indexes are allocated within a level sequentially starting
126695 ** with 0, so the allocated index is one greater than the value returned
126696 ** by:
126697 **
126698 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
126699 **
126700 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
126701 ** level, they are merged into a single level (iLevel+1) segment and the 
126702 ** allocated index is 0.
126703 **
126704 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
126705 ** returned. Otherwise, an SQLite error code is returned.
126706 */
126707 static int fts3AllocateSegdirIdx(
126708   Fts3Table *p, 
126709   int iLangid,                    /* Language id */
126710   int iIndex,                     /* Index for p->aIndex */
126711   int iLevel, 
126712   int *piIdx
126713 ){
126714   int rc;                         /* Return Code */
126715   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
126716   int iNext = 0;                  /* Result of query pNextIdx */
126717
126718   assert( iLangid>=0 );
126719   assert( p->nIndex>=1 );
126720
126721   /* Set variable iNext to the next available segdir index at level iLevel. */
126722   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
126723   if( rc==SQLITE_OK ){
126724     sqlite3_bind_int64(
126725         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
126726     );
126727     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
126728       iNext = sqlite3_column_int(pNextIdx, 0);
126729     }
126730     rc = sqlite3_reset(pNextIdx);
126731   }
126732
126733   if( rc==SQLITE_OK ){
126734     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
126735     ** full, merge all segments in level iLevel into a single iLevel+1
126736     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
126737     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
126738     */
126739     if( iNext>=FTS3_MERGE_COUNT ){
126740       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
126741       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
126742       *piIdx = 0;
126743     }else{
126744       *piIdx = iNext;
126745     }
126746   }
126747
126748   return rc;
126749 }
126750
126751 /*
126752 ** The %_segments table is declared as follows:
126753 **
126754 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
126755 **
126756 ** This function reads data from a single row of the %_segments table. The
126757 ** specific row is identified by the iBlockid parameter. If paBlob is not
126758 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
126759 ** with the contents of the blob stored in the "block" column of the 
126760 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
126761 ** to the size of the blob in bytes before returning.
126762 **
126763 ** If an error occurs, or the table does not contain the specified row,
126764 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
126765 ** paBlob is non-NULL, then it is the responsibility of the caller to
126766 ** eventually free the returned buffer.
126767 **
126768 ** This function may leave an open sqlite3_blob* handle in the
126769 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
126770 ** to this function. The handle may be closed by calling the
126771 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
126772 ** performance improvement, but the blob handle should always be closed
126773 ** before control is returned to the user (to prevent a lock being held
126774 ** on the database file for longer than necessary). Thus, any virtual table
126775 ** method (xFilter etc.) that may directly or indirectly call this function
126776 ** must call sqlite3Fts3SegmentsClose() before returning.
126777 */
126778 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
126779   Fts3Table *p,                   /* FTS3 table handle */
126780   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
126781   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
126782   int *pnBlob,                    /* OUT: Size of blob data */
126783   int *pnLoad                     /* OUT: Bytes actually loaded */
126784 ){
126785   int rc;                         /* Return code */
126786
126787   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
126788   assert( pnBlob );
126789
126790   if( p->pSegments ){
126791     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
126792   }else{
126793     if( 0==p->zSegmentsTbl ){
126794       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
126795       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
126796     }
126797     rc = sqlite3_blob_open(
126798        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
126799     );
126800   }
126801
126802   if( rc==SQLITE_OK ){
126803     int nByte = sqlite3_blob_bytes(p->pSegments);
126804     *pnBlob = nByte;
126805     if( paBlob ){
126806       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
126807       if( !aByte ){
126808         rc = SQLITE_NOMEM;
126809       }else{
126810         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
126811           nByte = FTS3_NODE_CHUNKSIZE;
126812           *pnLoad = nByte;
126813         }
126814         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
126815         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
126816         if( rc!=SQLITE_OK ){
126817           sqlite3_free(aByte);
126818           aByte = 0;
126819         }
126820       }
126821       *paBlob = aByte;
126822     }
126823   }
126824
126825   return rc;
126826 }
126827
126828 /*
126829 ** Close the blob handle at p->pSegments, if it is open. See comments above
126830 ** the sqlite3Fts3ReadBlock() function for details.
126831 */
126832 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
126833   sqlite3_blob_close(p->pSegments);
126834   p->pSegments = 0;
126835 }
126836     
126837 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
126838   int nRead;                      /* Number of bytes to read */
126839   int rc;                         /* Return code */
126840
126841   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
126842   rc = sqlite3_blob_read(
126843       pReader->pBlob, 
126844       &pReader->aNode[pReader->nPopulate],
126845       nRead,
126846       pReader->nPopulate
126847   );
126848
126849   if( rc==SQLITE_OK ){
126850     pReader->nPopulate += nRead;
126851     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
126852     if( pReader->nPopulate==pReader->nNode ){
126853       sqlite3_blob_close(pReader->pBlob);
126854       pReader->pBlob = 0;
126855       pReader->nPopulate = 0;
126856     }
126857   }
126858   return rc;
126859 }
126860
126861 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
126862   int rc = SQLITE_OK;
126863   assert( !pReader->pBlob 
126864        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
126865   );
126866   while( pReader->pBlob && rc==SQLITE_OK 
126867      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
126868   ){
126869     rc = fts3SegReaderIncrRead(pReader);
126870   }
126871   return rc;
126872 }
126873
126874 /*
126875 ** Set an Fts3SegReader cursor to point at EOF.
126876 */
126877 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
126878   if( !fts3SegReaderIsRootOnly(pSeg) ){
126879     sqlite3_free(pSeg->aNode);
126880     sqlite3_blob_close(pSeg->pBlob);
126881     pSeg->pBlob = 0;
126882   }
126883   pSeg->aNode = 0;
126884 }
126885
126886 /*
126887 ** Move the iterator passed as the first argument to the next term in the
126888 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
126889 ** SQLITE_DONE. Otherwise, an SQLite error code.
126890 */
126891 static int fts3SegReaderNext(
126892   Fts3Table *p, 
126893   Fts3SegReader *pReader,
126894   int bIncr
126895 ){
126896   int rc;                         /* Return code of various sub-routines */
126897   char *pNext;                    /* Cursor variable */
126898   int nPrefix;                    /* Number of bytes in term prefix */
126899   int nSuffix;                    /* Number of bytes in term suffix */
126900
126901   if( !pReader->aDoclist ){
126902     pNext = pReader->aNode;
126903   }else{
126904     pNext = &pReader->aDoclist[pReader->nDoclist];
126905   }
126906
126907   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
126908
126909     if( fts3SegReaderIsPending(pReader) ){
126910       Fts3HashElem *pElem = *(pReader->ppNextElem);
126911       if( pElem==0 ){
126912         pReader->aNode = 0;
126913       }else{
126914         PendingList *pList = (PendingList *)fts3HashData(pElem);
126915         pReader->zTerm = (char *)fts3HashKey(pElem);
126916         pReader->nTerm = fts3HashKeysize(pElem);
126917         pReader->nNode = pReader->nDoclist = pList->nData + 1;
126918         pReader->aNode = pReader->aDoclist = pList->aData;
126919         pReader->ppNextElem++;
126920         assert( pReader->aNode );
126921       }
126922       return SQLITE_OK;
126923     }
126924
126925     fts3SegReaderSetEof(pReader);
126926
126927     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
126928     ** blocks have already been traversed.  */
126929     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
126930     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
126931       return SQLITE_OK;
126932     }
126933
126934     rc = sqlite3Fts3ReadBlock(
126935         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
126936         (bIncr ? &pReader->nPopulate : 0)
126937     );
126938     if( rc!=SQLITE_OK ) return rc;
126939     assert( pReader->pBlob==0 );
126940     if( bIncr && pReader->nPopulate<pReader->nNode ){
126941       pReader->pBlob = p->pSegments;
126942       p->pSegments = 0;
126943     }
126944     pNext = pReader->aNode;
126945   }
126946
126947   assert( !fts3SegReaderIsPending(pReader) );
126948
126949   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
126950   if( rc!=SQLITE_OK ) return rc;
126951   
126952   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
126953   ** safe (no risk of overread) even if the node data is corrupted. */
126954   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
126955   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
126956   if( nPrefix<0 || nSuffix<=0 
126957    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
126958   ){
126959     return FTS_CORRUPT_VTAB;
126960   }
126961
126962   if( nPrefix+nSuffix>pReader->nTermAlloc ){
126963     int nNew = (nPrefix+nSuffix)*2;
126964     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
126965     if( !zNew ){
126966       return SQLITE_NOMEM;
126967     }
126968     pReader->zTerm = zNew;
126969     pReader->nTermAlloc = nNew;
126970   }
126971
126972   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
126973   if( rc!=SQLITE_OK ) return rc;
126974
126975   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
126976   pReader->nTerm = nPrefix+nSuffix;
126977   pNext += nSuffix;
126978   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
126979   pReader->aDoclist = pNext;
126980   pReader->pOffsetList = 0;
126981
126982   /* Check that the doclist does not appear to extend past the end of the
126983   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
126984   ** of these statements is untrue, then the data structure is corrupt.
126985   */
126986   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
126987    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
126988   ){
126989     return FTS_CORRUPT_VTAB;
126990   }
126991   return SQLITE_OK;
126992 }
126993
126994 /*
126995 ** Set the SegReader to point to the first docid in the doclist associated
126996 ** with the current term.
126997 */
126998 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
126999   int rc = SQLITE_OK;
127000   assert( pReader->aDoclist );
127001   assert( !pReader->pOffsetList );
127002   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127003     u8 bEof = 0;
127004     pReader->iDocid = 0;
127005     pReader->nOffsetList = 0;
127006     sqlite3Fts3DoclistPrev(0,
127007         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
127008         &pReader->iDocid, &pReader->nOffsetList, &bEof
127009     );
127010   }else{
127011     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
127012     if( rc==SQLITE_OK ){
127013       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
127014       pReader->pOffsetList = &pReader->aDoclist[n];
127015     }
127016   }
127017   return rc;
127018 }
127019
127020 /*
127021 ** Advance the SegReader to point to the next docid in the doclist
127022 ** associated with the current term.
127023 ** 
127024 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
127025 ** *ppOffsetList is set to point to the first column-offset list
127026 ** in the doclist entry (i.e. immediately past the docid varint).
127027 ** *pnOffsetList is set to the length of the set of column-offset
127028 ** lists, not including the nul-terminator byte. For example:
127029 */
127030 static int fts3SegReaderNextDocid(
127031   Fts3Table *pTab,
127032   Fts3SegReader *pReader,         /* Reader to advance to next docid */
127033   char **ppOffsetList,            /* OUT: Pointer to current position-list */
127034   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
127035 ){
127036   int rc = SQLITE_OK;
127037   char *p = pReader->pOffsetList;
127038   char c = 0;
127039
127040   assert( p );
127041
127042   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127043     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
127044     ** Pending-terms doclists are always built up in ascending order, so
127045     ** we have to iterate through them backwards here. */
127046     u8 bEof = 0;
127047     if( ppOffsetList ){
127048       *ppOffsetList = pReader->pOffsetList;
127049       *pnOffsetList = pReader->nOffsetList - 1;
127050     }
127051     sqlite3Fts3DoclistPrev(0,
127052         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
127053         &pReader->nOffsetList, &bEof
127054     );
127055     if( bEof ){
127056       pReader->pOffsetList = 0;
127057     }else{
127058       pReader->pOffsetList = p;
127059     }
127060   }else{
127061     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
127062
127063     /* Pointer p currently points at the first byte of an offset list. The
127064     ** following block advances it to point one byte past the end of
127065     ** the same offset list. */
127066     while( 1 ){
127067   
127068       /* The following line of code (and the "p++" below the while() loop) is
127069       ** normally all that is required to move pointer p to the desired 
127070       ** position. The exception is if this node is being loaded from disk
127071       ** incrementally and pointer "p" now points to the first byte passed
127072       ** the populated part of pReader->aNode[].
127073       */
127074       while( *p | c ) c = *p++ & 0x80;
127075       assert( *p==0 );
127076   
127077       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
127078       rc = fts3SegReaderIncrRead(pReader);
127079       if( rc!=SQLITE_OK ) return rc;
127080     }
127081     p++;
127082   
127083     /* If required, populate the output variables with a pointer to and the
127084     ** size of the previous offset-list.
127085     */
127086     if( ppOffsetList ){
127087       *ppOffsetList = pReader->pOffsetList;
127088       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
127089     }
127090
127091     while( p<pEnd && *p==0 ) p++;
127092   
127093     /* If there are no more entries in the doclist, set pOffsetList to
127094     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
127095     ** Fts3SegReader.pOffsetList to point to the next offset list before
127096     ** returning.
127097     */
127098     if( p>=pEnd ){
127099       pReader->pOffsetList = 0;
127100     }else{
127101       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
127102       if( rc==SQLITE_OK ){
127103         sqlite3_int64 iDelta;
127104         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
127105         if( pTab->bDescIdx ){
127106           pReader->iDocid -= iDelta;
127107         }else{
127108           pReader->iDocid += iDelta;
127109         }
127110       }
127111     }
127112   }
127113
127114   return SQLITE_OK;
127115 }
127116
127117
127118 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
127119   Fts3Cursor *pCsr, 
127120   Fts3MultiSegReader *pMsr,
127121   int *pnOvfl
127122 ){
127123   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
127124   int nOvfl = 0;
127125   int ii;
127126   int rc = SQLITE_OK;
127127   int pgsz = p->nPgsz;
127128
127129   assert( p->bFts4 );
127130   assert( pgsz>0 );
127131
127132   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
127133     Fts3SegReader *pReader = pMsr->apSegment[ii];
127134     if( !fts3SegReaderIsPending(pReader) 
127135      && !fts3SegReaderIsRootOnly(pReader) 
127136     ){
127137       sqlite3_int64 jj;
127138       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
127139         int nBlob;
127140         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
127141         if( rc!=SQLITE_OK ) break;
127142         if( (nBlob+35)>pgsz ){
127143           nOvfl += (nBlob + 34)/pgsz;
127144         }
127145       }
127146     }
127147   }
127148   *pnOvfl = nOvfl;
127149   return rc;
127150 }
127151
127152 /*
127153 ** Free all allocations associated with the iterator passed as the 
127154 ** second argument.
127155 */
127156 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
127157   if( pReader && !fts3SegReaderIsPending(pReader) ){
127158     sqlite3_free(pReader->zTerm);
127159     if( !fts3SegReaderIsRootOnly(pReader) ){
127160       sqlite3_free(pReader->aNode);
127161       sqlite3_blob_close(pReader->pBlob);
127162     }
127163   }
127164   sqlite3_free(pReader);
127165 }
127166
127167 /*
127168 ** Allocate a new SegReader object.
127169 */
127170 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
127171   int iAge,                       /* Segment "age". */
127172   int bLookup,                    /* True for a lookup only */
127173   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
127174   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
127175   sqlite3_int64 iEndBlock,        /* Final block of segment */
127176   const char *zRoot,              /* Buffer containing root node */
127177   int nRoot,                      /* Size of buffer containing root node */
127178   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
127179 ){
127180   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
127181   int nExtra = 0;                 /* Bytes to allocate segment root node */
127182
127183   assert( iStartLeaf<=iEndLeaf );
127184   if( iStartLeaf==0 ){
127185     nExtra = nRoot + FTS3_NODE_PADDING;
127186   }
127187
127188   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
127189   if( !pReader ){
127190     return SQLITE_NOMEM;
127191   }
127192   memset(pReader, 0, sizeof(Fts3SegReader));
127193   pReader->iIdx = iAge;
127194   pReader->bLookup = bLookup!=0;
127195   pReader->iStartBlock = iStartLeaf;
127196   pReader->iLeafEndBlock = iEndLeaf;
127197   pReader->iEndBlock = iEndBlock;
127198
127199   if( nExtra ){
127200     /* The entire segment is stored in the root node. */
127201     pReader->aNode = (char *)&pReader[1];
127202     pReader->rootOnly = 1;
127203     pReader->nNode = nRoot;
127204     memcpy(pReader->aNode, zRoot, nRoot);
127205     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
127206   }else{
127207     pReader->iCurrentBlock = iStartLeaf-1;
127208   }
127209   *ppReader = pReader;
127210   return SQLITE_OK;
127211 }
127212
127213 /*
127214 ** This is a comparison function used as a qsort() callback when sorting
127215 ** an array of pending terms by term. This occurs as part of flushing
127216 ** the contents of the pending-terms hash table to the database.
127217 */
127218 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
127219   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
127220   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
127221   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
127222   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
127223
127224   int n = (n1<n2 ? n1 : n2);
127225   int c = memcmp(z1, z2, n);
127226   if( c==0 ){
127227     c = n1 - n2;
127228   }
127229   return c;
127230 }
127231
127232 /*
127233 ** This function is used to allocate an Fts3SegReader that iterates through
127234 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
127235 **
127236 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
127237 ** through each term in the pending-terms table. Or, if isPrefixIter is
127238 ** non-zero, it iterates through each term and its prefixes. For example, if
127239 ** the pending terms hash table contains the terms "sqlite", "mysql" and
127240 ** "firebird", then the iterator visits the following 'terms' (in the order
127241 ** shown):
127242 **
127243 **   f fi fir fire fireb firebi firebir firebird
127244 **   m my mys mysq mysql
127245 **   s sq sql sqli sqlit sqlite
127246 **
127247 ** Whereas if isPrefixIter is zero, the terms visited are:
127248 **
127249 **   firebird mysql sqlite
127250 */
127251 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
127252   Fts3Table *p,                   /* Virtual table handle */
127253   int iIndex,                     /* Index for p->aIndex */
127254   const char *zTerm,              /* Term to search for */
127255   int nTerm,                      /* Size of buffer zTerm */
127256   int bPrefix,                    /* True for a prefix iterator */
127257   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
127258 ){
127259   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
127260   Fts3HashElem *pE;               /* Iterator variable */
127261   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
127262   int nElem = 0;                  /* Size of array at aElem */
127263   int rc = SQLITE_OK;             /* Return Code */
127264   Fts3Hash *pHash;
127265
127266   pHash = &p->aIndex[iIndex].hPending;
127267   if( bPrefix ){
127268     int nAlloc = 0;               /* Size of allocated array at aElem */
127269
127270     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
127271       char *zKey = (char *)fts3HashKey(pE);
127272       int nKey = fts3HashKeysize(pE);
127273       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
127274         if( nElem==nAlloc ){
127275           Fts3HashElem **aElem2;
127276           nAlloc += 16;
127277           aElem2 = (Fts3HashElem **)sqlite3_realloc(
127278               aElem, nAlloc*sizeof(Fts3HashElem *)
127279           );
127280           if( !aElem2 ){
127281             rc = SQLITE_NOMEM;
127282             nElem = 0;
127283             break;
127284           }
127285           aElem = aElem2;
127286         }
127287
127288         aElem[nElem++] = pE;
127289       }
127290     }
127291
127292     /* If more than one term matches the prefix, sort the Fts3HashElem
127293     ** objects in term order using qsort(). This uses the same comparison
127294     ** callback as is used when flushing terms to disk.
127295     */
127296     if( nElem>1 ){
127297       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
127298     }
127299
127300   }else{
127301     /* The query is a simple term lookup that matches at most one term in
127302     ** the index. All that is required is a straight hash-lookup. 
127303     **
127304     ** Because the stack address of pE may be accessed via the aElem pointer
127305     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
127306     ** within this entire function, not just this "else{...}" block.
127307     */
127308     pE = fts3HashFindElem(pHash, zTerm, nTerm);
127309     if( pE ){
127310       aElem = &pE;
127311       nElem = 1;
127312     }
127313   }
127314
127315   if( nElem>0 ){
127316     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
127317     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
127318     if( !pReader ){
127319       rc = SQLITE_NOMEM;
127320     }else{
127321       memset(pReader, 0, nByte);
127322       pReader->iIdx = 0x7FFFFFFF;
127323       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
127324       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
127325     }
127326   }
127327
127328   if( bPrefix ){
127329     sqlite3_free(aElem);
127330   }
127331   *ppReader = pReader;
127332   return rc;
127333 }
127334
127335 /*
127336 ** Compare the entries pointed to by two Fts3SegReader structures. 
127337 ** Comparison is as follows:
127338 **
127339 **   1) EOF is greater than not EOF.
127340 **
127341 **   2) The current terms (if any) are compared using memcmp(). If one
127342 **      term is a prefix of another, the longer term is considered the
127343 **      larger.
127344 **
127345 **   3) By segment age. An older segment is considered larger.
127346 */
127347 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
127348   int rc;
127349   if( pLhs->aNode && pRhs->aNode ){
127350     int rc2 = pLhs->nTerm - pRhs->nTerm;
127351     if( rc2<0 ){
127352       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
127353     }else{
127354       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
127355     }
127356     if( rc==0 ){
127357       rc = rc2;
127358     }
127359   }else{
127360     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
127361   }
127362   if( rc==0 ){
127363     rc = pRhs->iIdx - pLhs->iIdx;
127364   }
127365   assert( rc!=0 );
127366   return rc;
127367 }
127368
127369 /*
127370 ** A different comparison function for SegReader structures. In this
127371 ** version, it is assumed that each SegReader points to an entry in
127372 ** a doclist for identical terms. Comparison is made as follows:
127373 **
127374 **   1) EOF (end of doclist in this case) is greater than not EOF.
127375 **
127376 **   2) By current docid.
127377 **
127378 **   3) By segment age. An older segment is considered larger.
127379 */
127380 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
127381   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
127382   if( rc==0 ){
127383     if( pLhs->iDocid==pRhs->iDocid ){
127384       rc = pRhs->iIdx - pLhs->iIdx;
127385     }else{
127386       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
127387     }
127388   }
127389   assert( pLhs->aNode && pRhs->aNode );
127390   return rc;
127391 }
127392 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
127393   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
127394   if( rc==0 ){
127395     if( pLhs->iDocid==pRhs->iDocid ){
127396       rc = pRhs->iIdx - pLhs->iIdx;
127397     }else{
127398       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
127399     }
127400   }
127401   assert( pLhs->aNode && pRhs->aNode );
127402   return rc;
127403 }
127404
127405 /*
127406 ** Compare the term that the Fts3SegReader object passed as the first argument
127407 ** points to with the term specified by arguments zTerm and nTerm. 
127408 **
127409 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
127410 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
127411 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
127412 */
127413 static int fts3SegReaderTermCmp(
127414   Fts3SegReader *pSeg,            /* Segment reader object */
127415   const char *zTerm,              /* Term to compare to */
127416   int nTerm                       /* Size of term zTerm in bytes */
127417 ){
127418   int res = 0;
127419   if( pSeg->aNode ){
127420     if( pSeg->nTerm>nTerm ){
127421       res = memcmp(pSeg->zTerm, zTerm, nTerm);
127422     }else{
127423       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
127424     }
127425     if( res==0 ){
127426       res = pSeg->nTerm-nTerm;
127427     }
127428   }
127429   return res;
127430 }
127431
127432 /*
127433 ** Argument apSegment is an array of nSegment elements. It is known that
127434 ** the final (nSegment-nSuspect) members are already in sorted order
127435 ** (according to the comparison function provided). This function shuffles
127436 ** the array around until all entries are in sorted order.
127437 */
127438 static void fts3SegReaderSort(
127439   Fts3SegReader **apSegment,                     /* Array to sort entries of */
127440   int nSegment,                                  /* Size of apSegment array */
127441   int nSuspect,                                  /* Unsorted entry count */
127442   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
127443 ){
127444   int i;                          /* Iterator variable */
127445
127446   assert( nSuspect<=nSegment );
127447
127448   if( nSuspect==nSegment ) nSuspect--;
127449   for(i=nSuspect-1; i>=0; i--){
127450     int j;
127451     for(j=i; j<(nSegment-1); j++){
127452       Fts3SegReader *pTmp;
127453       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
127454       pTmp = apSegment[j+1];
127455       apSegment[j+1] = apSegment[j];
127456       apSegment[j] = pTmp;
127457     }
127458   }
127459
127460 #ifndef NDEBUG
127461   /* Check that the list really is sorted now. */
127462   for(i=0; i<(nSuspect-1); i++){
127463     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
127464   }
127465 #endif
127466 }
127467
127468 /* 
127469 ** Insert a record into the %_segments table.
127470 */
127471 static int fts3WriteSegment(
127472   Fts3Table *p,                   /* Virtual table handle */
127473   sqlite3_int64 iBlock,           /* Block id for new block */
127474   char *z,                        /* Pointer to buffer containing block data */
127475   int n                           /* Size of buffer z in bytes */
127476 ){
127477   sqlite3_stmt *pStmt;
127478   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
127479   if( rc==SQLITE_OK ){
127480     sqlite3_bind_int64(pStmt, 1, iBlock);
127481     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
127482     sqlite3_step(pStmt);
127483     rc = sqlite3_reset(pStmt);
127484   }
127485   return rc;
127486 }
127487
127488 /*
127489 ** Find the largest relative level number in the table. If successful, set
127490 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
127491 ** set *pnMax to zero and return an SQLite error code.
127492 */
127493 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
127494   int rc;
127495   int mxLevel = 0;
127496   sqlite3_stmt *pStmt = 0;
127497
127498   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
127499   if( rc==SQLITE_OK ){
127500     if( SQLITE_ROW==sqlite3_step(pStmt) ){
127501       mxLevel = sqlite3_column_int(pStmt, 0);
127502     }
127503     rc = sqlite3_reset(pStmt);
127504   }
127505   *pnMax = mxLevel;
127506   return rc;
127507 }
127508
127509 /* 
127510 ** Insert a record into the %_segdir table.
127511 */
127512 static int fts3WriteSegdir(
127513   Fts3Table *p,                   /* Virtual table handle */
127514   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
127515   int iIdx,                       /* Value for "idx" field */
127516   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
127517   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
127518   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
127519   char *zRoot,                    /* Blob value for "root" field */
127520   int nRoot                       /* Number of bytes in buffer zRoot */
127521 ){
127522   sqlite3_stmt *pStmt;
127523   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
127524   if( rc==SQLITE_OK ){
127525     sqlite3_bind_int64(pStmt, 1, iLevel);
127526     sqlite3_bind_int(pStmt, 2, iIdx);
127527     sqlite3_bind_int64(pStmt, 3, iStartBlock);
127528     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
127529     sqlite3_bind_int64(pStmt, 5, iEndBlock);
127530     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
127531     sqlite3_step(pStmt);
127532     rc = sqlite3_reset(pStmt);
127533   }
127534   return rc;
127535 }
127536
127537 /*
127538 ** Return the size of the common prefix (if any) shared by zPrev and
127539 ** zNext, in bytes. For example, 
127540 **
127541 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
127542 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
127543 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
127544 */
127545 static int fts3PrefixCompress(
127546   const char *zPrev,              /* Buffer containing previous term */
127547   int nPrev,                      /* Size of buffer zPrev in bytes */
127548   const char *zNext,              /* Buffer containing next term */
127549   int nNext                       /* Size of buffer zNext in bytes */
127550 ){
127551   int n;
127552   UNUSED_PARAMETER(nNext);
127553   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
127554   return n;
127555 }
127556
127557 /*
127558 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
127559 ** (according to memcmp) than the previous term.
127560 */
127561 static int fts3NodeAddTerm(
127562   Fts3Table *p,                   /* Virtual table handle */
127563   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
127564   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
127565   const char *zTerm,              /* Pointer to buffer containing term */
127566   int nTerm                       /* Size of term in bytes */
127567 ){
127568   SegmentNode *pTree = *ppTree;
127569   int rc;
127570   SegmentNode *pNew;
127571
127572   /* First try to append the term to the current node. Return early if 
127573   ** this is possible.
127574   */
127575   if( pTree ){
127576     int nData = pTree->nData;     /* Current size of node in bytes */
127577     int nReq = nData;             /* Required space after adding zTerm */
127578     int nPrefix;                  /* Number of bytes of prefix compression */
127579     int nSuffix;                  /* Suffix length */
127580
127581     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
127582     nSuffix = nTerm-nPrefix;
127583
127584     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
127585     if( nReq<=p->nNodeSize || !pTree->zTerm ){
127586
127587       if( nReq>p->nNodeSize ){
127588         /* An unusual case: this is the first term to be added to the node
127589         ** and the static node buffer (p->nNodeSize bytes) is not large
127590         ** enough. Use a separately malloced buffer instead This wastes
127591         ** p->nNodeSize bytes, but since this scenario only comes about when
127592         ** the database contain two terms that share a prefix of almost 2KB, 
127593         ** this is not expected to be a serious problem. 
127594         */
127595         assert( pTree->aData==(char *)&pTree[1] );
127596         pTree->aData = (char *)sqlite3_malloc(nReq);
127597         if( !pTree->aData ){
127598           return SQLITE_NOMEM;
127599         }
127600       }
127601
127602       if( pTree->zTerm ){
127603         /* There is no prefix-length field for first term in a node */
127604         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
127605       }
127606
127607       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
127608       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
127609       pTree->nData = nData + nSuffix;
127610       pTree->nEntry++;
127611
127612       if( isCopyTerm ){
127613         if( pTree->nMalloc<nTerm ){
127614           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
127615           if( !zNew ){
127616             return SQLITE_NOMEM;
127617           }
127618           pTree->nMalloc = nTerm*2;
127619           pTree->zMalloc = zNew;
127620         }
127621         pTree->zTerm = pTree->zMalloc;
127622         memcpy(pTree->zTerm, zTerm, nTerm);
127623         pTree->nTerm = nTerm;
127624       }else{
127625         pTree->zTerm = (char *)zTerm;
127626         pTree->nTerm = nTerm;
127627       }
127628       return SQLITE_OK;
127629     }
127630   }
127631
127632   /* If control flows to here, it was not possible to append zTerm to the
127633   ** current node. Create a new node (a right-sibling of the current node).
127634   ** If this is the first node in the tree, the term is added to it.
127635   **
127636   ** Otherwise, the term is not added to the new node, it is left empty for
127637   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
127638   ** has no parent, one is created here.
127639   */
127640   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
127641   if( !pNew ){
127642     return SQLITE_NOMEM;
127643   }
127644   memset(pNew, 0, sizeof(SegmentNode));
127645   pNew->nData = 1 + FTS3_VARINT_MAX;
127646   pNew->aData = (char *)&pNew[1];
127647
127648   if( pTree ){
127649     SegmentNode *pParent = pTree->pParent;
127650     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
127651     if( pTree->pParent==0 ){
127652       pTree->pParent = pParent;
127653     }
127654     pTree->pRight = pNew;
127655     pNew->pLeftmost = pTree->pLeftmost;
127656     pNew->pParent = pParent;
127657     pNew->zMalloc = pTree->zMalloc;
127658     pNew->nMalloc = pTree->nMalloc;
127659     pTree->zMalloc = 0;
127660   }else{
127661     pNew->pLeftmost = pNew;
127662     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
127663   }
127664
127665   *ppTree = pNew;
127666   return rc;
127667 }
127668
127669 /*
127670 ** Helper function for fts3NodeWrite().
127671 */
127672 static int fts3TreeFinishNode(
127673   SegmentNode *pTree, 
127674   int iHeight, 
127675   sqlite3_int64 iLeftChild
127676 ){
127677   int nStart;
127678   assert( iHeight>=1 && iHeight<128 );
127679   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
127680   pTree->aData[nStart] = (char)iHeight;
127681   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
127682   return nStart;
127683 }
127684
127685 /*
127686 ** Write the buffer for the segment node pTree and all of its peers to the
127687 ** database. Then call this function recursively to write the parent of 
127688 ** pTree and its peers to the database. 
127689 **
127690 ** Except, if pTree is a root node, do not write it to the database. Instead,
127691 ** set output variables *paRoot and *pnRoot to contain the root node.
127692 **
127693 ** If successful, SQLITE_OK is returned and output variable *piLast is
127694 ** set to the largest blockid written to the database (or zero if no
127695 ** blocks were written to the db). Otherwise, an SQLite error code is 
127696 ** returned.
127697 */
127698 static int fts3NodeWrite(
127699   Fts3Table *p,                   /* Virtual table handle */
127700   SegmentNode *pTree,             /* SegmentNode handle */
127701   int iHeight,                    /* Height of this node in tree */
127702   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
127703   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
127704   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
127705   char **paRoot,                  /* OUT: Data for root node */
127706   int *pnRoot                     /* OUT: Size of root node in bytes */
127707 ){
127708   int rc = SQLITE_OK;
127709
127710   if( !pTree->pParent ){
127711     /* Root node of the tree. */
127712     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
127713     *piLast = iFree-1;
127714     *pnRoot = pTree->nData - nStart;
127715     *paRoot = &pTree->aData[nStart];
127716   }else{
127717     SegmentNode *pIter;
127718     sqlite3_int64 iNextFree = iFree;
127719     sqlite3_int64 iNextLeaf = iLeaf;
127720     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
127721       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
127722       int nWrite = pIter->nData - nStart;
127723   
127724       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
127725       iNextFree++;
127726       iNextLeaf += (pIter->nEntry+1);
127727     }
127728     if( rc==SQLITE_OK ){
127729       assert( iNextLeaf==iFree );
127730       rc = fts3NodeWrite(
127731           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
127732       );
127733     }
127734   }
127735
127736   return rc;
127737 }
127738
127739 /*
127740 ** Free all memory allocations associated with the tree pTree.
127741 */
127742 static void fts3NodeFree(SegmentNode *pTree){
127743   if( pTree ){
127744     SegmentNode *p = pTree->pLeftmost;
127745     fts3NodeFree(p->pParent);
127746     while( p ){
127747       SegmentNode *pRight = p->pRight;
127748       if( p->aData!=(char *)&p[1] ){
127749         sqlite3_free(p->aData);
127750       }
127751       assert( pRight==0 || p->zMalloc==0 );
127752       sqlite3_free(p->zMalloc);
127753       sqlite3_free(p);
127754       p = pRight;
127755     }
127756   }
127757 }
127758
127759 /*
127760 ** Add a term to the segment being constructed by the SegmentWriter object
127761 ** *ppWriter. When adding the first term to a segment, *ppWriter should
127762 ** be passed NULL. This function will allocate a new SegmentWriter object
127763 ** and return it via the input/output variable *ppWriter in this case.
127764 **
127765 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127766 */
127767 static int fts3SegWriterAdd(
127768   Fts3Table *p,                   /* Virtual table handle */
127769   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
127770   int isCopyTerm,                 /* True if buffer zTerm must be copied */
127771   const char *zTerm,              /* Pointer to buffer containing term */
127772   int nTerm,                      /* Size of term in bytes */
127773   const char *aDoclist,           /* Pointer to buffer containing doclist */
127774   int nDoclist                    /* Size of doclist in bytes */
127775 ){
127776   int nPrefix;                    /* Size of term prefix in bytes */
127777   int nSuffix;                    /* Size of term suffix in bytes */
127778   int nReq;                       /* Number of bytes required on leaf page */
127779   int nData;
127780   SegmentWriter *pWriter = *ppWriter;
127781
127782   if( !pWriter ){
127783     int rc;
127784     sqlite3_stmt *pStmt;
127785
127786     /* Allocate the SegmentWriter structure */
127787     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
127788     if( !pWriter ) return SQLITE_NOMEM;
127789     memset(pWriter, 0, sizeof(SegmentWriter));
127790     *ppWriter = pWriter;
127791
127792     /* Allocate a buffer in which to accumulate data */
127793     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
127794     if( !pWriter->aData ) return SQLITE_NOMEM;
127795     pWriter->nSize = p->nNodeSize;
127796
127797     /* Find the next free blockid in the %_segments table */
127798     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
127799     if( rc!=SQLITE_OK ) return rc;
127800     if( SQLITE_ROW==sqlite3_step(pStmt) ){
127801       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
127802       pWriter->iFirst = pWriter->iFree;
127803     }
127804     rc = sqlite3_reset(pStmt);
127805     if( rc!=SQLITE_OK ) return rc;
127806   }
127807   nData = pWriter->nData;
127808
127809   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
127810   nSuffix = nTerm-nPrefix;
127811
127812   /* Figure out how many bytes are required by this new entry */
127813   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
127814     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
127815     nSuffix +                               /* Term suffix */
127816     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
127817     nDoclist;                               /* Doclist data */
127818
127819   if( nData>0 && nData+nReq>p->nNodeSize ){
127820     int rc;
127821
127822     /* The current leaf node is full. Write it out to the database. */
127823     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
127824     if( rc!=SQLITE_OK ) return rc;
127825     p->nLeafAdd++;
127826
127827     /* Add the current term to the interior node tree. The term added to
127828     ** the interior tree must:
127829     **
127830     **   a) be greater than the largest term on the leaf node just written
127831     **      to the database (still available in pWriter->zTerm), and
127832     **
127833     **   b) be less than or equal to the term about to be added to the new
127834     **      leaf node (zTerm/nTerm).
127835     **
127836     ** In other words, it must be the prefix of zTerm 1 byte longer than
127837     ** the common prefix (if any) of zTerm and pWriter->zTerm.
127838     */
127839     assert( nPrefix<nTerm );
127840     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
127841     if( rc!=SQLITE_OK ) return rc;
127842
127843     nData = 0;
127844     pWriter->nTerm = 0;
127845
127846     nPrefix = 0;
127847     nSuffix = nTerm;
127848     nReq = 1 +                              /* varint containing prefix size */
127849       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
127850       nTerm +                               /* Term suffix */
127851       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
127852       nDoclist;                             /* Doclist data */
127853   }
127854
127855   /* If the buffer currently allocated is too small for this entry, realloc
127856   ** the buffer to make it large enough.
127857   */
127858   if( nReq>pWriter->nSize ){
127859     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
127860     if( !aNew ) return SQLITE_NOMEM;
127861     pWriter->aData = aNew;
127862     pWriter->nSize = nReq;
127863   }
127864   assert( nData+nReq<=pWriter->nSize );
127865
127866   /* Append the prefix-compressed term and doclist to the buffer. */
127867   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
127868   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
127869   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
127870   nData += nSuffix;
127871   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
127872   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
127873   pWriter->nData = nData + nDoclist;
127874
127875   /* Save the current term so that it can be used to prefix-compress the next.
127876   ** If the isCopyTerm parameter is true, then the buffer pointed to by
127877   ** zTerm is transient, so take a copy of the term data. Otherwise, just
127878   ** store a copy of the pointer.
127879   */
127880   if( isCopyTerm ){
127881     if( nTerm>pWriter->nMalloc ){
127882       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
127883       if( !zNew ){
127884         return SQLITE_NOMEM;
127885       }
127886       pWriter->nMalloc = nTerm*2;
127887       pWriter->zMalloc = zNew;
127888       pWriter->zTerm = zNew;
127889     }
127890     assert( pWriter->zTerm==pWriter->zMalloc );
127891     memcpy(pWriter->zTerm, zTerm, nTerm);
127892   }else{
127893     pWriter->zTerm = (char *)zTerm;
127894   }
127895   pWriter->nTerm = nTerm;
127896
127897   return SQLITE_OK;
127898 }
127899
127900 /*
127901 ** Flush all data associated with the SegmentWriter object pWriter to the
127902 ** database. This function must be called after all terms have been added
127903 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
127904 ** returned. Otherwise, an SQLite error code.
127905 */
127906 static int fts3SegWriterFlush(
127907   Fts3Table *p,                   /* Virtual table handle */
127908   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
127909   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
127910   int iIdx                        /* Value for 'idx' column of %_segdir */
127911 ){
127912   int rc;                         /* Return code */
127913   if( pWriter->pTree ){
127914     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
127915     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
127916     char *zRoot = NULL;           /* Pointer to buffer containing root node */
127917     int nRoot = 0;                /* Size of buffer zRoot */
127918
127919     iLastLeaf = pWriter->iFree;
127920     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
127921     if( rc==SQLITE_OK ){
127922       rc = fts3NodeWrite(p, pWriter->pTree, 1,
127923           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
127924     }
127925     if( rc==SQLITE_OK ){
127926       rc = fts3WriteSegdir(
127927           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
127928     }
127929   }else{
127930     /* The entire tree fits on the root node. Write it to the segdir table. */
127931     rc = fts3WriteSegdir(
127932         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
127933   }
127934   p->nLeafAdd++;
127935   return rc;
127936 }
127937
127938 /*
127939 ** Release all memory held by the SegmentWriter object passed as the 
127940 ** first argument.
127941 */
127942 static void fts3SegWriterFree(SegmentWriter *pWriter){
127943   if( pWriter ){
127944     sqlite3_free(pWriter->aData);
127945     sqlite3_free(pWriter->zMalloc);
127946     fts3NodeFree(pWriter->pTree);
127947     sqlite3_free(pWriter);
127948   }
127949 }
127950
127951 /*
127952 ** The first value in the apVal[] array is assumed to contain an integer.
127953 ** This function tests if there exist any documents with docid values that
127954 ** are different from that integer. i.e. if deleting the document with docid
127955 ** pRowid would mean the FTS3 table were empty.
127956 **
127957 ** If successful, *pisEmpty is set to true if the table is empty except for
127958 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
127959 ** error occurs, an SQLite error code is returned.
127960 */
127961 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
127962   sqlite3_stmt *pStmt;
127963   int rc;
127964   if( p->zContentTbl ){
127965     /* If using the content=xxx option, assume the table is never empty */
127966     *pisEmpty = 0;
127967     rc = SQLITE_OK;
127968   }else{
127969     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
127970     if( rc==SQLITE_OK ){
127971       if( SQLITE_ROW==sqlite3_step(pStmt) ){
127972         *pisEmpty = sqlite3_column_int(pStmt, 0);
127973       }
127974       rc = sqlite3_reset(pStmt);
127975     }
127976   }
127977   return rc;
127978 }
127979
127980 /*
127981 ** Set *pnMax to the largest segment level in the database for the index
127982 ** iIndex.
127983 **
127984 ** Segment levels are stored in the 'level' column of the %_segdir table.
127985 **
127986 ** Return SQLITE_OK if successful, or an SQLite error code if not.
127987 */
127988 static int fts3SegmentMaxLevel(
127989   Fts3Table *p, 
127990   int iLangid,
127991   int iIndex, 
127992   sqlite3_int64 *pnMax
127993 ){
127994   sqlite3_stmt *pStmt;
127995   int rc;
127996   assert( iIndex>=0 && iIndex<p->nIndex );
127997
127998   /* Set pStmt to the compiled version of:
127999   **
128000   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
128001   **
128002   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
128003   */
128004   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
128005   if( rc!=SQLITE_OK ) return rc;
128006   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128007   sqlite3_bind_int64(pStmt, 2, 
128008       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128009   );
128010   if( SQLITE_ROW==sqlite3_step(pStmt) ){
128011     *pnMax = sqlite3_column_int64(pStmt, 0);
128012   }
128013   return sqlite3_reset(pStmt);
128014 }
128015
128016 /*
128017 ** Delete all entries in the %_segments table associated with the segment
128018 ** opened with seg-reader pSeg. This function does not affect the contents
128019 ** of the %_segdir table.
128020 */
128021 static int fts3DeleteSegment(
128022   Fts3Table *p,                   /* FTS table handle */
128023   Fts3SegReader *pSeg             /* Segment to delete */
128024 ){
128025   int rc = SQLITE_OK;             /* Return code */
128026   if( pSeg->iStartBlock ){
128027     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
128028     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
128029     if( rc==SQLITE_OK ){
128030       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
128031       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
128032       sqlite3_step(pDelete);
128033       rc = sqlite3_reset(pDelete);
128034     }
128035   }
128036   return rc;
128037 }
128038
128039 /*
128040 ** This function is used after merging multiple segments into a single large
128041 ** segment to delete the old, now redundant, segment b-trees. Specifically,
128042 ** it:
128043 ** 
128044 **   1) Deletes all %_segments entries for the segments associated with 
128045 **      each of the SegReader objects in the array passed as the third 
128046 **      argument, and
128047 **
128048 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
128049 **      entries regardless of level if (iLevel<0).
128050 **
128051 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
128052 */
128053 static int fts3DeleteSegdir(
128054   Fts3Table *p,                   /* Virtual table handle */
128055   int iLangid,                    /* Language id */
128056   int iIndex,                     /* Index for p->aIndex */
128057   int iLevel,                     /* Level of %_segdir entries to delete */
128058   Fts3SegReader **apSegment,      /* Array of SegReader objects */
128059   int nReader                     /* Size of array apSegment */
128060 ){
128061   int rc = SQLITE_OK;             /* Return Code */
128062   int i;                          /* Iterator variable */
128063   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
128064
128065   for(i=0; rc==SQLITE_OK && i<nReader; i++){
128066     rc = fts3DeleteSegment(p, apSegment[i]);
128067   }
128068   if( rc!=SQLITE_OK ){
128069     return rc;
128070   }
128071
128072   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
128073   if( iLevel==FTS3_SEGCURSOR_ALL ){
128074     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
128075     if( rc==SQLITE_OK ){
128076       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128077       sqlite3_bind_int64(pDelete, 2, 
128078           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128079       );
128080     }
128081   }else{
128082     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
128083     if( rc==SQLITE_OK ){
128084       sqlite3_bind_int64(
128085           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
128086       );
128087     }
128088   }
128089
128090   if( rc==SQLITE_OK ){
128091     sqlite3_step(pDelete);
128092     rc = sqlite3_reset(pDelete);
128093   }
128094
128095   return rc;
128096 }
128097
128098 /*
128099 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
128100 ** a position list that may (or may not) feature multiple columns. This
128101 ** function adjusts the pointer *ppList and the length *pnList so that they
128102 ** identify the subset of the position list that corresponds to column iCol.
128103 **
128104 ** If there are no entries in the input position list for column iCol, then
128105 ** *pnList is set to zero before returning.
128106 */
128107 static void fts3ColumnFilter(
128108   int iCol,                       /* Column to filter on */
128109   char **ppList,                  /* IN/OUT: Pointer to position list */
128110   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
128111 ){
128112   char *pList = *ppList;
128113   int nList = *pnList;
128114   char *pEnd = &pList[nList];
128115   int iCurrent = 0;
128116   char *p = pList;
128117
128118   assert( iCol>=0 );
128119   while( 1 ){
128120     char c = 0;
128121     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
128122   
128123     if( iCol==iCurrent ){
128124       nList = (int)(p - pList);
128125       break;
128126     }
128127
128128     nList -= (int)(p - pList);
128129     pList = p;
128130     if( nList==0 ){
128131       break;
128132     }
128133     p = &pList[1];
128134     p += sqlite3Fts3GetVarint32(p, &iCurrent);
128135   }
128136
128137   *ppList = pList;
128138   *pnList = nList;
128139 }
128140
128141 /*
128142 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
128143 ** existing data). Grow the buffer if required.
128144 **
128145 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
128146 ** trying to resize the buffer, return SQLITE_NOMEM.
128147 */
128148 static int fts3MsrBufferData(
128149   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128150   char *pList,
128151   int nList
128152 ){
128153   if( nList>pMsr->nBuffer ){
128154     char *pNew;
128155     pMsr->nBuffer = nList*2;
128156     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
128157     if( !pNew ) return SQLITE_NOMEM;
128158     pMsr->aBuffer = pNew;
128159   }
128160
128161   memcpy(pMsr->aBuffer, pList, nList);
128162   return SQLITE_OK;
128163 }
128164
128165 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
128166   Fts3Table *p,                   /* Virtual table handle */
128167   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128168   sqlite3_int64 *piDocid,         /* OUT: Docid value */
128169   char **paPoslist,               /* OUT: Pointer to position list */
128170   int *pnPoslist                  /* OUT: Size of position list in bytes */
128171 ){
128172   int nMerge = pMsr->nAdvance;
128173   Fts3SegReader **apSegment = pMsr->apSegment;
128174   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128175     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128176   );
128177
128178   if( nMerge==0 ){
128179     *paPoslist = 0;
128180     return SQLITE_OK;
128181   }
128182
128183   while( 1 ){
128184     Fts3SegReader *pSeg;
128185     pSeg = pMsr->apSegment[0];
128186
128187     if( pSeg->pOffsetList==0 ){
128188       *paPoslist = 0;
128189       break;
128190     }else{
128191       int rc;
128192       char *pList;
128193       int nList;
128194       int j;
128195       sqlite3_int64 iDocid = apSegment[0]->iDocid;
128196
128197       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
128198       j = 1;
128199       while( rc==SQLITE_OK 
128200         && j<nMerge
128201         && apSegment[j]->pOffsetList
128202         && apSegment[j]->iDocid==iDocid
128203       ){
128204         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
128205         j++;
128206       }
128207       if( rc!=SQLITE_OK ) return rc;
128208       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
128209
128210       if( pMsr->iColFilter>=0 ){
128211         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
128212       }
128213
128214       if( nList>0 ){
128215         if( fts3SegReaderIsPending(apSegment[0]) ){
128216           rc = fts3MsrBufferData(pMsr, pList, nList+1);
128217           if( rc!=SQLITE_OK ) return rc;
128218           *paPoslist = pMsr->aBuffer;
128219           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
128220         }else{
128221           *paPoslist = pList;
128222         }
128223         *piDocid = iDocid;
128224         *pnPoslist = nList;
128225         break;
128226       }
128227     }
128228   }
128229
128230   return SQLITE_OK;
128231 }
128232
128233 static int fts3SegReaderStart(
128234   Fts3Table *p,                   /* Virtual table handle */
128235   Fts3MultiSegReader *pCsr,       /* Cursor object */
128236   const char *zTerm,              /* Term searched for (or NULL) */
128237   int nTerm                       /* Length of zTerm in bytes */
128238 ){
128239   int i;
128240   int nSeg = pCsr->nSegment;
128241
128242   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
128243   ** for, then advance each segment iterator until it points to a term of
128244   ** equal or greater value than the specified term. This prevents many
128245   ** unnecessary merge/sort operations for the case where single segment
128246   ** b-tree leaf nodes contain more than one term.
128247   */
128248   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
128249     int res = 0;
128250     Fts3SegReader *pSeg = pCsr->apSegment[i];
128251     do {
128252       int rc = fts3SegReaderNext(p, pSeg, 0);
128253       if( rc!=SQLITE_OK ) return rc;
128254     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
128255
128256     if( pSeg->bLookup && res!=0 ){
128257       fts3SegReaderSetEof(pSeg);
128258     }
128259   }
128260   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
128261
128262   return SQLITE_OK;
128263 }
128264
128265 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
128266   Fts3Table *p,                   /* Virtual table handle */
128267   Fts3MultiSegReader *pCsr,       /* Cursor object */
128268   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
128269 ){
128270   pCsr->pFilter = pFilter;
128271   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
128272 }
128273
128274 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
128275   Fts3Table *p,                   /* Virtual table handle */
128276   Fts3MultiSegReader *pCsr,       /* Cursor object */
128277   int iCol,                       /* Column to match on. */
128278   const char *zTerm,              /* Term to iterate through a doclist for */
128279   int nTerm                       /* Number of bytes in zTerm */
128280 ){
128281   int i;
128282   int rc;
128283   int nSegment = pCsr->nSegment;
128284   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128285     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128286   );
128287
128288   assert( pCsr->pFilter==0 );
128289   assert( zTerm && nTerm>0 );
128290
128291   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
128292   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
128293   if( rc!=SQLITE_OK ) return rc;
128294
128295   /* Determine how many of the segments actually point to zTerm/nTerm. */
128296   for(i=0; i<nSegment; i++){
128297     Fts3SegReader *pSeg = pCsr->apSegment[i];
128298     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
128299       break;
128300     }
128301   }
128302   pCsr->nAdvance = i;
128303
128304   /* Advance each of the segments to point to the first docid. */
128305   for(i=0; i<pCsr->nAdvance; i++){
128306     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
128307     if( rc!=SQLITE_OK ) return rc;
128308   }
128309   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
128310
128311   assert( iCol<0 || iCol<p->nColumn );
128312   pCsr->iColFilter = iCol;
128313
128314   return SQLITE_OK;
128315 }
128316
128317 /*
128318 ** This function is called on a MultiSegReader that has been started using
128319 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
128320 ** have been made. Calling this function puts the MultiSegReader in such
128321 ** a state that if the next two calls are:
128322 **
128323 **   sqlite3Fts3SegReaderStart()
128324 **   sqlite3Fts3SegReaderStep()
128325 **
128326 ** then the entire doclist for the term is available in 
128327 ** MultiSegReader.aDoclist/nDoclist.
128328 */
128329 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
128330   int i;                          /* Used to iterate through segment-readers */
128331
128332   assert( pCsr->zTerm==0 );
128333   assert( pCsr->nTerm==0 );
128334   assert( pCsr->aDoclist==0 );
128335   assert( pCsr->nDoclist==0 );
128336
128337   pCsr->nAdvance = 0;
128338   pCsr->bRestart = 1;
128339   for(i=0; i<pCsr->nSegment; i++){
128340     pCsr->apSegment[i]->pOffsetList = 0;
128341     pCsr->apSegment[i]->nOffsetList = 0;
128342     pCsr->apSegment[i]->iDocid = 0;
128343   }
128344
128345   return SQLITE_OK;
128346 }
128347
128348
128349 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
128350   Fts3Table *p,                   /* Virtual table handle */
128351   Fts3MultiSegReader *pCsr        /* Cursor object */
128352 ){
128353   int rc = SQLITE_OK;
128354
128355   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
128356   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
128357   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
128358   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
128359   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
128360   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
128361
128362   Fts3SegReader **apSegment = pCsr->apSegment;
128363   int nSegment = pCsr->nSegment;
128364   Fts3SegFilter *pFilter = pCsr->pFilter;
128365   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128366     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128367   );
128368
128369   if( pCsr->nSegment==0 ) return SQLITE_OK;
128370
128371   do {
128372     int nMerge;
128373     int i;
128374   
128375     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
128376     ** forward. Then sort the list in order of current term again.  
128377     */
128378     for(i=0; i<pCsr->nAdvance; i++){
128379       Fts3SegReader *pSeg = apSegment[i];
128380       if( pSeg->bLookup ){
128381         fts3SegReaderSetEof(pSeg);
128382       }else{
128383         rc = fts3SegReaderNext(p, pSeg, 0);
128384       }
128385       if( rc!=SQLITE_OK ) return rc;
128386     }
128387     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
128388     pCsr->nAdvance = 0;
128389
128390     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
128391     assert( rc==SQLITE_OK );
128392     if( apSegment[0]->aNode==0 ) break;
128393
128394     pCsr->nTerm = apSegment[0]->nTerm;
128395     pCsr->zTerm = apSegment[0]->zTerm;
128396
128397     /* If this is a prefix-search, and if the term that apSegment[0] points
128398     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
128399     ** required callbacks have been made. In this case exit early.
128400     **
128401     ** Similarly, if this is a search for an exact match, and the first term
128402     ** of segment apSegment[0] is not a match, exit early.
128403     */
128404     if( pFilter->zTerm && !isScan ){
128405       if( pCsr->nTerm<pFilter->nTerm 
128406        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
128407        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
128408       ){
128409         break;
128410       }
128411     }
128412
128413     nMerge = 1;
128414     while( nMerge<nSegment 
128415         && apSegment[nMerge]->aNode
128416         && apSegment[nMerge]->nTerm==pCsr->nTerm 
128417         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
128418     ){
128419       nMerge++;
128420     }
128421
128422     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
128423     if( nMerge==1 
128424      && !isIgnoreEmpty 
128425      && !isFirst 
128426      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
128427     ){
128428       pCsr->nDoclist = apSegment[0]->nDoclist;
128429       if( fts3SegReaderIsPending(apSegment[0]) ){
128430         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
128431         pCsr->aDoclist = pCsr->aBuffer;
128432       }else{
128433         pCsr->aDoclist = apSegment[0]->aDoclist;
128434       }
128435       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
128436     }else{
128437       int nDoclist = 0;           /* Size of doclist */
128438       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
128439
128440       /* The current term of the first nMerge entries in the array
128441       ** of Fts3SegReader objects is the same. The doclists must be merged
128442       ** and a single term returned with the merged doclist.
128443       */
128444       for(i=0; i<nMerge; i++){
128445         fts3SegReaderFirstDocid(p, apSegment[i]);
128446       }
128447       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
128448       while( apSegment[0]->pOffsetList ){
128449         int j;                    /* Number of segments that share a docid */
128450         char *pList;
128451         int nList;
128452         int nByte;
128453         sqlite3_int64 iDocid = apSegment[0]->iDocid;
128454         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
128455         j = 1;
128456         while( j<nMerge
128457             && apSegment[j]->pOffsetList
128458             && apSegment[j]->iDocid==iDocid
128459         ){
128460           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
128461           j++;
128462         }
128463
128464         if( isColFilter ){
128465           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
128466         }
128467
128468         if( !isIgnoreEmpty || nList>0 ){
128469
128470           /* Calculate the 'docid' delta value to write into the merged 
128471           ** doclist. */
128472           sqlite3_int64 iDelta;
128473           if( p->bDescIdx && nDoclist>0 ){
128474             iDelta = iPrev - iDocid;
128475           }else{
128476             iDelta = iDocid - iPrev;
128477           }
128478           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
128479           assert( nDoclist>0 || iDelta==iDocid );
128480
128481           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
128482           if( nDoclist+nByte>pCsr->nBuffer ){
128483             char *aNew;
128484             pCsr->nBuffer = (nDoclist+nByte)*2;
128485             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
128486             if( !aNew ){
128487               return SQLITE_NOMEM;
128488             }
128489             pCsr->aBuffer = aNew;
128490           }
128491
128492           if( isFirst ){
128493             char *a = &pCsr->aBuffer[nDoclist];
128494             int nWrite;
128495            
128496             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
128497             if( nWrite ){
128498               iPrev = iDocid;
128499               nDoclist += nWrite;
128500             }
128501           }else{
128502             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
128503             iPrev = iDocid;
128504             if( isRequirePos ){
128505               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
128506               nDoclist += nList;
128507               pCsr->aBuffer[nDoclist++] = '\0';
128508             }
128509           }
128510         }
128511
128512         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
128513       }
128514       if( nDoclist>0 ){
128515         pCsr->aDoclist = pCsr->aBuffer;
128516         pCsr->nDoclist = nDoclist;
128517         rc = SQLITE_ROW;
128518       }
128519     }
128520     pCsr->nAdvance = nMerge;
128521   }while( rc==SQLITE_OK );
128522
128523   return rc;
128524 }
128525
128526
128527 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
128528   Fts3MultiSegReader *pCsr       /* Cursor object */
128529 ){
128530   if( pCsr ){
128531     int i;
128532     for(i=0; i<pCsr->nSegment; i++){
128533       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
128534     }
128535     sqlite3_free(pCsr->apSegment);
128536     sqlite3_free(pCsr->aBuffer);
128537
128538     pCsr->nSegment = 0;
128539     pCsr->apSegment = 0;
128540     pCsr->aBuffer = 0;
128541   }
128542 }
128543
128544 /*
128545 ** Merge all level iLevel segments in the database into a single 
128546 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
128547 ** single segment with a level equal to the numerically largest level 
128548 ** currently present in the database.
128549 **
128550 ** If this function is called with iLevel<0, but there is only one
128551 ** segment in the database, SQLITE_DONE is returned immediately. 
128552 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
128553 ** an SQLite error code is returned.
128554 */
128555 static int fts3SegmentMerge(
128556   Fts3Table *p, 
128557   int iLangid,                    /* Language id to merge */
128558   int iIndex,                     /* Index in p->aIndex[] to merge */
128559   int iLevel                      /* Level to merge */
128560 ){
128561   int rc;                         /* Return code */
128562   int iIdx = 0;                   /* Index of new segment */
128563   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
128564   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
128565   Fts3SegFilter filter;           /* Segment term filter condition */
128566   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
128567   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
128568
128569   assert( iLevel==FTS3_SEGCURSOR_ALL
128570        || iLevel==FTS3_SEGCURSOR_PENDING
128571        || iLevel>=0
128572   );
128573   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
128574   assert( iIndex>=0 && iIndex<p->nIndex );
128575
128576   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
128577   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
128578
128579   if( iLevel==FTS3_SEGCURSOR_ALL ){
128580     /* This call is to merge all segments in the database to a single
128581     ** segment. The level of the new segment is equal to the numerically
128582     ** greatest segment level currently present in the database for this
128583     ** index. The idx of the new segment is always 0.  */
128584     if( csr.nSegment==1 ){
128585       rc = SQLITE_DONE;
128586       goto finished;
128587     }
128588     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
128589     bIgnoreEmpty = 1;
128590
128591   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
128592     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
128593     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
128594   }else{
128595     /* This call is to merge all segments at level iLevel. find the next
128596     ** available segment index at level iLevel+1. The call to
128597     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
128598     ** a single iLevel+2 segment if necessary.  */
128599     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
128600     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
128601   }
128602   if( rc!=SQLITE_OK ) goto finished;
128603   assert( csr.nSegment>0 );
128604   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
128605   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
128606
128607   memset(&filter, 0, sizeof(Fts3SegFilter));
128608   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
128609   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
128610
128611   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
128612   while( SQLITE_OK==rc ){
128613     rc = sqlite3Fts3SegReaderStep(p, &csr);
128614     if( rc!=SQLITE_ROW ) break;
128615     rc = fts3SegWriterAdd(p, &pWriter, 1, 
128616         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
128617   }
128618   if( rc!=SQLITE_OK ) goto finished;
128619   assert( pWriter );
128620
128621   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
128622     rc = fts3DeleteSegdir(
128623         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
128624     );
128625     if( rc!=SQLITE_OK ) goto finished;
128626   }
128627   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
128628
128629  finished:
128630   fts3SegWriterFree(pWriter);
128631   sqlite3Fts3SegReaderFinish(&csr);
128632   return rc;
128633 }
128634
128635
128636 /* 
128637 ** Flush the contents of pendingTerms to level 0 segments.
128638 */
128639 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
128640   int rc = SQLITE_OK;
128641   int i;
128642         
128643   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
128644     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
128645     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
128646   }
128647   sqlite3Fts3PendingTermsClear(p);
128648
128649   /* Determine the auto-incr-merge setting if unknown.  If enabled,
128650   ** estimate the number of leaf blocks of content to be written
128651   */
128652   if( rc==SQLITE_OK && p->bHasStat
128653    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
128654   ){
128655     sqlite3_stmt *pStmt = 0;
128656     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
128657     if( rc==SQLITE_OK ){
128658       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
128659       rc = sqlite3_step(pStmt);
128660       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
128661       rc = sqlite3_reset(pStmt);
128662     }
128663   }
128664   return rc;
128665 }
128666
128667 /*
128668 ** Encode N integers as varints into a blob.
128669 */
128670 static void fts3EncodeIntArray(
128671   int N,             /* The number of integers to encode */
128672   u32 *a,            /* The integer values */
128673   char *zBuf,        /* Write the BLOB here */
128674   int *pNBuf         /* Write number of bytes if zBuf[] used here */
128675 ){
128676   int i, j;
128677   for(i=j=0; i<N; i++){
128678     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
128679   }
128680   *pNBuf = j;
128681 }
128682
128683 /*
128684 ** Decode a blob of varints into N integers
128685 */
128686 static void fts3DecodeIntArray(
128687   int N,             /* The number of integers to decode */
128688   u32 *a,            /* Write the integer values */
128689   const char *zBuf,  /* The BLOB containing the varints */
128690   int nBuf           /* size of the BLOB */
128691 ){
128692   int i, j;
128693   UNUSED_PARAMETER(nBuf);
128694   for(i=j=0; i<N; i++){
128695     sqlite3_int64 x;
128696     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
128697     assert(j<=nBuf);
128698     a[i] = (u32)(x & 0xffffffff);
128699   }
128700 }
128701
128702 /*
128703 ** Insert the sizes (in tokens) for each column of the document
128704 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
128705 ** a blob of varints.
128706 */
128707 static void fts3InsertDocsize(
128708   int *pRC,                       /* Result code */
128709   Fts3Table *p,                   /* Table into which to insert */
128710   u32 *aSz                        /* Sizes of each column, in tokens */
128711 ){
128712   char *pBlob;             /* The BLOB encoding of the document size */
128713   int nBlob;               /* Number of bytes in the BLOB */
128714   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
128715   int rc;                  /* Result code from subfunctions */
128716
128717   if( *pRC ) return;
128718   pBlob = sqlite3_malloc( 10*p->nColumn );
128719   if( pBlob==0 ){
128720     *pRC = SQLITE_NOMEM;
128721     return;
128722   }
128723   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
128724   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
128725   if( rc ){
128726     sqlite3_free(pBlob);
128727     *pRC = rc;
128728     return;
128729   }
128730   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
128731   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
128732   sqlite3_step(pStmt);
128733   *pRC = sqlite3_reset(pStmt);
128734 }
128735
128736 /*
128737 ** Record 0 of the %_stat table contains a blob consisting of N varints,
128738 ** where N is the number of user defined columns in the fts3 table plus
128739 ** two. If nCol is the number of user defined columns, then values of the 
128740 ** varints are set as follows:
128741 **
128742 **   Varint 0:       Total number of rows in the table.
128743 **
128744 **   Varint 1..nCol: For each column, the total number of tokens stored in
128745 **                   the column for all rows of the table.
128746 **
128747 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
128748 **                   columns of all rows of the table.
128749 **
128750 */
128751 static void fts3UpdateDocTotals(
128752   int *pRC,                       /* The result code */
128753   Fts3Table *p,                   /* Table being updated */
128754   u32 *aSzIns,                    /* Size increases */
128755   u32 *aSzDel,                    /* Size decreases */
128756   int nChng                       /* Change in the number of documents */
128757 ){
128758   char *pBlob;             /* Storage for BLOB written into %_stat */
128759   int nBlob;               /* Size of BLOB written into %_stat */
128760   u32 *a;                  /* Array of integers that becomes the BLOB */
128761   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
128762   int i;                   /* Loop counter */
128763   int rc;                  /* Result code from subfunctions */
128764
128765   const int nStat = p->nColumn+2;
128766
128767   if( *pRC ) return;
128768   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
128769   if( a==0 ){
128770     *pRC = SQLITE_NOMEM;
128771     return;
128772   }
128773   pBlob = (char*)&a[nStat];
128774   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
128775   if( rc ){
128776     sqlite3_free(a);
128777     *pRC = rc;
128778     return;
128779   }
128780   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
128781   if( sqlite3_step(pStmt)==SQLITE_ROW ){
128782     fts3DecodeIntArray(nStat, a,
128783          sqlite3_column_blob(pStmt, 0),
128784          sqlite3_column_bytes(pStmt, 0));
128785   }else{
128786     memset(a, 0, sizeof(u32)*(nStat) );
128787   }
128788   rc = sqlite3_reset(pStmt);
128789   if( rc!=SQLITE_OK ){
128790     sqlite3_free(a);
128791     *pRC = rc;
128792     return;
128793   }
128794   if( nChng<0 && a[0]<(u32)(-nChng) ){
128795     a[0] = 0;
128796   }else{
128797     a[0] += nChng;
128798   }
128799   for(i=0; i<p->nColumn+1; i++){
128800     u32 x = a[i+1];
128801     if( x+aSzIns[i] < aSzDel[i] ){
128802       x = 0;
128803     }else{
128804       x = x + aSzIns[i] - aSzDel[i];
128805     }
128806     a[i+1] = x;
128807   }
128808   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
128809   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
128810   if( rc ){
128811     sqlite3_free(a);
128812     *pRC = rc;
128813     return;
128814   }
128815   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
128816   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
128817   sqlite3_step(pStmt);
128818   *pRC = sqlite3_reset(pStmt);
128819   sqlite3_free(a);
128820 }
128821
128822 /*
128823 ** Merge the entire database so that there is one segment for each 
128824 ** iIndex/iLangid combination.
128825 */
128826 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
128827   int bSeenDone = 0;
128828   int rc;
128829   sqlite3_stmt *pAllLangid = 0;
128830
128831   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
128832   if( rc==SQLITE_OK ){
128833     int rc2;
128834     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
128835     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
128836       int i;
128837       int iLangid = sqlite3_column_int(pAllLangid, 0);
128838       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
128839         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
128840         if( rc==SQLITE_DONE ){
128841           bSeenDone = 1;
128842           rc = SQLITE_OK;
128843         }
128844       }
128845     }
128846     rc2 = sqlite3_reset(pAllLangid);
128847     if( rc==SQLITE_OK ) rc = rc2;
128848   }
128849
128850   sqlite3Fts3SegmentsClose(p);
128851   sqlite3Fts3PendingTermsClear(p);
128852
128853   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
128854 }
128855
128856 /*
128857 ** This function is called when the user executes the following statement:
128858 **
128859 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
128860 **
128861 ** The entire FTS index is discarded and rebuilt. If the table is one 
128862 ** created using the content=xxx option, then the new index is based on
128863 ** the current contents of the xxx table. Otherwise, it is rebuilt based
128864 ** on the contents of the %_content table.
128865 */
128866 static int fts3DoRebuild(Fts3Table *p){
128867   int rc;                         /* Return Code */
128868
128869   rc = fts3DeleteAll(p, 0);
128870   if( rc==SQLITE_OK ){
128871     u32 *aSz = 0;
128872     u32 *aSzIns = 0;
128873     u32 *aSzDel = 0;
128874     sqlite3_stmt *pStmt = 0;
128875     int nEntry = 0;
128876
128877     /* Compose and prepare an SQL statement to loop through the content table */
128878     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
128879     if( !zSql ){
128880       rc = SQLITE_NOMEM;
128881     }else{
128882       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
128883       sqlite3_free(zSql);
128884     }
128885
128886     if( rc==SQLITE_OK ){
128887       int nByte = sizeof(u32) * (p->nColumn+1)*3;
128888       aSz = (u32 *)sqlite3_malloc(nByte);
128889       if( aSz==0 ){
128890         rc = SQLITE_NOMEM;
128891       }else{
128892         memset(aSz, 0, nByte);
128893         aSzIns = &aSz[p->nColumn+1];
128894         aSzDel = &aSzIns[p->nColumn+1];
128895       }
128896     }
128897
128898     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
128899       int iCol;
128900       int iLangid = langidFromSelect(p, pStmt);
128901       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
128902       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
128903       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
128904         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
128905         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
128906         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
128907       }
128908       if( p->bHasDocsize ){
128909         fts3InsertDocsize(&rc, p, aSz);
128910       }
128911       if( rc!=SQLITE_OK ){
128912         sqlite3_finalize(pStmt);
128913         pStmt = 0;
128914       }else{
128915         nEntry++;
128916         for(iCol=0; iCol<=p->nColumn; iCol++){
128917           aSzIns[iCol] += aSz[iCol];
128918         }
128919       }
128920     }
128921     if( p->bFts4 ){
128922       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
128923     }
128924     sqlite3_free(aSz);
128925
128926     if( pStmt ){
128927       int rc2 = sqlite3_finalize(pStmt);
128928       if( rc==SQLITE_OK ){
128929         rc = rc2;
128930       }
128931     }
128932   }
128933
128934   return rc;
128935 }
128936
128937
128938 /*
128939 ** This function opens a cursor used to read the input data for an 
128940 ** incremental merge operation. Specifically, it opens a cursor to scan
128941 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
128942 ** level iAbsLevel.
128943 */
128944 static int fts3IncrmergeCsr(
128945   Fts3Table *p,                   /* FTS3 table handle */
128946   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
128947   int nSeg,                       /* Number of segments to merge */
128948   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
128949 ){
128950   int rc;                         /* Return Code */
128951   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
128952   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
128953
128954   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
128955   memset(pCsr, 0, sizeof(*pCsr));
128956   nByte = sizeof(Fts3SegReader *) * nSeg;
128957   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
128958
128959   if( pCsr->apSegment==0 ){
128960     rc = SQLITE_NOMEM;
128961   }else{
128962     memset(pCsr->apSegment, 0, nByte);
128963     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
128964   }
128965   if( rc==SQLITE_OK ){
128966     int i;
128967     int rc2;
128968     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
128969     assert( pCsr->nSegment==0 );
128970     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
128971       rc = sqlite3Fts3SegReaderNew(i, 0,
128972           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
128973           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
128974           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
128975           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
128976           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
128977           &pCsr->apSegment[i]
128978       );
128979       pCsr->nSegment++;
128980     }
128981     rc2 = sqlite3_reset(pStmt);
128982     if( rc==SQLITE_OK ) rc = rc2;
128983   }
128984
128985   return rc;
128986 }
128987
128988 typedef struct IncrmergeWriter IncrmergeWriter;
128989 typedef struct NodeWriter NodeWriter;
128990 typedef struct Blob Blob;
128991 typedef struct NodeReader NodeReader;
128992
128993 /*
128994 ** An instance of the following structure is used as a dynamic buffer
128995 ** to build up nodes or other blobs of data in.
128996 **
128997 ** The function blobGrowBuffer() is used to extend the allocation.
128998 */
128999 struct Blob {
129000   char *a;                        /* Pointer to allocation */
129001   int n;                          /* Number of valid bytes of data in a[] */
129002   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
129003 };
129004
129005 /*
129006 ** This structure is used to build up buffers containing segment b-tree 
129007 ** nodes (blocks).
129008 */
129009 struct NodeWriter {
129010   sqlite3_int64 iBlock;           /* Current block id */
129011   Blob key;                       /* Last key written to the current block */
129012   Blob block;                     /* Current block image */
129013 };
129014
129015 /*
129016 ** An object of this type contains the state required to create or append
129017 ** to an appendable b-tree segment.
129018 */
129019 struct IncrmergeWriter {
129020   int nLeafEst;                   /* Space allocated for leaf blocks */
129021   int nWork;                      /* Number of leaf pages flushed */
129022   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
129023   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
129024   sqlite3_int64 iStart;           /* Block number of first allocated block */
129025   sqlite3_int64 iEnd;             /* Block number of last allocated block */
129026   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
129027 };
129028
129029 /*
129030 ** An object of the following type is used to read data from a single
129031 ** FTS segment node. See the following functions:
129032 **
129033 **     nodeReaderInit()
129034 **     nodeReaderNext()
129035 **     nodeReaderRelease()
129036 */
129037 struct NodeReader {
129038   const char *aNode;
129039   int nNode;
129040   int iOff;                       /* Current offset within aNode[] */
129041
129042   /* Output variables. Containing the current node entry. */
129043   sqlite3_int64 iChild;           /* Pointer to child node */
129044   Blob term;                      /* Current term */
129045   const char *aDoclist;           /* Pointer to doclist */
129046   int nDoclist;                   /* Size of doclist in bytes */
129047 };
129048
129049 /*
129050 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129051 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
129052 ** bytes in size, extend (realloc) it to be so.
129053 **
129054 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
129055 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
129056 ** to reflect the new size of the pBlob->a[] buffer.
129057 */
129058 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
129059   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
129060     int nAlloc = nMin;
129061     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
129062     if( a ){
129063       pBlob->nAlloc = nAlloc;
129064       pBlob->a = a;
129065     }else{
129066       *pRc = SQLITE_NOMEM;
129067     }
129068   }
129069 }
129070
129071 /*
129072 ** Attempt to advance the node-reader object passed as the first argument to
129073 ** the next entry on the node. 
129074 **
129075 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
129076 ** Otherwise return SQLITE_OK. If there is no next entry on the node
129077 ** (e.g. because the current entry is the last) set NodeReader->aNode to
129078 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
129079 ** variables for the new entry.
129080 */
129081 static int nodeReaderNext(NodeReader *p){
129082   int bFirst = (p->term.n==0);    /* True for first term on the node */
129083   int nPrefix = 0;                /* Bytes to copy from previous term */
129084   int nSuffix = 0;                /* Bytes to append to the prefix */
129085   int rc = SQLITE_OK;             /* Return code */
129086
129087   assert( p->aNode );
129088   if( p->iChild && bFirst==0 ) p->iChild++;
129089   if( p->iOff>=p->nNode ){
129090     /* EOF */
129091     p->aNode = 0;
129092   }else{
129093     if( bFirst==0 ){
129094       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
129095     }
129096     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
129097
129098     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
129099     if( rc==SQLITE_OK ){
129100       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
129101       p->term.n = nPrefix+nSuffix;
129102       p->iOff += nSuffix;
129103       if( p->iChild==0 ){
129104         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
129105         p->aDoclist = &p->aNode[p->iOff];
129106         p->iOff += p->nDoclist;
129107       }
129108     }
129109   }
129110
129111   assert( p->iOff<=p->nNode );
129112
129113   return rc;
129114 }
129115
129116 /*
129117 ** Release all dynamic resources held by node-reader object *p.
129118 */
129119 static void nodeReaderRelease(NodeReader *p){
129120   sqlite3_free(p->term.a);
129121 }
129122
129123 /*
129124 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
129125 **
129126 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
129127 ** point to the first entry on the node (if any). Otherwise, an SQLite
129128 ** error code is returned.
129129 */
129130 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
129131   memset(p, 0, sizeof(NodeReader));
129132   p->aNode = aNode;
129133   p->nNode = nNode;
129134
129135   /* Figure out if this is a leaf or an internal node. */
129136   if( p->aNode[0] ){
129137     /* An internal node. */
129138     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
129139   }else{
129140     p->iOff = 1;
129141   }
129142
129143   return nodeReaderNext(p);
129144 }
129145
129146 /*
129147 ** This function is called while writing an FTS segment each time a leaf o
129148 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
129149 ** to be greater than the largest key on the node just written, but smaller
129150 ** than or equal to the first key that will be written to the next leaf
129151 ** node.
129152 **
129153 ** The block id of the leaf node just written to disk may be found in
129154 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
129155 */
129156 static int fts3IncrmergePush(
129157   Fts3Table *p,                   /* Fts3 table handle */
129158   IncrmergeWriter *pWriter,       /* Writer object */
129159   const char *zTerm,              /* Term to write to internal node */
129160   int nTerm                       /* Bytes at zTerm */
129161 ){
129162   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
129163   int iLayer;
129164
129165   assert( nTerm>0 );
129166   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
129167     sqlite3_int64 iNextPtr = 0;
129168     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
129169     int rc = SQLITE_OK;
129170     int nPrefix;
129171     int nSuffix;
129172     int nSpace;
129173
129174     /* Figure out how much space the key will consume if it is written to
129175     ** the current node of layer iLayer. Due to the prefix compression, 
129176     ** the space required changes depending on which node the key is to
129177     ** be added to.  */
129178     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
129179     nSuffix = nTerm - nPrefix;
129180     nSpace  = sqlite3Fts3VarintLen(nPrefix);
129181     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
129182
129183     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
129184       /* If the current node of layer iLayer contains zero keys, or if adding
129185       ** the key to it will not cause it to grow to larger than nNodeSize 
129186       ** bytes in size, write the key here.  */
129187
129188       Blob *pBlk = &pNode->block;
129189       if( pBlk->n==0 ){
129190         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
129191         if( rc==SQLITE_OK ){
129192           pBlk->a[0] = (char)iLayer;
129193           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
129194         }
129195       }
129196       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
129197       blobGrowBuffer(&pNode->key, nTerm, &rc);
129198
129199       if( rc==SQLITE_OK ){
129200         if( pNode->key.n ){
129201           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
129202         }
129203         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
129204         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
129205         pBlk->n += nSuffix;
129206
129207         memcpy(pNode->key.a, zTerm, nTerm);
129208         pNode->key.n = nTerm;
129209       }
129210     }else{
129211       /* Otherwise, flush the current node of layer iLayer to disk.
129212       ** Then allocate a new, empty sibling node. The key will be written
129213       ** into the parent of this node. */
129214       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
129215
129216       assert( pNode->block.nAlloc>=p->nNodeSize );
129217       pNode->block.a[0] = (char)iLayer;
129218       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
129219
129220       iNextPtr = pNode->iBlock;
129221       pNode->iBlock++;
129222       pNode->key.n = 0;
129223     }
129224
129225     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
129226     iPtr = iNextPtr;
129227   }
129228
129229   assert( 0 );
129230   return 0;
129231 }
129232
129233 /*
129234 ** Append a term and (optionally) doclist to the FTS segment node currently
129235 ** stored in blob *pNode. The node need not contain any terms, but the
129236 ** header must be written before this function is called.
129237 **
129238 ** A node header is a single 0x00 byte for a leaf node, or a height varint
129239 ** followed by the left-hand-child varint for an internal node.
129240 **
129241 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
129242 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
129243 ** node, both aDoclist and nDoclist must be passed 0.
129244 **
129245 ** If the size of the value in blob pPrev is zero, then this is the first
129246 ** term written to the node. Otherwise, pPrev contains a copy of the 
129247 ** previous term. Before this function returns, it is updated to contain a
129248 ** copy of zTerm/nTerm.
129249 **
129250 ** It is assumed that the buffer associated with pNode is already large
129251 ** enough to accommodate the new entry. The buffer associated with pPrev
129252 ** is extended by this function if requrired.
129253 **
129254 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
129255 ** returned. Otherwise, SQLITE_OK.
129256 */
129257 static int fts3AppendToNode(
129258   Blob *pNode,                    /* Current node image to append to */
129259   Blob *pPrev,                    /* Buffer containing previous term written */
129260   const char *zTerm,              /* New term to write */
129261   int nTerm,                      /* Size of zTerm in bytes */
129262   const char *aDoclist,           /* Doclist (or NULL) to write */
129263   int nDoclist                    /* Size of aDoclist in bytes */ 
129264 ){
129265   int rc = SQLITE_OK;             /* Return code */
129266   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
129267   int nPrefix;                    /* Size of term prefix in bytes */
129268   int nSuffix;                    /* Size of term suffix in bytes */
129269
129270   /* Node must have already been started. There must be a doclist for a
129271   ** leaf node, and there must not be a doclist for an internal node.  */
129272   assert( pNode->n>0 );
129273   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
129274
129275   blobGrowBuffer(pPrev, nTerm, &rc);
129276   if( rc!=SQLITE_OK ) return rc;
129277
129278   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
129279   nSuffix = nTerm - nPrefix;
129280   memcpy(pPrev->a, zTerm, nTerm);
129281   pPrev->n = nTerm;
129282
129283   if( bFirst==0 ){
129284     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
129285   }
129286   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
129287   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
129288   pNode->n += nSuffix;
129289
129290   if( aDoclist ){
129291     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
129292     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
129293     pNode->n += nDoclist;
129294   }
129295
129296   assert( pNode->n<=pNode->nAlloc );
129297
129298   return SQLITE_OK;
129299 }
129300
129301 /*
129302 ** Append the current term and doclist pointed to by cursor pCsr to the
129303 ** appendable b-tree segment opened for writing by pWriter.
129304 **
129305 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
129306 */
129307 static int fts3IncrmergeAppend(
129308   Fts3Table *p,                   /* Fts3 table handle */
129309   IncrmergeWriter *pWriter,       /* Writer object */
129310   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
129311 ){
129312   const char *zTerm = pCsr->zTerm;
129313   int nTerm = pCsr->nTerm;
129314   const char *aDoclist = pCsr->aDoclist;
129315   int nDoclist = pCsr->nDoclist;
129316   int rc = SQLITE_OK;           /* Return code */
129317   int nSpace;                   /* Total space in bytes required on leaf */
129318   int nPrefix;                  /* Size of prefix shared with previous term */
129319   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
129320   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
129321
129322   pLeaf = &pWriter->aNodeWriter[0];
129323   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
129324   nSuffix = nTerm - nPrefix;
129325
129326   nSpace  = sqlite3Fts3VarintLen(nPrefix);
129327   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
129328   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
129329
129330   /* If the current block is not empty, and if adding this term/doclist
129331   ** to the current block would make it larger than Fts3Table.nNodeSize
129332   ** bytes, write this block out to the database. */
129333   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
129334     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
129335     pWriter->nWork++;
129336
129337     /* Add the current term to the parent node. The term added to the 
129338     ** parent must:
129339     **
129340     **   a) be greater than the largest term on the leaf node just written
129341     **      to the database (still available in pLeaf->key), and
129342     **
129343     **   b) be less than or equal to the term about to be added to the new
129344     **      leaf node (zTerm/nTerm).
129345     **
129346     ** In other words, it must be the prefix of zTerm 1 byte longer than
129347     ** the common prefix (if any) of zTerm and pWriter->zTerm.
129348     */
129349     if( rc==SQLITE_OK ){
129350       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
129351     }
129352
129353     /* Advance to the next output block */
129354     pLeaf->iBlock++;
129355     pLeaf->key.n = 0;
129356     pLeaf->block.n = 0;
129357
129358     nSuffix = nTerm;
129359     nSpace  = 1;
129360     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
129361     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
129362   }
129363
129364   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
129365
129366   if( rc==SQLITE_OK ){
129367     if( pLeaf->block.n==0 ){
129368       pLeaf->block.n = 1;
129369       pLeaf->block.a[0] = '\0';
129370     }
129371     rc = fts3AppendToNode(
129372         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
129373     );
129374   }
129375
129376   return rc;
129377 }
129378
129379 /*
129380 ** This function is called to release all dynamic resources held by the
129381 ** merge-writer object pWriter, and if no error has occurred, to flush
129382 ** all outstanding node buffers held by pWriter to disk.
129383 **
129384 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
129385 ** is made to write any data to disk. Instead, this function serves only
129386 ** to release outstanding resources.
129387 **
129388 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
129389 ** flushing buffers to disk, *pRc is set to an SQLite error code before
129390 ** returning.
129391 */
129392 static void fts3IncrmergeRelease(
129393   Fts3Table *p,                   /* FTS3 table handle */
129394   IncrmergeWriter *pWriter,       /* Merge-writer object */
129395   int *pRc                        /* IN/OUT: Error code */
129396 ){
129397   int i;                          /* Used to iterate through non-root layers */
129398   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
129399   NodeWriter *pRoot;              /* NodeWriter for root node */
129400   int rc = *pRc;                  /* Error code */
129401
129402   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
129403   ** root node. If the segment fits entirely on a single leaf node, iRoot
129404   ** will be set to 0. If the root node is the parent of the leaves, iRoot
129405   ** will be 1. And so on.  */
129406   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
129407     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
129408     if( pNode->block.n>0 ) break;
129409     assert( *pRc || pNode->block.nAlloc==0 );
129410     assert( *pRc || pNode->key.nAlloc==0 );
129411     sqlite3_free(pNode->block.a);
129412     sqlite3_free(pNode->key.a);
129413   }
129414
129415   /* Empty output segment. This is a no-op. */
129416   if( iRoot<0 ) return;
129417
129418   /* The entire output segment fits on a single node. Normally, this means
129419   ** the node would be stored as a blob in the "root" column of the %_segdir
129420   ** table. However, this is not permitted in this case. The problem is that 
129421   ** space has already been reserved in the %_segments table, and so the 
129422   ** start_block and end_block fields of the %_segdir table must be populated. 
129423   ** And, by design or by accident, released versions of FTS cannot handle 
129424   ** segments that fit entirely on the root node with start_block!=0.
129425   **
129426   ** Instead, create a synthetic root node that contains nothing but a 
129427   ** pointer to the single content node. So that the segment consists of a
129428   ** single leaf and a single interior (root) node.
129429   **
129430   ** Todo: Better might be to defer allocating space in the %_segments 
129431   ** table until we are sure it is needed.
129432   */
129433   if( iRoot==0 ){
129434     Blob *pBlock = &pWriter->aNodeWriter[1].block;
129435     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
129436     if( rc==SQLITE_OK ){
129437       pBlock->a[0] = 0x01;
129438       pBlock->n = 1 + sqlite3Fts3PutVarint(
129439           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
129440       );
129441     }
129442     iRoot = 1;
129443   }
129444   pRoot = &pWriter->aNodeWriter[iRoot];
129445
129446   /* Flush all currently outstanding nodes to disk. */
129447   for(i=0; i<iRoot; i++){
129448     NodeWriter *pNode = &pWriter->aNodeWriter[i];
129449     if( pNode->block.n>0 && rc==SQLITE_OK ){
129450       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
129451     }
129452     sqlite3_free(pNode->block.a);
129453     sqlite3_free(pNode->key.a);
129454   }
129455
129456   /* Write the %_segdir record. */
129457   if( rc==SQLITE_OK ){
129458     rc = fts3WriteSegdir(p, 
129459         pWriter->iAbsLevel+1,               /* level */
129460         pWriter->iIdx,                      /* idx */
129461         pWriter->iStart,                    /* start_block */
129462         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
129463         pWriter->iEnd,                      /* end_block */
129464         pRoot->block.a, pRoot->block.n      /* root */
129465     );
129466   }
129467   sqlite3_free(pRoot->block.a);
129468   sqlite3_free(pRoot->key.a);
129469
129470   *pRc = rc;
129471 }
129472
129473 /*
129474 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
129475 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
129476 ** the other, it is considered to be smaller than the other.
129477 **
129478 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
129479 ** if it is greater.
129480 */
129481 static int fts3TermCmp(
129482   const char *zLhs, int nLhs,     /* LHS of comparison */
129483   const char *zRhs, int nRhs      /* RHS of comparison */
129484 ){
129485   int nCmp = MIN(nLhs, nRhs);
129486   int res;
129487
129488   res = memcmp(zLhs, zRhs, nCmp);
129489   if( res==0 ) res = nLhs - nRhs;
129490
129491   return res;
129492 }
129493
129494
129495 /*
129496 ** Query to see if the entry in the %_segments table with blockid iEnd is 
129497 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
129498 ** returning. Otherwise, set *pbRes to 0. 
129499 **
129500 ** Or, if an error occurs while querying the database, return an SQLite 
129501 ** error code. The final value of *pbRes is undefined in this case.
129502 **
129503 ** This is used to test if a segment is an "appendable" segment. If it
129504 ** is, then a NULL entry has been inserted into the %_segments table
129505 ** with blockid %_segdir.end_block.
129506 */
129507 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
129508   int bRes = 0;                   /* Result to set *pbRes to */
129509   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
129510   int rc;                         /* Return code */
129511
129512   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
129513   if( rc==SQLITE_OK ){
129514     sqlite3_bind_int64(pCheck, 1, iEnd);
129515     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
129516     rc = sqlite3_reset(pCheck);
129517   }
129518   
129519   *pbRes = bRes;
129520   return rc;
129521 }
129522
129523 /*
129524 ** This function is called when initializing an incremental-merge operation.
129525 ** It checks if the existing segment with index value iIdx at absolute level 
129526 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
129527 ** merge-writer object *pWriter is initialized to write to it.
129528 **
129529 ** An existing segment can be appended to by an incremental merge if:
129530 **
129531 **   * It was initially created as an appendable segment (with all required
129532 **     space pre-allocated), and
129533 **
129534 **   * The first key read from the input (arguments zKey and nKey) is 
129535 **     greater than the largest key currently stored in the potential
129536 **     output segment.
129537 */
129538 static int fts3IncrmergeLoad(
129539   Fts3Table *p,                   /* Fts3 table handle */
129540   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
129541   int iIdx,                       /* Index of candidate output segment */
129542   const char *zKey,               /* First key to write */
129543   int nKey,                       /* Number of bytes in nKey */
129544   IncrmergeWriter *pWriter        /* Populate this object */
129545 ){
129546   int rc;                         /* Return code */
129547   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
129548
129549   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
129550   if( rc==SQLITE_OK ){
129551     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
129552     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
129553     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
129554     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
129555     int nRoot = 0;                /* Size of aRoot[] in bytes */
129556     int rc2;                      /* Return code from sqlite3_reset() */
129557     int bAppendable = 0;          /* Set to true if segment is appendable */
129558
129559     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
129560     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
129561     sqlite3_bind_int(pSelect, 2, iIdx);
129562     if( sqlite3_step(pSelect)==SQLITE_ROW ){
129563       iStart = sqlite3_column_int64(pSelect, 1);
129564       iLeafEnd = sqlite3_column_int64(pSelect, 2);
129565       iEnd = sqlite3_column_int64(pSelect, 3);
129566       nRoot = sqlite3_column_bytes(pSelect, 4);
129567       aRoot = sqlite3_column_blob(pSelect, 4);
129568     }else{
129569       return sqlite3_reset(pSelect);
129570     }
129571
129572     /* Check for the zero-length marker in the %_segments table */
129573     rc = fts3IsAppendable(p, iEnd, &bAppendable);
129574
129575     /* Check that zKey/nKey is larger than the largest key the candidate */
129576     if( rc==SQLITE_OK && bAppendable ){
129577       char *aLeaf = 0;
129578       int nLeaf = 0;
129579
129580       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
129581       if( rc==SQLITE_OK ){
129582         NodeReader reader;
129583         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
129584             rc==SQLITE_OK && reader.aNode;
129585             rc = nodeReaderNext(&reader)
129586         ){
129587           assert( reader.aNode );
129588         }
129589         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
129590           bAppendable = 0;
129591         }
129592         nodeReaderRelease(&reader);
129593       }
129594       sqlite3_free(aLeaf);
129595     }
129596
129597     if( rc==SQLITE_OK && bAppendable ){
129598       /* It is possible to append to this segment. Set up the IncrmergeWriter
129599       ** object to do so.  */
129600       int i;
129601       int nHeight = (int)aRoot[0];
129602       NodeWriter *pNode;
129603
129604       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
129605       pWriter->iStart = iStart;
129606       pWriter->iEnd = iEnd;
129607       pWriter->iAbsLevel = iAbsLevel;
129608       pWriter->iIdx = iIdx;
129609
129610       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
129611         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
129612       }
129613
129614       pNode = &pWriter->aNodeWriter[nHeight];
129615       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
129616       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
129617       if( rc==SQLITE_OK ){
129618         memcpy(pNode->block.a, aRoot, nRoot);
129619         pNode->block.n = nRoot;
129620       }
129621
129622       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
129623         NodeReader reader;
129624         pNode = &pWriter->aNodeWriter[i];
129625
129626         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
129627         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
129628         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
129629         if( rc==SQLITE_OK ){
129630           memcpy(pNode->key.a, reader.term.a, reader.term.n);
129631           pNode->key.n = reader.term.n;
129632           if( i>0 ){
129633             char *aBlock = 0;
129634             int nBlock = 0;
129635             pNode = &pWriter->aNodeWriter[i-1];
129636             pNode->iBlock = reader.iChild;
129637             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
129638             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
129639             if( rc==SQLITE_OK ){
129640               memcpy(pNode->block.a, aBlock, nBlock);
129641               pNode->block.n = nBlock;
129642             }
129643             sqlite3_free(aBlock);
129644           }
129645         }
129646         nodeReaderRelease(&reader);
129647       }
129648     }
129649
129650     rc2 = sqlite3_reset(pSelect);
129651     if( rc==SQLITE_OK ) rc = rc2;
129652   }
129653
129654   return rc;
129655 }
129656
129657 /*
129658 ** Determine the largest segment index value that exists within absolute
129659 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
129660 ** one before returning SQLITE_OK. Or, if there are no segments at all 
129661 ** within level iAbsLevel, set *piIdx to zero.
129662 **
129663 ** If an error occurs, return an SQLite error code. The final value of
129664 ** *piIdx is undefined in this case.
129665 */
129666 static int fts3IncrmergeOutputIdx( 
129667   Fts3Table *p,                   /* FTS Table handle */
129668   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
129669   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
129670 ){
129671   int rc;
129672   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
129673
129674   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
129675   if( rc==SQLITE_OK ){
129676     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
129677     sqlite3_step(pOutputIdx);
129678     *piIdx = sqlite3_column_int(pOutputIdx, 0);
129679     rc = sqlite3_reset(pOutputIdx);
129680   }
129681
129682   return rc;
129683 }
129684
129685 /* 
129686 ** Allocate an appendable output segment on absolute level iAbsLevel+1
129687 ** with idx value iIdx.
129688 **
129689 ** In the %_segdir table, a segment is defined by the values in three
129690 ** columns:
129691 **
129692 **     start_block
129693 **     leaves_end_block
129694 **     end_block
129695 **
129696 ** When an appendable segment is allocated, it is estimated that the
129697 ** maximum number of leaf blocks that may be required is the sum of the
129698 ** number of leaf blocks consumed by the input segments, plus the number
129699 ** of input segments, multiplied by two. This value is stored in stack 
129700 ** variable nLeafEst.
129701 **
129702 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
129703 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
129704 ** array of leaf nodes starts at the first block allocated. The array
129705 ** of interior nodes that are parents of the leaf nodes start at block
129706 ** (start_block + (1 + end_block - start_block) / 16). And so on.
129707 **
129708 ** In the actual code below, the value "16" is replaced with the 
129709 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
129710 */
129711 static int fts3IncrmergeWriter( 
129712   Fts3Table *p,                   /* Fts3 table handle */
129713   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
129714   int iIdx,                       /* Index of new output segment */
129715   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
129716   IncrmergeWriter *pWriter        /* Populate this object */
129717 ){
129718   int rc;                         /* Return Code */
129719   int i;                          /* Iterator variable */
129720   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
129721   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
129722   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
129723
129724   /* Calculate nLeafEst. */
129725   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
129726   if( rc==SQLITE_OK ){
129727     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
129728     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
129729     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
129730       nLeafEst = sqlite3_column_int(pLeafEst, 0);
129731     }
129732     rc = sqlite3_reset(pLeafEst);
129733   }
129734   if( rc!=SQLITE_OK ) return rc;
129735
129736   /* Calculate the first block to use in the output segment */
129737   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
129738   if( rc==SQLITE_OK ){
129739     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
129740       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
129741       pWriter->iEnd = pWriter->iStart - 1;
129742       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
129743     }
129744     rc = sqlite3_reset(pFirstBlock);
129745   }
129746   if( rc!=SQLITE_OK ) return rc;
129747
129748   /* Insert the marker in the %_segments table to make sure nobody tries
129749   ** to steal the space just allocated. This is also used to identify 
129750   ** appendable segments.  */
129751   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
129752   if( rc!=SQLITE_OK ) return rc;
129753
129754   pWriter->iAbsLevel = iAbsLevel;
129755   pWriter->nLeafEst = nLeafEst;
129756   pWriter->iIdx = iIdx;
129757
129758   /* Set up the array of NodeWriter objects */
129759   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
129760     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
129761   }
129762   return SQLITE_OK;
129763 }
129764
129765 /*
129766 ** Remove an entry from the %_segdir table. This involves running the 
129767 ** following two statements:
129768 **
129769 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
129770 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
129771 **
129772 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
129773 ** statement ensures that the remaining segments have contiguously allocated
129774 ** idx values.
129775 */
129776 static int fts3RemoveSegdirEntry(
129777   Fts3Table *p,                   /* FTS3 table handle */
129778   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
129779   int iIdx                        /* Index of %_segdir entry to delete */
129780 ){
129781   int rc;                         /* Return code */
129782   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
129783
129784   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
129785   if( rc==SQLITE_OK ){
129786     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
129787     sqlite3_bind_int(pDelete, 2, iIdx);
129788     sqlite3_step(pDelete);
129789     rc = sqlite3_reset(pDelete);
129790   }
129791
129792   return rc;
129793 }
129794
129795 /*
129796 ** One or more segments have just been removed from absolute level iAbsLevel.
129797 ** Update the 'idx' values of the remaining segments in the level so that
129798 ** the idx values are a contiguous sequence starting from 0.
129799 */
129800 static int fts3RepackSegdirLevel(
129801   Fts3Table *p,                   /* FTS3 table handle */
129802   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
129803 ){
129804   int rc;                         /* Return code */
129805   int *aIdx = 0;                  /* Array of remaining idx values */
129806   int nIdx = 0;                   /* Valid entries in aIdx[] */
129807   int nAlloc = 0;                 /* Allocated size of aIdx[] */
129808   int i;                          /* Iterator variable */
129809   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
129810   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
129811
129812   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
129813   if( rc==SQLITE_OK ){
129814     int rc2;
129815     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
129816     while( SQLITE_ROW==sqlite3_step(pSelect) ){
129817       if( nIdx>=nAlloc ){
129818         int *aNew;
129819         nAlloc += 16;
129820         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
129821         if( !aNew ){
129822           rc = SQLITE_NOMEM;
129823           break;
129824         }
129825         aIdx = aNew;
129826       }
129827       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
129828     }
129829     rc2 = sqlite3_reset(pSelect);
129830     if( rc==SQLITE_OK ) rc = rc2;
129831   }
129832
129833   if( rc==SQLITE_OK ){
129834     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
129835   }
129836   if( rc==SQLITE_OK ){
129837     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
129838   }
129839
129840   assert( p->bIgnoreSavepoint==0 );
129841   p->bIgnoreSavepoint = 1;
129842   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
129843     if( aIdx[i]!=i ){
129844       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
129845       sqlite3_bind_int(pUpdate, 1, i);
129846       sqlite3_step(pUpdate);
129847       rc = sqlite3_reset(pUpdate);
129848     }
129849   }
129850   p->bIgnoreSavepoint = 0;
129851
129852   sqlite3_free(aIdx);
129853   return rc;
129854 }
129855
129856 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
129857   pNode->a[0] = (char)iHeight;
129858   if( iChild ){
129859     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
129860     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
129861   }else{
129862     assert( pNode->nAlloc>=1 );
129863     pNode->n = 1;
129864   }
129865 }
129866
129867 /*
129868 ** The first two arguments are a pointer to and the size of a segment b-tree
129869 ** node. The node may be a leaf or an internal node.
129870 **
129871 ** This function creates a new node image in blob object *pNew by copying
129872 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
129873 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
129874 */
129875 static int fts3TruncateNode(
129876   const char *aNode,              /* Current node image */
129877   int nNode,                      /* Size of aNode in bytes */
129878   Blob *pNew,                     /* OUT: Write new node image here */
129879   const char *zTerm,              /* Omit all terms smaller than this */
129880   int nTerm,                      /* Size of zTerm in bytes */
129881   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
129882 ){
129883   NodeReader reader;              /* Reader object */
129884   Blob prev = {0, 0, 0};          /* Previous term written to new node */
129885   int rc = SQLITE_OK;             /* Return code */
129886   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
129887
129888   /* Allocate required output space */
129889   blobGrowBuffer(pNew, nNode, &rc);
129890   if( rc!=SQLITE_OK ) return rc;
129891   pNew->n = 0;
129892
129893   /* Populate new node buffer */
129894   for(rc = nodeReaderInit(&reader, aNode, nNode); 
129895       rc==SQLITE_OK && reader.aNode; 
129896       rc = nodeReaderNext(&reader)
129897   ){
129898     if( pNew->n==0 ){
129899       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
129900       if( res<0 || (bLeaf==0 && res==0) ) continue;
129901       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
129902       *piBlock = reader.iChild;
129903     }
129904     rc = fts3AppendToNode(
129905         pNew, &prev, reader.term.a, reader.term.n,
129906         reader.aDoclist, reader.nDoclist
129907     );
129908     if( rc!=SQLITE_OK ) break;
129909   }
129910   if( pNew->n==0 ){
129911     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
129912     *piBlock = reader.iChild;
129913   }
129914   assert( pNew->n<=pNew->nAlloc );
129915
129916   nodeReaderRelease(&reader);
129917   sqlite3_free(prev.a);
129918   return rc;
129919 }
129920
129921 /*
129922 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
129923 ** level iAbsLevel. This may involve deleting entries from the %_segments
129924 ** table, and modifying existing entries in both the %_segments and %_segdir
129925 ** tables.
129926 **
129927 ** SQLITE_OK is returned if the segment is updated successfully. Or an
129928 ** SQLite error code otherwise.
129929 */
129930 static int fts3TruncateSegment(
129931   Fts3Table *p,                   /* FTS3 table handle */
129932   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
129933   int iIdx,                       /* Index within level of segment to modify */
129934   const char *zTerm,              /* Remove terms smaller than this */
129935   int nTerm                      /* Number of bytes in buffer zTerm */
129936 ){
129937   int rc = SQLITE_OK;             /* Return code */
129938   Blob root = {0,0,0};            /* New root page image */
129939   Blob block = {0,0,0};           /* Buffer used for any other block */
129940   sqlite3_int64 iBlock = 0;       /* Block id */
129941   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
129942   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
129943   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
129944
129945   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
129946   if( rc==SQLITE_OK ){
129947     int rc2;                      /* sqlite3_reset() return code */
129948     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
129949     sqlite3_bind_int(pFetch, 2, iIdx);
129950     if( SQLITE_ROW==sqlite3_step(pFetch) ){
129951       const char *aRoot = sqlite3_column_blob(pFetch, 4);
129952       int nRoot = sqlite3_column_bytes(pFetch, 4);
129953       iOldStart = sqlite3_column_int64(pFetch, 1);
129954       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
129955     }
129956     rc2 = sqlite3_reset(pFetch);
129957     if( rc==SQLITE_OK ) rc = rc2;
129958   }
129959
129960   while( rc==SQLITE_OK && iBlock ){
129961     char *aBlock = 0;
129962     int nBlock = 0;
129963     iNewStart = iBlock;
129964
129965     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
129966     if( rc==SQLITE_OK ){
129967       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
129968     }
129969     if( rc==SQLITE_OK ){
129970       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
129971     }
129972     sqlite3_free(aBlock);
129973   }
129974
129975   /* Variable iNewStart now contains the first valid leaf node. */
129976   if( rc==SQLITE_OK && iNewStart ){
129977     sqlite3_stmt *pDel = 0;
129978     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
129979     if( rc==SQLITE_OK ){
129980       sqlite3_bind_int64(pDel, 1, iOldStart);
129981       sqlite3_bind_int64(pDel, 2, iNewStart-1);
129982       sqlite3_step(pDel);
129983       rc = sqlite3_reset(pDel);
129984     }
129985   }
129986
129987   if( rc==SQLITE_OK ){
129988     sqlite3_stmt *pChomp = 0;
129989     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
129990     if( rc==SQLITE_OK ){
129991       sqlite3_bind_int64(pChomp, 1, iNewStart);
129992       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
129993       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
129994       sqlite3_bind_int(pChomp, 4, iIdx);
129995       sqlite3_step(pChomp);
129996       rc = sqlite3_reset(pChomp);
129997     }
129998   }
129999
130000   sqlite3_free(root.a);
130001   sqlite3_free(block.a);
130002   return rc;
130003 }
130004
130005 /*
130006 ** This function is called after an incrmental-merge operation has run to
130007 ** merge (or partially merge) two or more segments from absolute level
130008 ** iAbsLevel.
130009 **
130010 ** Each input segment is either removed from the db completely (if all of
130011 ** its data was copied to the output segment by the incrmerge operation)
130012 ** or modified in place so that it no longer contains those entries that
130013 ** have been duplicated in the output segment.
130014 */
130015 static int fts3IncrmergeChomp(
130016   Fts3Table *p,                   /* FTS table handle */
130017   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
130018   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
130019   int *pnRem                      /* Number of segments not deleted */
130020 ){
130021   int i;
130022   int nRem = 0;
130023   int rc = SQLITE_OK;
130024
130025   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
130026     Fts3SegReader *pSeg = 0;
130027     int j;
130028
130029     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
130030     ** somewhere in the pCsr->apSegment[] array.  */
130031     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
130032       pSeg = pCsr->apSegment[j];
130033       if( pSeg->iIdx==i ) break;
130034     }
130035     assert( j<pCsr->nSegment && pSeg->iIdx==i );
130036
130037     if( pSeg->aNode==0 ){
130038       /* Seg-reader is at EOF. Remove the entire input segment. */
130039       rc = fts3DeleteSegment(p, pSeg);
130040       if( rc==SQLITE_OK ){
130041         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
130042       }
130043       *pnRem = 0;
130044     }else{
130045       /* The incremental merge did not copy all the data from this 
130046       ** segment to the upper level. The segment is modified in place
130047       ** so that it contains no keys smaller than zTerm/nTerm. */ 
130048       const char *zTerm = pSeg->zTerm;
130049       int nTerm = pSeg->nTerm;
130050       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
130051       nRem++;
130052     }
130053   }
130054
130055   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
130056     rc = fts3RepackSegdirLevel(p, iAbsLevel);
130057   }
130058
130059   *pnRem = nRem;
130060   return rc;
130061 }
130062
130063 /*
130064 ** Store an incr-merge hint in the database.
130065 */
130066 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
130067   sqlite3_stmt *pReplace = 0;
130068   int rc;                         /* Return code */
130069
130070   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
130071   if( rc==SQLITE_OK ){
130072     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
130073     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
130074     sqlite3_step(pReplace);
130075     rc = sqlite3_reset(pReplace);
130076   }
130077
130078   return rc;
130079 }
130080
130081 /*
130082 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
130083 ** exists, is stored in the rowid==1 row of the %_stat table.
130084 **
130085 ** If successful, populate blob *pHint with the value read from the %_stat
130086 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
130087 ** SQLite error code.
130088 */
130089 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
130090   sqlite3_stmt *pSelect = 0;
130091   int rc;
130092
130093   pHint->n = 0;
130094   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
130095   if( rc==SQLITE_OK ){
130096     int rc2;
130097     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
130098     if( SQLITE_ROW==sqlite3_step(pSelect) ){
130099       const char *aHint = sqlite3_column_blob(pSelect, 0);
130100       int nHint = sqlite3_column_bytes(pSelect, 0);
130101       if( aHint ){
130102         blobGrowBuffer(pHint, nHint, &rc);
130103         if( rc==SQLITE_OK ){
130104           memcpy(pHint->a, aHint, nHint);
130105           pHint->n = nHint;
130106         }
130107       }
130108     }
130109     rc2 = sqlite3_reset(pSelect);
130110     if( rc==SQLITE_OK ) rc = rc2;
130111   }
130112
130113   return rc;
130114 }
130115
130116 /*
130117 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130118 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
130119 ** consists of two varints, the absolute level number of the input segments 
130120 ** and the number of input segments.
130121 **
130122 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
130123 ** set *pRc to an SQLite error code before returning.
130124 */
130125 static void fts3IncrmergeHintPush(
130126   Blob *pHint,                    /* Hint blob to append to */
130127   i64 iAbsLevel,                  /* First varint to store in hint */
130128   int nInput,                     /* Second varint to store in hint */
130129   int *pRc                        /* IN/OUT: Error code */
130130 ){
130131   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
130132   if( *pRc==SQLITE_OK ){
130133     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
130134     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
130135   }
130136 }
130137
130138 /*
130139 ** Read the last entry (most recently pushed) from the hint blob *pHint
130140 ** and then remove the entry. Write the two values read to *piAbsLevel and 
130141 ** *pnInput before returning.
130142 **
130143 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
130144 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
130145 */
130146 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
130147   const int nHint = pHint->n;
130148   int i;
130149
130150   i = pHint->n-2;
130151   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130152   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130153
130154   pHint->n = i;
130155   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
130156   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
130157   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
130158
130159   return SQLITE_OK;
130160 }
130161
130162
130163 /*
130164 ** Attempt an incremental merge that writes nMerge leaf blocks.
130165 **
130166 ** Incremental merges happen nMin segments at a time. The two
130167 ** segments to be merged are the nMin oldest segments (the ones with
130168 ** the smallest indexes) in the highest level that contains at least
130169 ** nMin segments. Multiple merges might occur in an attempt to write the 
130170 ** quota of nMerge leaf blocks.
130171 */
130172 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
130173   int rc;                         /* Return code */
130174   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
130175   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
130176   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
130177   IncrmergeWriter *pWriter;       /* Writer object */
130178   int nSeg = 0;                   /* Number of input segments */
130179   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
130180   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
130181   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
130182
130183   /* Allocate space for the cursor, filter and writer objects */
130184   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
130185   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
130186   if( !pWriter ) return SQLITE_NOMEM;
130187   pFilter = (Fts3SegFilter *)&pWriter[1];
130188   pCsr = (Fts3MultiSegReader *)&pFilter[1];
130189
130190   rc = fts3IncrmergeHintLoad(p, &hint);
130191   while( rc==SQLITE_OK && nRem>0 ){
130192     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
130193     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
130194     int bUseHint = 0;             /* True if attempting to append */
130195
130196     /* Search the %_segdir table for the absolute level with the smallest
130197     ** relative level number that contains at least nMin segments, if any.
130198     ** If one is found, set iAbsLevel to the absolute level number and
130199     ** nSeg to nMin. If no level with at least nMin segments can be found, 
130200     ** set nSeg to -1.
130201     */
130202     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
130203     sqlite3_bind_int(pFindLevel, 1, nMin);
130204     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
130205       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
130206       nSeg = nMin;
130207     }else{
130208       nSeg = -1;
130209     }
130210     rc = sqlite3_reset(pFindLevel);
130211
130212     /* If the hint read from the %_stat table is not empty, check if the
130213     ** last entry in it specifies a relative level smaller than or equal
130214     ** to the level identified by the block above (if any). If so, this 
130215     ** iteration of the loop will work on merging at the hinted level.
130216     */
130217     if( rc==SQLITE_OK && hint.n ){
130218       int nHint = hint.n;
130219       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
130220       int nHintSeg = 0;                     /* Hint number of segments */
130221
130222       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
130223       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
130224         iAbsLevel = iHintAbsLevel;
130225         nSeg = nHintSeg;
130226         bUseHint = 1;
130227         bDirtyHint = 1;
130228       }else{
130229         /* This undoes the effect of the HintPop() above - so that no entry
130230         ** is removed from the hint blob.  */
130231         hint.n = nHint;
130232       }
130233     }
130234
130235     /* If nSeg is less that zero, then there is no level with at least
130236     ** nMin segments and no hint in the %_stat table. No work to do.
130237     ** Exit early in this case.  */
130238     if( nSeg<0 ) break;
130239
130240     /* Open a cursor to iterate through the contents of the oldest nSeg 
130241     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
130242     ** the 'hint' parameters, it is possible that there are less than nSeg
130243     ** segments available in level iAbsLevel. In this case, no work is
130244     ** done on iAbsLevel - fall through to the next iteration of the loop 
130245     ** to start work on some other level.  */
130246     memset(pWriter, 0, nAlloc);
130247     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
130248     if( rc==SQLITE_OK ){
130249       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
130250     }
130251     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
130252      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
130253      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
130254     ){
130255       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
130256       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
130257       if( rc==SQLITE_OK ){
130258         if( bUseHint && iIdx>0 ){
130259           const char *zKey = pCsr->zTerm;
130260           int nKey = pCsr->nTerm;
130261           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
130262         }else{
130263           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
130264         }
130265       }
130266
130267       if( rc==SQLITE_OK && pWriter->nLeafEst ){
130268         fts3LogMerge(nSeg, iAbsLevel);
130269         do {
130270           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
130271           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
130272           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
130273         }while( rc==SQLITE_ROW );
130274
130275         /* Update or delete the input segments */
130276         if( rc==SQLITE_OK ){
130277           nRem -= (1 + pWriter->nWork);
130278           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
130279           if( nSeg!=0 ){
130280             bDirtyHint = 1;
130281             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
130282           }
130283         }
130284       }
130285
130286       fts3IncrmergeRelease(p, pWriter, &rc);
130287     }
130288
130289     sqlite3Fts3SegReaderFinish(pCsr);
130290   }
130291
130292   /* Write the hint values into the %_stat table for the next incr-merger */
130293   if( bDirtyHint && rc==SQLITE_OK ){
130294     rc = fts3IncrmergeHintStore(p, &hint);
130295   }
130296
130297   sqlite3_free(pWriter);
130298   sqlite3_free(hint.a);
130299   return rc;
130300 }
130301
130302 /*
130303 ** Convert the text beginning at *pz into an integer and return
130304 ** its value.  Advance *pz to point to the first character past
130305 ** the integer.
130306 */
130307 static int fts3Getint(const char **pz){
130308   const char *z = *pz;
130309   int i = 0;
130310   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
130311   *pz = z;
130312   return i;
130313 }
130314
130315 /*
130316 ** Process statements of the form:
130317 **
130318 **    INSERT INTO table(table) VALUES('merge=A,B');
130319 **
130320 ** A and B are integers that decode to be the number of leaf pages
130321 ** written for the merge, and the minimum number of segments on a level
130322 ** before it will be selected for a merge, respectively.
130323 */
130324 static int fts3DoIncrmerge(
130325   Fts3Table *p,                   /* FTS3 table handle */
130326   const char *zParam              /* Nul-terminated string containing "A,B" */
130327 ){
130328   int rc;
130329   int nMin = (FTS3_MERGE_COUNT / 2);
130330   int nMerge = 0;
130331   const char *z = zParam;
130332
130333   /* Read the first integer value */
130334   nMerge = fts3Getint(&z);
130335
130336   /* If the first integer value is followed by a ',',  read the second
130337   ** integer value. */
130338   if( z[0]==',' && z[1]!='\0' ){
130339     z++;
130340     nMin = fts3Getint(&z);
130341   }
130342
130343   if( z[0]!='\0' || nMin<2 ){
130344     rc = SQLITE_ERROR;
130345   }else{
130346     rc = SQLITE_OK;
130347     if( !p->bHasStat ){
130348       assert( p->bFts4==0 );
130349       sqlite3Fts3CreateStatTable(&rc, p);
130350     }
130351     if( rc==SQLITE_OK ){
130352       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
130353     }
130354     sqlite3Fts3SegmentsClose(p);
130355   }
130356   return rc;
130357 }
130358
130359 /*
130360 ** Process statements of the form:
130361 **
130362 **    INSERT INTO table(table) VALUES('automerge=X');
130363 **
130364 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
130365 ** turn it on.  The setting is persistent.
130366 */
130367 static int fts3DoAutoincrmerge(
130368   Fts3Table *p,                   /* FTS3 table handle */
130369   const char *zParam              /* Nul-terminated string containing boolean */
130370 ){
130371   int rc = SQLITE_OK;
130372   sqlite3_stmt *pStmt = 0;
130373   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
130374   if( !p->bHasStat ){
130375     assert( p->bFts4==0 );
130376     sqlite3Fts3CreateStatTable(&rc, p);
130377     if( rc ) return rc;
130378   }
130379   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
130380   if( rc ) return rc;;
130381   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
130382   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
130383   sqlite3_step(pStmt);
130384   rc = sqlite3_reset(pStmt);
130385   return rc;
130386 }
130387
130388 /*
130389 ** Return a 64-bit checksum for the FTS index entry specified by the
130390 ** arguments to this function.
130391 */
130392 static u64 fts3ChecksumEntry(
130393   const char *zTerm,              /* Pointer to buffer containing term */
130394   int nTerm,                      /* Size of zTerm in bytes */
130395   int iLangid,                    /* Language id for current row */
130396   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
130397   i64 iDocid,                     /* Docid for current row. */
130398   int iCol,                       /* Column number */
130399   int iPos                        /* Position */
130400 ){
130401   int i;
130402   u64 ret = (u64)iDocid;
130403
130404   ret += (ret<<3) + iLangid;
130405   ret += (ret<<3) + iIndex;
130406   ret += (ret<<3) + iCol;
130407   ret += (ret<<3) + iPos;
130408   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
130409
130410   return ret;
130411 }
130412
130413 /*
130414 ** Return a checksum of all entries in the FTS index that correspond to
130415 ** language id iLangid. The checksum is calculated by XORing the checksums
130416 ** of each individual entry (see fts3ChecksumEntry()) together.
130417 **
130418 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
130419 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
130420 ** return value is undefined in this case.
130421 */
130422 static u64 fts3ChecksumIndex(
130423   Fts3Table *p,                   /* FTS3 table handle */
130424   int iLangid,                    /* Language id to return cksum for */
130425   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
130426   int *pRc                        /* OUT: Return code */
130427 ){
130428   Fts3SegFilter filter;
130429   Fts3MultiSegReader csr;
130430   int rc;
130431   u64 cksum = 0;
130432
130433   assert( *pRc==SQLITE_OK );
130434
130435   memset(&filter, 0, sizeof(filter));
130436   memset(&csr, 0, sizeof(csr));
130437   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
130438   filter.flags |= FTS3_SEGMENT_SCAN;
130439
130440   rc = sqlite3Fts3SegReaderCursor(
130441       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
130442   );
130443   if( rc==SQLITE_OK ){
130444     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
130445   }
130446
130447   if( rc==SQLITE_OK ){
130448     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
130449       char *pCsr = csr.aDoclist;
130450       char *pEnd = &pCsr[csr.nDoclist];
130451
130452       i64 iDocid = 0;
130453       i64 iCol = 0;
130454       i64 iPos = 0;
130455
130456       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
130457       while( pCsr<pEnd ){
130458         i64 iVal = 0;
130459         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
130460         if( pCsr<pEnd ){
130461           if( iVal==0 || iVal==1 ){
130462             iCol = 0;
130463             iPos = 0;
130464             if( iVal ){
130465               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
130466             }else{
130467               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
130468               iDocid += iVal;
130469             }
130470           }else{
130471             iPos += (iVal - 2);
130472             cksum = cksum ^ fts3ChecksumEntry(
130473                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
130474                 (int)iCol, (int)iPos
130475             );
130476           }
130477         }
130478       }
130479     }
130480   }
130481   sqlite3Fts3SegReaderFinish(&csr);
130482
130483   *pRc = rc;
130484   return cksum;
130485 }
130486
130487 /*
130488 ** Check if the contents of the FTS index match the current contents of the
130489 ** content table. If no error occurs and the contents do match, set *pbOk
130490 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
130491 ** to false before returning.
130492 **
130493 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
130494 ** code. The final value of *pbOk is undefined in this case.
130495 */
130496 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
130497   int rc = SQLITE_OK;             /* Return code */
130498   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
130499   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
130500   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
130501
130502   /* This block calculates the checksum according to the FTS index. */
130503   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
130504   if( rc==SQLITE_OK ){
130505     int rc2;
130506     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
130507     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
130508       int iLangid = sqlite3_column_int(pAllLangid, 0);
130509       int i;
130510       for(i=0; i<p->nIndex; i++){
130511         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
130512       }
130513     }
130514     rc2 = sqlite3_reset(pAllLangid);
130515     if( rc==SQLITE_OK ) rc = rc2;
130516   }
130517
130518   /* This block calculates the checksum according to the %_content table */
130519   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
130520   if( rc==SQLITE_OK ){
130521     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
130522     sqlite3_stmt *pStmt = 0;
130523     char *zSql;
130524    
130525     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
130526     if( !zSql ){
130527       rc = SQLITE_NOMEM;
130528     }else{
130529       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
130530       sqlite3_free(zSql);
130531     }
130532
130533     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
130534       i64 iDocid = sqlite3_column_int64(pStmt, 0);
130535       int iLang = langidFromSelect(p, pStmt);
130536       int iCol;
130537
130538       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
130539         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
130540         int nText = sqlite3_column_bytes(pStmt, iCol+1);
130541         sqlite3_tokenizer_cursor *pT = 0;
130542
130543         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
130544         while( rc==SQLITE_OK ){
130545           char const *zToken;       /* Buffer containing token */
130546           int nToken = 0;           /* Number of bytes in token */
130547           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
130548           int iPos = 0;             /* Position of token in zText */
130549
130550           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
130551           if( rc==SQLITE_OK ){
130552             int i;
130553             cksum2 = cksum2 ^ fts3ChecksumEntry(
130554                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
130555             );
130556             for(i=1; i<p->nIndex; i++){
130557               if( p->aIndex[i].nPrefix<=nToken ){
130558                 cksum2 = cksum2 ^ fts3ChecksumEntry(
130559                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
130560                 );
130561               }
130562             }
130563           }
130564         }
130565         if( pT ) pModule->xClose(pT);
130566         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
130567       }
130568     }
130569
130570     sqlite3_finalize(pStmt);
130571   }
130572
130573   *pbOk = (cksum1==cksum2);
130574   return rc;
130575 }
130576
130577 /*
130578 ** Run the integrity-check. If no error occurs and the current contents of
130579 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
130580 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
130581 **
130582 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
130583 ** error code.
130584 **
130585 ** The integrity-check works as follows. For each token and indexed token
130586 ** prefix in the document set, a 64-bit checksum is calculated (by code
130587 ** in fts3ChecksumEntry()) based on the following:
130588 **
130589 **     + The index number (0 for the main index, 1 for the first prefix
130590 **       index etc.),
130591 **     + The token (or token prefix) text itself, 
130592 **     + The language-id of the row it appears in,
130593 **     + The docid of the row it appears in,
130594 **     + The column it appears in, and
130595 **     + The tokens position within that column.
130596 **
130597 ** The checksums for all entries in the index are XORed together to create
130598 ** a single checksum for the entire index.
130599 **
130600 ** The integrity-check code calculates the same checksum in two ways:
130601 **
130602 **     1. By scanning the contents of the FTS index, and 
130603 **     2. By scanning and tokenizing the content table.
130604 **
130605 ** If the two checksums are identical, the integrity-check is deemed to have
130606 ** passed.
130607 */
130608 static int fts3DoIntegrityCheck(
130609   Fts3Table *p                    /* FTS3 table handle */
130610 ){
130611   int rc;
130612   int bOk = 0;
130613   rc = fts3IntegrityCheck(p, &bOk);
130614   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
130615   return rc;
130616 }
130617
130618 /*
130619 ** Handle a 'special' INSERT of the form:
130620 **
130621 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
130622 **
130623 ** Argument pVal contains the result of <expr>. Currently the only 
130624 ** meaningful value to insert is the text 'optimize'.
130625 */
130626 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
130627   int rc;                         /* Return Code */
130628   const char *zVal = (const char *)sqlite3_value_text(pVal);
130629   int nVal = sqlite3_value_bytes(pVal);
130630
130631   if( !zVal ){
130632     return SQLITE_NOMEM;
130633   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
130634     rc = fts3DoOptimize(p, 0);
130635   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
130636     rc = fts3DoRebuild(p);
130637   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
130638     rc = fts3DoIntegrityCheck(p);
130639   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
130640     rc = fts3DoIncrmerge(p, &zVal[6]);
130641   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
130642     rc = fts3DoAutoincrmerge(p, &zVal[10]);
130643 #ifdef SQLITE_TEST
130644   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
130645     p->nNodeSize = atoi(&zVal[9]);
130646     rc = SQLITE_OK;
130647   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
130648     p->nMaxPendingData = atoi(&zVal[11]);
130649     rc = SQLITE_OK;
130650 #endif
130651   }else{
130652     rc = SQLITE_ERROR;
130653   }
130654
130655   return rc;
130656 }
130657
130658 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
130659 /*
130660 ** Delete all cached deferred doclists. Deferred doclists are cached
130661 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
130662 */
130663 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
130664   Fts3DeferredToken *pDef;
130665   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
130666     fts3PendingListDelete(pDef->pList);
130667     pDef->pList = 0;
130668   }
130669 }
130670
130671 /*
130672 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
130673 ** this list using sqlite3Fts3DeferToken().
130674 */
130675 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
130676   Fts3DeferredToken *pDef;
130677   Fts3DeferredToken *pNext;
130678   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
130679     pNext = pDef->pNext;
130680     fts3PendingListDelete(pDef->pList);
130681     sqlite3_free(pDef);
130682   }
130683   pCsr->pDeferred = 0;
130684 }
130685
130686 /*
130687 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
130688 ** based on the row that pCsr currently points to.
130689 **
130690 ** A deferred-doclist is like any other doclist with position information
130691 ** included, except that it only contains entries for a single row of the
130692 ** table, not for all rows.
130693 */
130694 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
130695   int rc = SQLITE_OK;             /* Return code */
130696   if( pCsr->pDeferred ){
130697     int i;                        /* Used to iterate through table columns */
130698     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
130699     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
130700   
130701     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
130702     sqlite3_tokenizer *pT = p->pTokenizer;
130703     sqlite3_tokenizer_module const *pModule = pT->pModule;
130704    
130705     assert( pCsr->isRequireSeek==0 );
130706     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
130707   
130708     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
130709       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
130710       sqlite3_tokenizer_cursor *pTC = 0;
130711   
130712       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
130713       while( rc==SQLITE_OK ){
130714         char const *zToken;       /* Buffer containing token */
130715         int nToken = 0;           /* Number of bytes in token */
130716         int iDum1 = 0, iDum2 = 0; /* Dummy variables */
130717         int iPos = 0;             /* Position of token in zText */
130718   
130719         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
130720         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
130721           Fts3PhraseToken *pPT = pDef->pToken;
130722           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
130723            && (pPT->bFirst==0 || iPos==0)
130724            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
130725            && (0==memcmp(zToken, pPT->z, pPT->n))
130726           ){
130727             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
130728           }
130729         }
130730       }
130731       if( pTC ) pModule->xClose(pTC);
130732       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
130733     }
130734   
130735     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
130736       if( pDef->pList ){
130737         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
130738       }
130739     }
130740   }
130741
130742   return rc;
130743 }
130744
130745 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
130746   Fts3DeferredToken *p, 
130747   char **ppData, 
130748   int *pnData
130749 ){
130750   char *pRet;
130751   int nSkip;
130752   sqlite3_int64 dummy;
130753
130754   *ppData = 0;
130755   *pnData = 0;
130756
130757   if( p->pList==0 ){
130758     return SQLITE_OK;
130759   }
130760
130761   pRet = (char *)sqlite3_malloc(p->pList->nData);
130762   if( !pRet ) return SQLITE_NOMEM;
130763
130764   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
130765   *pnData = p->pList->nData - nSkip;
130766   *ppData = pRet;
130767   
130768   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
130769   return SQLITE_OK;
130770 }
130771
130772 /*
130773 ** Add an entry for token pToken to the pCsr->pDeferred list.
130774 */
130775 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
130776   Fts3Cursor *pCsr,               /* Fts3 table cursor */
130777   Fts3PhraseToken *pToken,        /* Token to defer */
130778   int iCol                        /* Column that token must appear in (or -1) */
130779 ){
130780   Fts3DeferredToken *pDeferred;
130781   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
130782   if( !pDeferred ){
130783     return SQLITE_NOMEM;
130784   }
130785   memset(pDeferred, 0, sizeof(*pDeferred));
130786   pDeferred->pToken = pToken;
130787   pDeferred->pNext = pCsr->pDeferred; 
130788   pDeferred->iCol = iCol;
130789   pCsr->pDeferred = pDeferred;
130790
130791   assert( pToken->pDeferred==0 );
130792   pToken->pDeferred = pDeferred;
130793
130794   return SQLITE_OK;
130795 }
130796 #endif
130797
130798 /*
130799 ** SQLite value pRowid contains the rowid of a row that may or may not be
130800 ** present in the FTS3 table. If it is, delete it and adjust the contents
130801 ** of subsiduary data structures accordingly.
130802 */
130803 static int fts3DeleteByRowid(
130804   Fts3Table *p, 
130805   sqlite3_value *pRowid, 
130806   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
130807   u32 *aSzDel
130808 ){
130809   int rc = SQLITE_OK;             /* Return code */
130810   int bFound = 0;                 /* True if *pRowid really is in the table */
130811
130812   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
130813   if( bFound && rc==SQLITE_OK ){
130814     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
130815     rc = fts3IsEmpty(p, pRowid, &isEmpty);
130816     if( rc==SQLITE_OK ){
130817       if( isEmpty ){
130818         /* Deleting this row means the whole table is empty. In this case
130819         ** delete the contents of all three tables and throw away any
130820         ** data in the pendingTerms hash table.  */
130821         rc = fts3DeleteAll(p, 1);
130822         *pnChng = 0;
130823         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
130824       }else{
130825         *pnChng = *pnChng - 1;
130826         if( p->zContentTbl==0 ){
130827           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
130828         }
130829         if( p->bHasDocsize ){
130830           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
130831         }
130832       }
130833     }
130834   }
130835
130836   return rc;
130837 }
130838
130839 /*
130840 ** This function does the work for the xUpdate method of FTS3 virtual
130841 ** tables. The schema of the virtual table being:
130842 **
130843 **     CREATE TABLE <table name>( 
130844 **       <user columns>,
130845 **       <table name> HIDDEN, 
130846 **       docid HIDDEN, 
130847 **       <langid> HIDDEN
130848 **     );
130849 **
130850 ** 
130851 */
130852 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
130853   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
130854   int nArg,                       /* Size of argument array */
130855   sqlite3_value **apVal,          /* Array of arguments */
130856   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
130857 ){
130858   Fts3Table *p = (Fts3Table *)pVtab;
130859   int rc = SQLITE_OK;             /* Return Code */
130860   int isRemove = 0;               /* True for an UPDATE or DELETE */
130861   u32 *aSzIns = 0;                /* Sizes of inserted documents */
130862   u32 *aSzDel = 0;                /* Sizes of deleted documents */
130863   int nChng = 0;                  /* Net change in number of documents */
130864   int bInsertDone = 0;
130865
130866   assert( p->pSegments==0 );
130867   assert( 
130868       nArg==1                     /* DELETE operations */
130869    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
130870   );
130871
130872   /* Check for a "special" INSERT operation. One of the form:
130873   **
130874   **   INSERT INTO xyz(xyz) VALUES('command');
130875   */
130876   if( nArg>1 
130877    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
130878    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
130879   ){
130880     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
130881     goto update_out;
130882   }
130883
130884   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
130885     rc = SQLITE_CONSTRAINT;
130886     goto update_out;
130887   }
130888
130889   /* Allocate space to hold the change in document sizes */
130890   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
130891   if( aSzDel==0 ){
130892     rc = SQLITE_NOMEM;
130893     goto update_out;
130894   }
130895   aSzIns = &aSzDel[p->nColumn+1];
130896   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
130897
130898   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
130899   ** value, then this operation requires constraint handling.
130900   **
130901   ** If the on-conflict mode is REPLACE, this means that the existing row
130902   ** should be deleted from the database before inserting the new row. Or,
130903   ** if the on-conflict mode is other than REPLACE, then this method must
130904   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
130905   ** modify the database file.
130906   */
130907   if( nArg>1 && p->zContentTbl==0 ){
130908     /* Find the value object that holds the new rowid value. */
130909     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
130910     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
130911       pNewRowid = apVal[1];
130912     }
130913
130914     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
130915         sqlite3_value_type(apVal[0])==SQLITE_NULL
130916      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
130917     )){
130918       /* The new rowid is not NULL (in this case the rowid will be
130919       ** automatically assigned and there is no chance of a conflict), and 
130920       ** the statement is either an INSERT or an UPDATE that modifies the
130921       ** rowid column. So if the conflict mode is REPLACE, then delete any
130922       ** existing row with rowid=pNewRowid. 
130923       **
130924       ** Or, if the conflict mode is not REPLACE, insert the new record into 
130925       ** the %_content table. If we hit the duplicate rowid constraint (or any
130926       ** other error) while doing so, return immediately.
130927       **
130928       ** This branch may also run if pNewRowid contains a value that cannot
130929       ** be losslessly converted to an integer. In this case, the eventual 
130930       ** call to fts3InsertData() (either just below or further on in this
130931       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
130932       ** invoked, it will delete zero rows (since no row will have
130933       ** docid=$pNewRowid if $pNewRowid is not an integer value).
130934       */
130935       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
130936         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
130937       }else{
130938         rc = fts3InsertData(p, apVal, pRowid);
130939         bInsertDone = 1;
130940       }
130941     }
130942   }
130943   if( rc!=SQLITE_OK ){
130944     goto update_out;
130945   }
130946
130947   /* If this is a DELETE or UPDATE operation, remove the old record. */
130948   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
130949     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
130950     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
130951     isRemove = 1;
130952   }
130953   
130954   /* If this is an INSERT or UPDATE operation, insert the new record. */
130955   if( nArg>1 && rc==SQLITE_OK ){
130956     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
130957     if( bInsertDone==0 ){
130958       rc = fts3InsertData(p, apVal, pRowid);
130959       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
130960         rc = FTS_CORRUPT_VTAB;
130961       }
130962     }
130963     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
130964       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
130965     }
130966     if( rc==SQLITE_OK ){
130967       assert( p->iPrevDocid==*pRowid );
130968       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
130969     }
130970     if( p->bHasDocsize ){
130971       fts3InsertDocsize(&rc, p, aSzIns);
130972     }
130973     nChng++;
130974   }
130975
130976   if( p->bFts4 ){
130977     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
130978   }
130979
130980  update_out:
130981   sqlite3_free(aSzDel);
130982   sqlite3Fts3SegmentsClose(p);
130983   return rc;
130984 }
130985
130986 /* 
130987 ** Flush any data in the pending-terms hash table to disk. If successful,
130988 ** merge all segments in the database (including the new segment, if 
130989 ** there was any data to flush) into a single segment. 
130990 */
130991 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
130992   int rc;
130993   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
130994   if( rc==SQLITE_OK ){
130995     rc = fts3DoOptimize(p, 1);
130996     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
130997       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
130998       if( rc2!=SQLITE_OK ) rc = rc2;
130999     }else{
131000       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
131001       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131002     }
131003   }
131004   sqlite3Fts3SegmentsClose(p);
131005   return rc;
131006 }
131007
131008 #endif
131009
131010 /************** End of fts3_write.c ******************************************/
131011 /************** Begin file fts3_snippet.c ************************************/
131012 /*
131013 ** 2009 Oct 23
131014 **
131015 ** The author disclaims copyright to this source code.  In place of
131016 ** a legal notice, here is a blessing:
131017 **
131018 **    May you do good and not evil.
131019 **    May you find forgiveness for yourself and forgive others.
131020 **    May you share freely, never taking more than you give.
131021 **
131022 ******************************************************************************
131023 */
131024
131025 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131026
131027 /* #include <string.h> */
131028 /* #include <assert.h> */
131029
131030 /*
131031 ** Characters that may appear in the second argument to matchinfo().
131032 */
131033 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
131034 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
131035 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
131036 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
131037 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
131038 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
131039 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
131040
131041 /*
131042 ** The default value for the second argument to matchinfo(). 
131043 */
131044 #define FTS3_MATCHINFO_DEFAULT   "pcx"
131045
131046
131047 /*
131048 ** Used as an fts3ExprIterate() context when loading phrase doclists to
131049 ** Fts3Expr.aDoclist[]/nDoclist.
131050 */
131051 typedef struct LoadDoclistCtx LoadDoclistCtx;
131052 struct LoadDoclistCtx {
131053   Fts3Cursor *pCsr;               /* FTS3 Cursor */
131054   int nPhrase;                    /* Number of phrases seen so far */
131055   int nToken;                     /* Number of tokens seen so far */
131056 };
131057
131058 /*
131059 ** The following types are used as part of the implementation of the 
131060 ** fts3BestSnippet() routine.
131061 */
131062 typedef struct SnippetIter SnippetIter;
131063 typedef struct SnippetPhrase SnippetPhrase;
131064 typedef struct SnippetFragment SnippetFragment;
131065
131066 struct SnippetIter {
131067   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
131068   int iCol;                       /* Extract snippet from this column */
131069   int nSnippet;                   /* Requested snippet length (in tokens) */
131070   int nPhrase;                    /* Number of phrases in query */
131071   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
131072   int iCurrent;                   /* First token of current snippet */
131073 };
131074
131075 struct SnippetPhrase {
131076   int nToken;                     /* Number of tokens in phrase */
131077   char *pList;                    /* Pointer to start of phrase position list */
131078   int iHead;                      /* Next value in position list */
131079   char *pHead;                    /* Position list data following iHead */
131080   int iTail;                      /* Next value in trailing position list */
131081   char *pTail;                    /* Position list data following iTail */
131082 };
131083
131084 struct SnippetFragment {
131085   int iCol;                       /* Column snippet is extracted from */
131086   int iPos;                       /* Index of first token in snippet */
131087   u64 covered;                    /* Mask of query phrases covered */
131088   u64 hlmask;                     /* Mask of snippet terms to highlight */
131089 };
131090
131091 /*
131092 ** This type is used as an fts3ExprIterate() context object while 
131093 ** accumulating the data returned by the matchinfo() function.
131094 */
131095 typedef struct MatchInfo MatchInfo;
131096 struct MatchInfo {
131097   Fts3Cursor *pCursor;            /* FTS3 Cursor */
131098   int nCol;                       /* Number of columns in table */
131099   int nPhrase;                    /* Number of matchable phrases in query */
131100   sqlite3_int64 nDoc;             /* Number of docs in database */
131101   u32 *aMatchinfo;                /* Pre-allocated buffer */
131102 };
131103
131104
131105
131106 /*
131107 ** The snippet() and offsets() functions both return text values. An instance
131108 ** of the following structure is used to accumulate those values while the
131109 ** functions are running. See fts3StringAppend() for details.
131110 */
131111 typedef struct StrBuffer StrBuffer;
131112 struct StrBuffer {
131113   char *z;                        /* Pointer to buffer containing string */
131114   int n;                          /* Length of z in bytes (excl. nul-term) */
131115   int nAlloc;                     /* Allocated size of buffer z in bytes */
131116 };
131117
131118
131119 /*
131120 ** This function is used to help iterate through a position-list. A position
131121 ** list is a list of unique integers, sorted from smallest to largest. Each
131122 ** element of the list is represented by an FTS3 varint that takes the value
131123 ** of the difference between the current element and the previous one plus
131124 ** two. For example, to store the position-list:
131125 **
131126 **     4 9 113
131127 **
131128 ** the three varints:
131129 **
131130 **     6 7 106
131131 **
131132 ** are encoded.
131133 **
131134 ** When this function is called, *pp points to the start of an element of
131135 ** the list. *piPos contains the value of the previous entry in the list.
131136 ** After it returns, *piPos contains the value of the next element of the
131137 ** list and *pp is advanced to the following varint.
131138 */
131139 static void fts3GetDeltaPosition(char **pp, int *piPos){
131140   int iVal;
131141   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
131142   *piPos += (iVal-2);
131143 }
131144
131145 /*
131146 ** Helper function for fts3ExprIterate() (see below).
131147 */
131148 static int fts3ExprIterate2(
131149   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131150   int *piPhrase,                  /* Pointer to phrase counter */
131151   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131152   void *pCtx                      /* Second argument to pass to callback */
131153 ){
131154   int rc;                         /* Return code */
131155   int eType = pExpr->eType;       /* Type of expression node pExpr */
131156
131157   if( eType!=FTSQUERY_PHRASE ){
131158     assert( pExpr->pLeft && pExpr->pRight );
131159     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
131160     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
131161       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
131162     }
131163   }else{
131164     rc = x(pExpr, *piPhrase, pCtx);
131165     (*piPhrase)++;
131166   }
131167   return rc;
131168 }
131169
131170 /*
131171 ** Iterate through all phrase nodes in an FTS3 query, except those that
131172 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
131173 ** For each phrase node found, the supplied callback function is invoked.
131174 **
131175 ** If the callback function returns anything other than SQLITE_OK, 
131176 ** the iteration is abandoned and the error code returned immediately.
131177 ** Otherwise, SQLITE_OK is returned after a callback has been made for
131178 ** all eligible phrase nodes.
131179 */
131180 static int fts3ExprIterate(
131181   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131182   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131183   void *pCtx                      /* Second argument to pass to callback */
131184 ){
131185   int iPhrase = 0;                /* Variable used as the phrase counter */
131186   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
131187 }
131188
131189 /*
131190 ** This is an fts3ExprIterate() callback used while loading the doclists
131191 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
131192 ** fts3ExprLoadDoclists().
131193 */
131194 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131195   int rc = SQLITE_OK;
131196   Fts3Phrase *pPhrase = pExpr->pPhrase;
131197   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
131198
131199   UNUSED_PARAMETER(iPhrase);
131200
131201   p->nPhrase++;
131202   p->nToken += pPhrase->nToken;
131203
131204   return rc;
131205 }
131206
131207 /*
131208 ** Load the doclists for each phrase in the query associated with FTS3 cursor
131209 ** pCsr. 
131210 **
131211 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
131212 ** phrases in the expression (all phrases except those directly or 
131213 ** indirectly descended from the right-hand-side of a NOT operator). If 
131214 ** pnToken is not NULL, then it is set to the number of tokens in all
131215 ** matchable phrases of the expression.
131216 */
131217 static int fts3ExprLoadDoclists(
131218   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
131219   int *pnPhrase,                  /* OUT: Number of phrases in query */
131220   int *pnToken                    /* OUT: Number of tokens in query */
131221 ){
131222   int rc;                         /* Return Code */
131223   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
131224   sCtx.pCsr = pCsr;
131225   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
131226   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
131227   if( pnToken ) *pnToken = sCtx.nToken;
131228   return rc;
131229 }
131230
131231 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131232   (*(int *)ctx)++;
131233   UNUSED_PARAMETER(pExpr);
131234   UNUSED_PARAMETER(iPhrase);
131235   return SQLITE_OK;
131236 }
131237 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
131238   int nPhrase = 0;
131239   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
131240   return nPhrase;
131241 }
131242
131243 /*
131244 ** Advance the position list iterator specified by the first two 
131245 ** arguments so that it points to the first element with a value greater
131246 ** than or equal to parameter iNext.
131247 */
131248 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
131249   char *pIter = *ppIter;
131250   if( pIter ){
131251     int iIter = *piIter;
131252
131253     while( iIter<iNext ){
131254       if( 0==(*pIter & 0xFE) ){
131255         iIter = -1;
131256         pIter = 0;
131257         break;
131258       }
131259       fts3GetDeltaPosition(&pIter, &iIter);
131260     }
131261
131262     *piIter = iIter;
131263     *ppIter = pIter;
131264   }
131265 }
131266
131267 /*
131268 ** Advance the snippet iterator to the next candidate snippet.
131269 */
131270 static int fts3SnippetNextCandidate(SnippetIter *pIter){
131271   int i;                          /* Loop counter */
131272
131273   if( pIter->iCurrent<0 ){
131274     /* The SnippetIter object has just been initialized. The first snippet
131275     ** candidate always starts at offset 0 (even if this candidate has a
131276     ** score of 0.0).
131277     */
131278     pIter->iCurrent = 0;
131279
131280     /* Advance the 'head' iterator of each phrase to the first offset that
131281     ** is greater than or equal to (iNext+nSnippet).
131282     */
131283     for(i=0; i<pIter->nPhrase; i++){
131284       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131285       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
131286     }
131287   }else{
131288     int iStart;
131289     int iEnd = 0x7FFFFFFF;
131290
131291     for(i=0; i<pIter->nPhrase; i++){
131292       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131293       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
131294         iEnd = pPhrase->iHead;
131295       }
131296     }
131297     if( iEnd==0x7FFFFFFF ){
131298       return 1;
131299     }
131300
131301     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
131302     for(i=0; i<pIter->nPhrase; i++){
131303       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131304       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
131305       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
131306     }
131307   }
131308
131309   return 0;
131310 }
131311
131312 /*
131313 ** Retrieve information about the current candidate snippet of snippet 
131314 ** iterator pIter.
131315 */
131316 static void fts3SnippetDetails(
131317   SnippetIter *pIter,             /* Snippet iterator */
131318   u64 mCovered,                   /* Bitmask of phrases already covered */
131319   int *piToken,                   /* OUT: First token of proposed snippet */
131320   int *piScore,                   /* OUT: "Score" for this snippet */
131321   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
131322   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
131323 ){
131324   int iStart = pIter->iCurrent;   /* First token of snippet */
131325   int iScore = 0;                 /* Score of this snippet */
131326   int i;                          /* Loop counter */
131327   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
131328   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
131329
131330   for(i=0; i<pIter->nPhrase; i++){
131331     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131332     if( pPhrase->pTail ){
131333       char *pCsr = pPhrase->pTail;
131334       int iCsr = pPhrase->iTail;
131335
131336       while( iCsr<(iStart+pIter->nSnippet) ){
131337         int j;
131338         u64 mPhrase = (u64)1 << i;
131339         u64 mPos = (u64)1 << (iCsr - iStart);
131340         assert( iCsr>=iStart );
131341         if( (mCover|mCovered)&mPhrase ){
131342           iScore++;
131343         }else{
131344           iScore += 1000;
131345         }
131346         mCover |= mPhrase;
131347
131348         for(j=0; j<pPhrase->nToken; j++){
131349           mHighlight |= (mPos>>j);
131350         }
131351
131352         if( 0==(*pCsr & 0x0FE) ) break;
131353         fts3GetDeltaPosition(&pCsr, &iCsr);
131354       }
131355     }
131356   }
131357
131358   /* Set the output variables before returning. */
131359   *piToken = iStart;
131360   *piScore = iScore;
131361   *pmCover = mCover;
131362   *pmHighlight = mHighlight;
131363 }
131364
131365 /*
131366 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
131367 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
131368 */
131369 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
131370   SnippetIter *p = (SnippetIter *)ctx;
131371   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
131372   char *pCsr;
131373   int rc;
131374
131375   pPhrase->nToken = pExpr->pPhrase->nToken;
131376   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
131377   assert( rc==SQLITE_OK || pCsr==0 );
131378   if( pCsr ){
131379     int iFirst = 0;
131380     pPhrase->pList = pCsr;
131381     fts3GetDeltaPosition(&pCsr, &iFirst);
131382     assert( iFirst>=0 );
131383     pPhrase->pHead = pCsr;
131384     pPhrase->pTail = pCsr;
131385     pPhrase->iHead = iFirst;
131386     pPhrase->iTail = iFirst;
131387   }else{
131388     assert( rc!=SQLITE_OK || (
131389        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
131390     ));
131391   }
131392
131393   return rc;
131394 }
131395
131396 /*
131397 ** Select the fragment of text consisting of nFragment contiguous tokens 
131398 ** from column iCol that represent the "best" snippet. The best snippet
131399 ** is the snippet with the highest score, where scores are calculated
131400 ** by adding:
131401 **
131402 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
131403 **
131404 **   (b) +1000 points for the first occurence of each matchable phrase in 
131405 **       the snippet for which the corresponding mCovered bit is not set.
131406 **
131407 ** The selected snippet parameters are stored in structure *pFragment before
131408 ** returning. The score of the selected snippet is stored in *piScore
131409 ** before returning.
131410 */
131411 static int fts3BestSnippet(
131412   int nSnippet,                   /* Desired snippet length */
131413   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
131414   int iCol,                       /* Index of column to create snippet from */
131415   u64 mCovered,                   /* Mask of phrases already covered */
131416   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
131417   SnippetFragment *pFragment,     /* OUT: Best snippet found */
131418   int *piScore                    /* OUT: Score of snippet pFragment */
131419 ){
131420   int rc;                         /* Return Code */
131421   int nList;                      /* Number of phrases in expression */
131422   SnippetIter sIter;              /* Iterates through snippet candidates */
131423   int nByte;                      /* Number of bytes of space to allocate */
131424   int iBestScore = -1;            /* Best snippet score found so far */
131425   int i;                          /* Loop counter */
131426
131427   memset(&sIter, 0, sizeof(sIter));
131428
131429   /* Iterate through the phrases in the expression to count them. The same
131430   ** callback makes sure the doclists are loaded for each phrase.
131431   */
131432   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
131433   if( rc!=SQLITE_OK ){
131434     return rc;
131435   }
131436
131437   /* Now that it is known how many phrases there are, allocate and zero
131438   ** the required space using malloc().
131439   */
131440   nByte = sizeof(SnippetPhrase) * nList;
131441   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
131442   if( !sIter.aPhrase ){
131443     return SQLITE_NOMEM;
131444   }
131445   memset(sIter.aPhrase, 0, nByte);
131446
131447   /* Initialize the contents of the SnippetIter object. Then iterate through
131448   ** the set of phrases in the expression to populate the aPhrase[] array.
131449   */
131450   sIter.pCsr = pCsr;
131451   sIter.iCol = iCol;
131452   sIter.nSnippet = nSnippet;
131453   sIter.nPhrase = nList;
131454   sIter.iCurrent = -1;
131455   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
131456
131457   /* Set the *pmSeen output variable. */
131458   for(i=0; i<nList; i++){
131459     if( sIter.aPhrase[i].pHead ){
131460       *pmSeen |= (u64)1 << i;
131461     }
131462   }
131463
131464   /* Loop through all candidate snippets. Store the best snippet in 
131465   ** *pFragment. Store its associated 'score' in iBestScore.
131466   */
131467   pFragment->iCol = iCol;
131468   while( !fts3SnippetNextCandidate(&sIter) ){
131469     int iPos;
131470     int iScore;
131471     u64 mCover;
131472     u64 mHighlight;
131473     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
131474     assert( iScore>=0 );
131475     if( iScore>iBestScore ){
131476       pFragment->iPos = iPos;
131477       pFragment->hlmask = mHighlight;
131478       pFragment->covered = mCover;
131479       iBestScore = iScore;
131480     }
131481   }
131482
131483   sqlite3_free(sIter.aPhrase);
131484   *piScore = iBestScore;
131485   return SQLITE_OK;
131486 }
131487
131488
131489 /*
131490 ** Append a string to the string-buffer passed as the first argument.
131491 **
131492 ** If nAppend is negative, then the length of the string zAppend is
131493 ** determined using strlen().
131494 */
131495 static int fts3StringAppend(
131496   StrBuffer *pStr,                /* Buffer to append to */
131497   const char *zAppend,            /* Pointer to data to append to buffer */
131498   int nAppend                     /* Size of zAppend in bytes (or -1) */
131499 ){
131500   if( nAppend<0 ){
131501     nAppend = (int)strlen(zAppend);
131502   }
131503
131504   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
131505   ** to grow the buffer until so that it is big enough to accomadate the
131506   ** appended data.
131507   */
131508   if( pStr->n+nAppend+1>=pStr->nAlloc ){
131509     int nAlloc = pStr->nAlloc+nAppend+100;
131510     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
131511     if( !zNew ){
131512       return SQLITE_NOMEM;
131513     }
131514     pStr->z = zNew;
131515     pStr->nAlloc = nAlloc;
131516   }
131517
131518   /* Append the data to the string buffer. */
131519   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
131520   pStr->n += nAppend;
131521   pStr->z[pStr->n] = '\0';
131522
131523   return SQLITE_OK;
131524 }
131525
131526 /*
131527 ** The fts3BestSnippet() function often selects snippets that end with a
131528 ** query term. That is, the final term of the snippet is always a term
131529 ** that requires highlighting. For example, if 'X' is a highlighted term
131530 ** and '.' is a non-highlighted term, BestSnippet() may select:
131531 **
131532 **     ........X.....X
131533 **
131534 ** This function "shifts" the beginning of the snippet forward in the 
131535 ** document so that there are approximately the same number of 
131536 ** non-highlighted terms to the right of the final highlighted term as there
131537 ** are to the left of the first highlighted term. For example, to this:
131538 **
131539 **     ....X.....X....
131540 **
131541 ** This is done as part of extracting the snippet text, not when selecting
131542 ** the snippet. Snippet selection is done based on doclists only, so there
131543 ** is no way for fts3BestSnippet() to know whether or not the document 
131544 ** actually contains terms that follow the final highlighted term. 
131545 */
131546 static int fts3SnippetShift(
131547   Fts3Table *pTab,                /* FTS3 table snippet comes from */
131548   int iLangid,                    /* Language id to use in tokenizing */
131549   int nSnippet,                   /* Number of tokens desired for snippet */
131550   const char *zDoc,               /* Document text to extract snippet from */
131551   int nDoc,                       /* Size of buffer zDoc in bytes */
131552   int *piPos,                     /* IN/OUT: First token of snippet */
131553   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
131554 ){
131555   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
131556
131557   if( hlmask ){
131558     int nLeft;                    /* Tokens to the left of first highlight */
131559     int nRight;                   /* Tokens to the right of last highlight */
131560     int nDesired;                 /* Ideal number of tokens to shift forward */
131561
131562     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
131563     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
131564     nDesired = (nLeft-nRight)/2;
131565
131566     /* Ideally, the start of the snippet should be pushed forward in the
131567     ** document nDesired tokens. This block checks if there are actually
131568     ** nDesired tokens to the right of the snippet. If so, *piPos and
131569     ** *pHlMask are updated to shift the snippet nDesired tokens to the
131570     ** right. Otherwise, the snippet is shifted by the number of tokens
131571     ** available.
131572     */
131573     if( nDesired>0 ){
131574       int nShift;                 /* Number of tokens to shift snippet by */
131575       int iCurrent = 0;           /* Token counter */
131576       int rc;                     /* Return Code */
131577       sqlite3_tokenizer_module *pMod;
131578       sqlite3_tokenizer_cursor *pC;
131579       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
131580
131581       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
131582       ** or more tokens in zDoc/nDoc.
131583       */
131584       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
131585       if( rc!=SQLITE_OK ){
131586         return rc;
131587       }
131588       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
131589         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
131590         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
131591       }
131592       pMod->xClose(pC);
131593       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
131594
131595       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
131596       assert( nShift<=nDesired );
131597       if( nShift>0 ){
131598         *piPos += nShift;
131599         *pHlmask = hlmask >> nShift;
131600       }
131601     }
131602   }
131603   return SQLITE_OK;
131604 }
131605
131606 /*
131607 ** Extract the snippet text for fragment pFragment from cursor pCsr and
131608 ** append it to string buffer pOut.
131609 */
131610 static int fts3SnippetText(
131611   Fts3Cursor *pCsr,               /* FTS3 Cursor */
131612   SnippetFragment *pFragment,     /* Snippet to extract */
131613   int iFragment,                  /* Fragment number */
131614   int isLast,                     /* True for final fragment in snippet */
131615   int nSnippet,                   /* Number of tokens in extracted snippet */
131616   const char *zOpen,              /* String inserted before highlighted term */
131617   const char *zClose,             /* String inserted after highlighted term */
131618   const char *zEllipsis,          /* String inserted between snippets */
131619   StrBuffer *pOut                 /* Write output here */
131620 ){
131621   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131622   int rc;                         /* Return code */
131623   const char *zDoc;               /* Document text to extract snippet from */
131624   int nDoc;                       /* Size of zDoc in bytes */
131625   int iCurrent = 0;               /* Current token number of document */
131626   int iEnd = 0;                   /* Byte offset of end of current token */
131627   int isShiftDone = 0;            /* True after snippet is shifted */
131628   int iPos = pFragment->iPos;     /* First token of snippet */
131629   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
131630   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
131631   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
131632   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
131633   
131634   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
131635   if( zDoc==0 ){
131636     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
131637       return SQLITE_NOMEM;
131638     }
131639     return SQLITE_OK;
131640   }
131641   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
131642
131643   /* Open a token cursor on the document. */
131644   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
131645   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
131646   if( rc!=SQLITE_OK ){
131647     return rc;
131648   }
131649
131650   while( rc==SQLITE_OK ){
131651     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
131652     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
131653     int iBegin = 0;               /* Offset in zDoc of start of token */
131654     int iFin = 0;                 /* Offset in zDoc of end of token */
131655     int isHighlight = 0;          /* True for highlighted terms */
131656
131657     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
131658     ** in the FTS code the variable that the third argument to xNext points to
131659     ** is initialized to zero before the first (*but not necessarily
131660     ** subsequent*) call to xNext(). This is done for a particular application
131661     ** that needs to know whether or not the tokenizer is being used for
131662     ** snippet generation or for some other purpose.
131663     **
131664     ** Extreme care is required when writing code to depend on this
131665     ** initialization. It is not a documented part of the tokenizer interface.
131666     ** If a tokenizer is used directly by any code outside of FTS, this
131667     ** convention might not be respected.  */
131668     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
131669     if( rc!=SQLITE_OK ){
131670       if( rc==SQLITE_DONE ){
131671         /* Special case - the last token of the snippet is also the last token
131672         ** of the column. Append any punctuation that occurred between the end
131673         ** of the previous token and the end of the document to the output. 
131674         ** Then break out of the loop. */
131675         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
131676       }
131677       break;
131678     }
131679     if( iCurrent<iPos ){ continue; }
131680
131681     if( !isShiftDone ){
131682       int n = nDoc - iBegin;
131683       rc = fts3SnippetShift(
131684           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
131685       );
131686       isShiftDone = 1;
131687
131688       /* Now that the shift has been done, check if the initial "..." are
131689       ** required. They are required if (a) this is not the first fragment,
131690       ** or (b) this fragment does not begin at position 0 of its column. 
131691       */
131692       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
131693         rc = fts3StringAppend(pOut, zEllipsis, -1);
131694       }
131695       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
131696     }
131697
131698     if( iCurrent>=(iPos+nSnippet) ){
131699       if( isLast ){
131700         rc = fts3StringAppend(pOut, zEllipsis, -1);
131701       }
131702       break;
131703     }
131704
131705     /* Set isHighlight to true if this term should be highlighted. */
131706     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
131707
131708     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
131709     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
131710     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
131711     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
131712
131713     iEnd = iFin;
131714   }
131715
131716   pMod->xClose(pC);
131717   return rc;
131718 }
131719
131720
131721 /*
131722 ** This function is used to count the entries in a column-list (a 
131723 ** delta-encoded list of term offsets within a single column of a single 
131724 ** row). When this function is called, *ppCollist should point to the
131725 ** beginning of the first varint in the column-list (the varint that
131726 ** contains the position of the first matching term in the column data).
131727 ** Before returning, *ppCollist is set to point to the first byte after
131728 ** the last varint in the column-list (either the 0x00 signifying the end
131729 ** of the position-list, or the 0x01 that precedes the column number of
131730 ** the next column in the position-list).
131731 **
131732 ** The number of elements in the column-list is returned.
131733 */
131734 static int fts3ColumnlistCount(char **ppCollist){
131735   char *pEnd = *ppCollist;
131736   char c = 0;
131737   int nEntry = 0;
131738
131739   /* A column-list is terminated by either a 0x01 or 0x00. */
131740   while( 0xFE & (*pEnd | c) ){
131741     c = *pEnd++ & 0x80;
131742     if( !c ) nEntry++;
131743   }
131744
131745   *ppCollist = pEnd;
131746   return nEntry;
131747 }
131748
131749 /*
131750 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
131751 ** for a single query. 
131752 **
131753 ** fts3ExprIterate() callback to load the 'global' elements of a
131754 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
131755 ** of the matchinfo array that are constant for all rows returned by the 
131756 ** current query.
131757 **
131758 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
131759 ** function populates Matchinfo.aMatchinfo[] as follows:
131760 **
131761 **   for(iCol=0; iCol<nCol; iCol++){
131762 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
131763 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
131764 **   }
131765 **
131766 ** where X is the number of matches for phrase iPhrase is column iCol of all
131767 ** rows of the table. Y is the number of rows for which column iCol contains
131768 ** at least one instance of phrase iPhrase.
131769 **
131770 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
131771 ** Y values are set to nDoc, where nDoc is the number of documents in the 
131772 ** file system. This is done because the full-text index doclist is required
131773 ** to calculate these values properly, and the full-text index doclist is
131774 ** not available for deferred tokens.
131775 */
131776 static int fts3ExprGlobalHitsCb(
131777   Fts3Expr *pExpr,                /* Phrase expression node */
131778   int iPhrase,                    /* Phrase number (numbered from zero) */
131779   void *pCtx                      /* Pointer to MatchInfo structure */
131780 ){
131781   MatchInfo *p = (MatchInfo *)pCtx;
131782   return sqlite3Fts3EvalPhraseStats(
131783       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
131784   );
131785 }
131786
131787 /*
131788 ** fts3ExprIterate() callback used to collect the "local" part of the
131789 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
131790 ** array that are different for each row returned by the query.
131791 */
131792 static int fts3ExprLocalHitsCb(
131793   Fts3Expr *pExpr,                /* Phrase expression node */
131794   int iPhrase,                    /* Phrase number */
131795   void *pCtx                      /* Pointer to MatchInfo structure */
131796 ){
131797   int rc = SQLITE_OK;
131798   MatchInfo *p = (MatchInfo *)pCtx;
131799   int iStart = iPhrase * p->nCol * 3;
131800   int i;
131801
131802   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
131803     char *pCsr;
131804     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
131805     if( pCsr ){
131806       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
131807     }else{
131808       p->aMatchinfo[iStart+i*3] = 0;
131809     }
131810   }
131811
131812   return rc;
131813 }
131814
131815 static int fts3MatchinfoCheck(
131816   Fts3Table *pTab, 
131817   char cArg,
131818   char **pzErr
131819 ){
131820   if( (cArg==FTS3_MATCHINFO_NPHRASE)
131821    || (cArg==FTS3_MATCHINFO_NCOL)
131822    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
131823    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
131824    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
131825    || (cArg==FTS3_MATCHINFO_LCS)
131826    || (cArg==FTS3_MATCHINFO_HITS)
131827   ){
131828     return SQLITE_OK;
131829   }
131830   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
131831   return SQLITE_ERROR;
131832 }
131833
131834 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
131835   int nVal;                       /* Number of integers output by cArg */
131836
131837   switch( cArg ){
131838     case FTS3_MATCHINFO_NDOC:
131839     case FTS3_MATCHINFO_NPHRASE: 
131840     case FTS3_MATCHINFO_NCOL: 
131841       nVal = 1;
131842       break;
131843
131844     case FTS3_MATCHINFO_AVGLENGTH:
131845     case FTS3_MATCHINFO_LENGTH:
131846     case FTS3_MATCHINFO_LCS:
131847       nVal = pInfo->nCol;
131848       break;
131849
131850     default:
131851       assert( cArg==FTS3_MATCHINFO_HITS );
131852       nVal = pInfo->nCol * pInfo->nPhrase * 3;
131853       break;
131854   }
131855
131856   return nVal;
131857 }
131858
131859 static int fts3MatchinfoSelectDoctotal(
131860   Fts3Table *pTab,
131861   sqlite3_stmt **ppStmt,
131862   sqlite3_int64 *pnDoc,
131863   const char **paLen
131864 ){
131865   sqlite3_stmt *pStmt;
131866   const char *a;
131867   sqlite3_int64 nDoc;
131868
131869   if( !*ppStmt ){
131870     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
131871     if( rc!=SQLITE_OK ) return rc;
131872   }
131873   pStmt = *ppStmt;
131874   assert( sqlite3_data_count(pStmt)==1 );
131875
131876   a = sqlite3_column_blob(pStmt, 0);
131877   a += sqlite3Fts3GetVarint(a, &nDoc);
131878   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
131879   *pnDoc = (u32)nDoc;
131880
131881   if( paLen ) *paLen = a;
131882   return SQLITE_OK;
131883 }
131884
131885 /*
131886 ** An instance of the following structure is used to store state while 
131887 ** iterating through a multi-column position-list corresponding to the
131888 ** hits for a single phrase on a single row in order to calculate the
131889 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
131890 */
131891 typedef struct LcsIterator LcsIterator;
131892 struct LcsIterator {
131893   Fts3Expr *pExpr;                /* Pointer to phrase expression */
131894   int iPosOffset;                 /* Tokens count up to end of this phrase */
131895   char *pRead;                    /* Cursor used to iterate through aDoclist */
131896   int iPos;                       /* Current position */
131897 };
131898
131899 /* 
131900 ** If LcsIterator.iCol is set to the following value, the iterator has
131901 ** finished iterating through all offsets for all columns.
131902 */
131903 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
131904
131905 static int fts3MatchinfoLcsCb(
131906   Fts3Expr *pExpr,                /* Phrase expression node */
131907   int iPhrase,                    /* Phrase number (numbered from zero) */
131908   void *pCtx                      /* Pointer to MatchInfo structure */
131909 ){
131910   LcsIterator *aIter = (LcsIterator *)pCtx;
131911   aIter[iPhrase].pExpr = pExpr;
131912   return SQLITE_OK;
131913 }
131914
131915 /*
131916 ** Advance the iterator passed as an argument to the next position. Return
131917 ** 1 if the iterator is at EOF or if it now points to the start of the
131918 ** position list for the next column.
131919 */
131920 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
131921   char *pRead = pIter->pRead;
131922   sqlite3_int64 iRead;
131923   int rc = 0;
131924
131925   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
131926   if( iRead==0 || iRead==1 ){
131927     pRead = 0;
131928     rc = 1;
131929   }else{
131930     pIter->iPos += (int)(iRead-2);
131931   }
131932
131933   pIter->pRead = pRead;
131934   return rc;
131935 }
131936   
131937 /*
131938 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
131939 **
131940 ** If the call is successful, the longest-common-substring lengths for each
131941 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
131942 ** array before returning. SQLITE_OK is returned in this case.
131943 **
131944 ** Otherwise, if an error occurs, an SQLite error code is returned and the
131945 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
131946 ** undefined.
131947 */
131948 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
131949   LcsIterator *aIter;
131950   int i;
131951   int iCol;
131952   int nToken = 0;
131953
131954   /* Allocate and populate the array of LcsIterator objects. The array
131955   ** contains one element for each matchable phrase in the query.
131956   **/
131957   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
131958   if( !aIter ) return SQLITE_NOMEM;
131959   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
131960   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
131961
131962   for(i=0; i<pInfo->nPhrase; i++){
131963     LcsIterator *pIter = &aIter[i];
131964     nToken -= pIter->pExpr->pPhrase->nToken;
131965     pIter->iPosOffset = nToken;
131966   }
131967
131968   for(iCol=0; iCol<pInfo->nCol; iCol++){
131969     int nLcs = 0;                 /* LCS value for this column */
131970     int nLive = 0;                /* Number of iterators in aIter not at EOF */
131971
131972     for(i=0; i<pInfo->nPhrase; i++){
131973       int rc;
131974       LcsIterator *pIt = &aIter[i];
131975       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
131976       if( rc!=SQLITE_OK ) return rc;
131977       if( pIt->pRead ){
131978         pIt->iPos = pIt->iPosOffset;
131979         fts3LcsIteratorAdvance(&aIter[i]);
131980         nLive++;
131981       }
131982     }
131983
131984     while( nLive>0 ){
131985       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
131986       int nThisLcs = 0;           /* LCS for the current iterator positions */
131987
131988       for(i=0; i<pInfo->nPhrase; i++){
131989         LcsIterator *pIter = &aIter[i];
131990         if( pIter->pRead==0 ){
131991           /* This iterator is already at EOF for this column. */
131992           nThisLcs = 0;
131993         }else{
131994           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
131995             pAdv = pIter;
131996           }
131997           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
131998             nThisLcs++;
131999           }else{
132000             nThisLcs = 1;
132001           }
132002           if( nThisLcs>nLcs ) nLcs = nThisLcs;
132003         }
132004       }
132005       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
132006     }
132007
132008     pInfo->aMatchinfo[iCol] = nLcs;
132009   }
132010
132011   sqlite3_free(aIter);
132012   return SQLITE_OK;
132013 }
132014
132015 /*
132016 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
132017 ** be returned by the matchinfo() function. Argument zArg contains the 
132018 ** format string passed as the second argument to matchinfo (or the
132019 ** default value "pcx" if no second argument was specified). The format
132020 ** string has already been validated and the pInfo->aMatchinfo[] array
132021 ** is guaranteed to be large enough for the output.
132022 **
132023 ** If bGlobal is true, then populate all fields of the matchinfo() output.
132024 ** If it is false, then assume that those fields that do not change between
132025 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
132026 ** have already been populated.
132027 **
132028 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
132029 ** occurs. If a value other than SQLITE_OK is returned, the state the
132030 ** pInfo->aMatchinfo[] buffer is left in is undefined.
132031 */
132032 static int fts3MatchinfoValues(
132033   Fts3Cursor *pCsr,               /* FTS3 cursor object */
132034   int bGlobal,                    /* True to grab the global stats */
132035   MatchInfo *pInfo,               /* Matchinfo context object */
132036   const char *zArg                /* Matchinfo format string */
132037 ){
132038   int rc = SQLITE_OK;
132039   int i;
132040   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132041   sqlite3_stmt *pSelect = 0;
132042
132043   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
132044
132045     switch( zArg[i] ){
132046       case FTS3_MATCHINFO_NPHRASE:
132047         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
132048         break;
132049
132050       case FTS3_MATCHINFO_NCOL:
132051         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
132052         break;
132053         
132054       case FTS3_MATCHINFO_NDOC:
132055         if( bGlobal ){
132056           sqlite3_int64 nDoc = 0;
132057           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
132058           pInfo->aMatchinfo[0] = (u32)nDoc;
132059         }
132060         break;
132061
132062       case FTS3_MATCHINFO_AVGLENGTH: 
132063         if( bGlobal ){
132064           sqlite3_int64 nDoc;     /* Number of rows in table */
132065           const char *a;          /* Aggregate column length array */
132066
132067           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
132068           if( rc==SQLITE_OK ){
132069             int iCol;
132070             for(iCol=0; iCol<pInfo->nCol; iCol++){
132071               u32 iVal;
132072               sqlite3_int64 nToken;
132073               a += sqlite3Fts3GetVarint(a, &nToken);
132074               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
132075               pInfo->aMatchinfo[iCol] = iVal;
132076             }
132077           }
132078         }
132079         break;
132080
132081       case FTS3_MATCHINFO_LENGTH: {
132082         sqlite3_stmt *pSelectDocsize = 0;
132083         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
132084         if( rc==SQLITE_OK ){
132085           int iCol;
132086           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
132087           for(iCol=0; iCol<pInfo->nCol; iCol++){
132088             sqlite3_int64 nToken;
132089             a += sqlite3Fts3GetVarint(a, &nToken);
132090             pInfo->aMatchinfo[iCol] = (u32)nToken;
132091           }
132092         }
132093         sqlite3_reset(pSelectDocsize);
132094         break;
132095       }
132096
132097       case FTS3_MATCHINFO_LCS:
132098         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132099         if( rc==SQLITE_OK ){
132100           rc = fts3MatchinfoLcs(pCsr, pInfo);
132101         }
132102         break;
132103
132104       default: {
132105         Fts3Expr *pExpr;
132106         assert( zArg[i]==FTS3_MATCHINFO_HITS );
132107         pExpr = pCsr->pExpr;
132108         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132109         if( rc!=SQLITE_OK ) break;
132110         if( bGlobal ){
132111           if( pCsr->pDeferred ){
132112             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
132113             if( rc!=SQLITE_OK ) break;
132114           }
132115           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
132116           if( rc!=SQLITE_OK ) break;
132117         }
132118         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
132119         break;
132120       }
132121     }
132122
132123     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
132124   }
132125
132126   sqlite3_reset(pSelect);
132127   return rc;
132128 }
132129
132130
132131 /*
132132 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
132133 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
132134 */
132135 static int fts3GetMatchinfo(
132136   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
132137   const char *zArg                /* Second argument to matchinfo() function */
132138 ){
132139   MatchInfo sInfo;
132140   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132141   int rc = SQLITE_OK;
132142   int bGlobal = 0;                /* Collect 'global' stats as well as local */
132143
132144   memset(&sInfo, 0, sizeof(MatchInfo));
132145   sInfo.pCursor = pCsr;
132146   sInfo.nCol = pTab->nColumn;
132147
132148   /* If there is cached matchinfo() data, but the format string for the 
132149   ** cache does not match the format string for this request, discard 
132150   ** the cached data. */
132151   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
132152     assert( pCsr->aMatchinfo );
132153     sqlite3_free(pCsr->aMatchinfo);
132154     pCsr->zMatchinfo = 0;
132155     pCsr->aMatchinfo = 0;
132156   }
132157
132158   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
132159   ** matchinfo function has been called for this query. In this case 
132160   ** allocate the array used to accumulate the matchinfo data and
132161   ** initialize those elements that are constant for every row.
132162   */
132163   if( pCsr->aMatchinfo==0 ){
132164     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
132165     int nArg;                     /* Bytes in zArg */
132166     int i;                        /* Used to iterate through zArg */
132167
132168     /* Determine the number of phrases in the query */
132169     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
132170     sInfo.nPhrase = pCsr->nPhrase;
132171
132172     /* Determine the number of integers in the buffer returned by this call. */
132173     for(i=0; zArg[i]; i++){
132174       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
132175     }
132176
132177     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
132178     nArg = (int)strlen(zArg);
132179     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
132180     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
132181
132182     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
132183     pCsr->nMatchinfo = nMatchinfo;
132184     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
132185     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
132186     pCsr->isMatchinfoNeeded = 1;
132187     bGlobal = 1;
132188   }
132189
132190   sInfo.aMatchinfo = pCsr->aMatchinfo;
132191   sInfo.nPhrase = pCsr->nPhrase;
132192   if( pCsr->isMatchinfoNeeded ){
132193     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
132194     pCsr->isMatchinfoNeeded = 0;
132195   }
132196
132197   return rc;
132198 }
132199
132200 /*
132201 ** Implementation of snippet() function.
132202 */
132203 SQLITE_PRIVATE void sqlite3Fts3Snippet(
132204   sqlite3_context *pCtx,          /* SQLite function call context */
132205   Fts3Cursor *pCsr,               /* Cursor object */
132206   const char *zStart,             /* Snippet start text - "<b>" */
132207   const char *zEnd,               /* Snippet end text - "</b>" */
132208   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
132209   int iCol,                       /* Extract snippet from this column */
132210   int nToken                      /* Approximate number of tokens in snippet */
132211 ){
132212   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132213   int rc = SQLITE_OK;
132214   int i;
132215   StrBuffer res = {0, 0, 0};
132216
132217   /* The returned text includes up to four fragments of text extracted from
132218   ** the data in the current row. The first iteration of the for(...) loop
132219   ** below attempts to locate a single fragment of text nToken tokens in 
132220   ** size that contains at least one instance of all phrases in the query
132221   ** expression that appear in the current row. If such a fragment of text
132222   ** cannot be found, the second iteration of the loop attempts to locate
132223   ** a pair of fragments, and so on.
132224   */
132225   int nSnippet = 0;               /* Number of fragments in this snippet */
132226   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
132227   int nFToken = -1;               /* Number of tokens in each fragment */
132228
132229   if( !pCsr->pExpr ){
132230     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
132231     return;
132232   }
132233
132234   for(nSnippet=1; 1; nSnippet++){
132235
132236     int iSnip;                    /* Loop counter 0..nSnippet-1 */
132237     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
132238     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
132239
132240     if( nToken>=0 ){
132241       nFToken = (nToken+nSnippet-1) / nSnippet;
132242     }else{
132243       nFToken = -1 * nToken;
132244     }
132245
132246     for(iSnip=0; iSnip<nSnippet; iSnip++){
132247       int iBestScore = -1;        /* Best score of columns checked so far */
132248       int iRead;                  /* Used to iterate through columns */
132249       SnippetFragment *pFragment = &aSnippet[iSnip];
132250
132251       memset(pFragment, 0, sizeof(*pFragment));
132252
132253       /* Loop through all columns of the table being considered for snippets.
132254       ** If the iCol argument to this function was negative, this means all
132255       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
132256       */
132257       for(iRead=0; iRead<pTab->nColumn; iRead++){
132258         SnippetFragment sF = {0, 0, 0, 0};
132259         int iS;
132260         if( iCol>=0 && iRead!=iCol ) continue;
132261
132262         /* Find the best snippet of nFToken tokens in column iRead. */
132263         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
132264         if( rc!=SQLITE_OK ){
132265           goto snippet_out;
132266         }
132267         if( iS>iBestScore ){
132268           *pFragment = sF;
132269           iBestScore = iS;
132270         }
132271       }
132272
132273       mCovered |= pFragment->covered;
132274     }
132275
132276     /* If all query phrases seen by fts3BestSnippet() are present in at least
132277     ** one of the nSnippet snippet fragments, break out of the loop.
132278     */
132279     assert( (mCovered&mSeen)==mCovered );
132280     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
132281   }
132282
132283   assert( nFToken>0 );
132284
132285   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
132286     rc = fts3SnippetText(pCsr, &aSnippet[i], 
132287         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
132288     );
132289   }
132290
132291  snippet_out:
132292   sqlite3Fts3SegmentsClose(pTab);
132293   if( rc!=SQLITE_OK ){
132294     sqlite3_result_error_code(pCtx, rc);
132295     sqlite3_free(res.z);
132296   }else{
132297     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
132298   }
132299 }
132300
132301
132302 typedef struct TermOffset TermOffset;
132303 typedef struct TermOffsetCtx TermOffsetCtx;
132304
132305 struct TermOffset {
132306   char *pList;                    /* Position-list */
132307   int iPos;                       /* Position just read from pList */
132308   int iOff;                       /* Offset of this term from read positions */
132309 };
132310
132311 struct TermOffsetCtx {
132312   Fts3Cursor *pCsr;
132313   int iCol;                       /* Column of table to populate aTerm for */
132314   int iTerm;
132315   sqlite3_int64 iDocid;
132316   TermOffset *aTerm;
132317 };
132318
132319 /*
132320 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
132321 */
132322 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
132323   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
132324   int nTerm;                      /* Number of tokens in phrase */
132325   int iTerm;                      /* For looping through nTerm phrase terms */
132326   char *pList;                    /* Pointer to position list for phrase */
132327   int iPos = 0;                   /* First position in position-list */
132328   int rc;
132329
132330   UNUSED_PARAMETER(iPhrase);
132331   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
132332   nTerm = pExpr->pPhrase->nToken;
132333   if( pList ){
132334     fts3GetDeltaPosition(&pList, &iPos);
132335     assert( iPos>=0 );
132336   }
132337
132338   for(iTerm=0; iTerm<nTerm; iTerm++){
132339     TermOffset *pT = &p->aTerm[p->iTerm++];
132340     pT->iOff = nTerm-iTerm-1;
132341     pT->pList = pList;
132342     pT->iPos = iPos;
132343   }
132344
132345   return rc;
132346 }
132347
132348 /*
132349 ** Implementation of offsets() function.
132350 */
132351 SQLITE_PRIVATE void sqlite3Fts3Offsets(
132352   sqlite3_context *pCtx,          /* SQLite function call context */
132353   Fts3Cursor *pCsr                /* Cursor object */
132354 ){
132355   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132356   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
132357   int rc;                         /* Return Code */
132358   int nToken;                     /* Number of tokens in query */
132359   int iCol;                       /* Column currently being processed */
132360   StrBuffer res = {0, 0, 0};      /* Result string */
132361   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
132362
132363   if( !pCsr->pExpr ){
132364     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
132365     return;
132366   }
132367
132368   memset(&sCtx, 0, sizeof(sCtx));
132369   assert( pCsr->isRequireSeek==0 );
132370
132371   /* Count the number of terms in the query */
132372   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
132373   if( rc!=SQLITE_OK ) goto offsets_out;
132374
132375   /* Allocate the array of TermOffset iterators. */
132376   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
132377   if( 0==sCtx.aTerm ){
132378     rc = SQLITE_NOMEM;
132379     goto offsets_out;
132380   }
132381   sCtx.iDocid = pCsr->iPrevId;
132382   sCtx.pCsr = pCsr;
132383
132384   /* Loop through the table columns, appending offset information to 
132385   ** string-buffer res for each column.
132386   */
132387   for(iCol=0; iCol<pTab->nColumn; iCol++){
132388     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
132389     const char *ZDUMMY;           /* Dummy argument used with xNext() */
132390     int NDUMMY = 0;               /* Dummy argument used with xNext() */
132391     int iStart = 0;
132392     int iEnd = 0;
132393     int iCurrent = 0;
132394     const char *zDoc;
132395     int nDoc;
132396
132397     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
132398     ** no way that this operation can fail, so the return code from
132399     ** fts3ExprIterate() can be discarded.
132400     */
132401     sCtx.iCol = iCol;
132402     sCtx.iTerm = 0;
132403     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
132404
132405     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
132406     ** in column iCol, jump immediately to the next iteration of the loop.
132407     ** If an OOM occurs while retrieving the data (this can happen if SQLite
132408     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
132409     ** to the caller. 
132410     */
132411     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
132412     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
132413     if( zDoc==0 ){
132414       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
132415         continue;
132416       }
132417       rc = SQLITE_NOMEM;
132418       goto offsets_out;
132419     }
132420
132421     /* Initialize a tokenizer iterator to iterate through column iCol. */
132422     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
132423         zDoc, nDoc, &pC
132424     );
132425     if( rc!=SQLITE_OK ) goto offsets_out;
132426
132427     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
132428     while( rc==SQLITE_OK ){
132429       int i;                      /* Used to loop through terms */
132430       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
132431       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
132432
132433       for(i=0; i<nToken; i++){
132434         TermOffset *pT = &sCtx.aTerm[i];
132435         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
132436           iMinPos = pT->iPos-pT->iOff;
132437           pTerm = pT;
132438         }
132439       }
132440
132441       if( !pTerm ){
132442         /* All offsets for this column have been gathered. */
132443         rc = SQLITE_DONE;
132444       }else{
132445         assert( iCurrent<=iMinPos );
132446         if( 0==(0xFE&*pTerm->pList) ){
132447           pTerm->pList = 0;
132448         }else{
132449           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
132450         }
132451         while( rc==SQLITE_OK && iCurrent<iMinPos ){
132452           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
132453         }
132454         if( rc==SQLITE_OK ){
132455           char aBuffer[64];
132456           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
132457               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
132458           );
132459           rc = fts3StringAppend(&res, aBuffer, -1);
132460         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
132461           rc = FTS_CORRUPT_VTAB;
132462         }
132463       }
132464     }
132465     if( rc==SQLITE_DONE ){
132466       rc = SQLITE_OK;
132467     }
132468
132469     pMod->xClose(pC);
132470     if( rc!=SQLITE_OK ) goto offsets_out;
132471   }
132472
132473  offsets_out:
132474   sqlite3_free(sCtx.aTerm);
132475   assert( rc!=SQLITE_DONE );
132476   sqlite3Fts3SegmentsClose(pTab);
132477   if( rc!=SQLITE_OK ){
132478     sqlite3_result_error_code(pCtx,  rc);
132479     sqlite3_free(res.z);
132480   }else{
132481     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
132482   }
132483   return;
132484 }
132485
132486 /*
132487 ** Implementation of matchinfo() function.
132488 */
132489 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
132490   sqlite3_context *pContext,      /* Function call context */
132491   Fts3Cursor *pCsr,               /* FTS3 table cursor */
132492   const char *zArg                /* Second arg to matchinfo() function */
132493 ){
132494   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132495   int rc;
132496   int i;
132497   const char *zFormat;
132498
132499   if( zArg ){
132500     for(i=0; zArg[i]; i++){
132501       char *zErr = 0;
132502       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
132503         sqlite3_result_error(pContext, zErr, -1);
132504         sqlite3_free(zErr);
132505         return;
132506       }
132507     }
132508     zFormat = zArg;
132509   }else{
132510     zFormat = FTS3_MATCHINFO_DEFAULT;
132511   }
132512
132513   if( !pCsr->pExpr ){
132514     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
132515     return;
132516   }
132517
132518   /* Retrieve matchinfo() data. */
132519   rc = fts3GetMatchinfo(pCsr, zFormat);
132520   sqlite3Fts3SegmentsClose(pTab);
132521
132522   if( rc!=SQLITE_OK ){
132523     sqlite3_result_error_code(pContext, rc);
132524   }else{
132525     int n = pCsr->nMatchinfo * sizeof(u32);
132526     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
132527   }
132528 }
132529
132530 #endif
132531
132532 /************** End of fts3_snippet.c ****************************************/
132533 /************** Begin file fts3_unicode.c ************************************/
132534 /*
132535 ** 2012 May 24
132536 **
132537 ** The author disclaims copyright to this source code.  In place of
132538 ** a legal notice, here is a blessing:
132539 **
132540 **    May you do good and not evil.
132541 **    May you find forgiveness for yourself and forgive others.
132542 **    May you share freely, never taking more than you give.
132543 **
132544 ******************************************************************************
132545 **
132546 ** Implementation of the "unicode" full-text-search tokenizer.
132547 */
132548
132549 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
132550
132551 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132552
132553 /* #include <assert.h> */
132554 /* #include <stdlib.h> */
132555 /* #include <stdio.h> */
132556 /* #include <string.h> */
132557
132558
132559 /*
132560 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
132561 ** from the sqlite3 source file utf.c. If this file is compiled as part
132562 ** of the amalgamation, they are not required.
132563 */
132564 #ifndef SQLITE_AMALGAMATION
132565
132566 static const unsigned char sqlite3Utf8Trans1[] = {
132567   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
132568   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
132569   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
132570   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
132571   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
132572   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
132573   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
132574   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
132575 };
132576
132577 #define READ_UTF8(zIn, zTerm, c)                           \
132578   c = *(zIn++);                                            \
132579   if( c>=0xc0 ){                                           \
132580     c = sqlite3Utf8Trans1[c-0xc0];                         \
132581     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
132582       c = (c<<6) + (0x3f & *(zIn++));                      \
132583     }                                                      \
132584     if( c<0x80                                             \
132585         || (c&0xFFFFF800)==0xD800                          \
132586         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
132587   }
132588
132589 #define WRITE_UTF8(zOut, c) {                          \
132590   if( c<0x00080 ){                                     \
132591     *zOut++ = (u8)(c&0xFF);                            \
132592   }                                                    \
132593   else if( c<0x00800 ){                                \
132594     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
132595     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
132596   }                                                    \
132597   else if( c<0x10000 ){                                \
132598     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
132599     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
132600     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
132601   }else{                                               \
132602     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
132603     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
132604     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
132605     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
132606   }                                                    \
132607 }
132608
132609 #endif /* ifndef SQLITE_AMALGAMATION */
132610
132611 typedef struct unicode_tokenizer unicode_tokenizer;
132612 typedef struct unicode_cursor unicode_cursor;
132613
132614 struct unicode_tokenizer {
132615   sqlite3_tokenizer base;
132616   int bRemoveDiacritic;
132617   int nException;
132618   int *aiException;
132619 };
132620
132621 struct unicode_cursor {
132622   sqlite3_tokenizer_cursor base;
132623   const unsigned char *aInput;    /* Input text being tokenized */
132624   int nInput;                     /* Size of aInput[] in bytes */
132625   int iOff;                       /* Current offset within aInput[] */
132626   int iToken;                     /* Index of next token to be returned */
132627   char *zToken;                   /* storage for current token */
132628   int nAlloc;                     /* space allocated at zToken */
132629 };
132630
132631
132632 /*
132633 ** Destroy a tokenizer allocated by unicodeCreate().
132634 */
132635 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
132636   if( pTokenizer ){
132637     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
132638     sqlite3_free(p->aiException);
132639     sqlite3_free(p);
132640   }
132641   return SQLITE_OK;
132642 }
132643
132644 /*
132645 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
132646 ** statement has specified that the tokenizer for this table shall consider
132647 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
132648 ** token characters (if bAlnum==1).
132649 **
132650 ** For each codepoint in the zIn/nIn string, this function checks if the
132651 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
132652 ** If so, no action is taken. Otherwise, the codepoint is added to the 
132653 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
132654 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
132655 ** codepoints in the aiException[] array.
132656 **
132657 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
132658 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
132659 ** It is not possible to change the behaviour of the tokenizer with respect
132660 ** to these codepoints.
132661 */
132662 static int unicodeAddExceptions(
132663   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
132664   int bAlnum,                     /* Replace Isalnum() return value with this */
132665   const char *zIn,                /* Array of characters to make exceptions */
132666   int nIn                         /* Length of z in bytes */
132667 ){
132668   const unsigned char *z = (const unsigned char *)zIn;
132669   const unsigned char *zTerm = &z[nIn];
132670   int iCode;
132671   int nEntry = 0;
132672
132673   assert( bAlnum==0 || bAlnum==1 );
132674
132675   while( z<zTerm ){
132676     READ_UTF8(z, zTerm, iCode);
132677     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
132678     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
132679      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
132680     ){
132681       nEntry++;
132682     }
132683   }
132684
132685   if( nEntry ){
132686     int *aNew;                    /* New aiException[] array */
132687     int nNew;                     /* Number of valid entries in array aNew[] */
132688
132689     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
132690     if( aNew==0 ) return SQLITE_NOMEM;
132691     nNew = p->nException;
132692
132693     z = (const unsigned char *)zIn;
132694     while( z<zTerm ){
132695       READ_UTF8(z, zTerm, iCode);
132696       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
132697        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
132698       ){
132699         int i, j;
132700         for(i=0; i<nNew && aNew[i]<iCode; i++);
132701         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
132702         aNew[i] = iCode;
132703         nNew++;
132704       }
132705     }
132706     p->aiException = aNew;
132707     p->nException = nNew;
132708   }
132709
132710   return SQLITE_OK;
132711 }
132712
132713 /*
132714 ** Return true if the p->aiException[] array contains the value iCode.
132715 */
132716 static int unicodeIsException(unicode_tokenizer *p, int iCode){
132717   if( p->nException>0 ){
132718     int *a = p->aiException;
132719     int iLo = 0;
132720     int iHi = p->nException-1;
132721
132722     while( iHi>=iLo ){
132723       int iTest = (iHi + iLo) / 2;
132724       if( iCode==a[iTest] ){
132725         return 1;
132726       }else if( iCode>a[iTest] ){
132727         iLo = iTest+1;
132728       }else{
132729         iHi = iTest-1;
132730       }
132731     }
132732   }
132733
132734   return 0;
132735 }
132736
132737 /*
132738 ** Return true if, for the purposes of tokenization, codepoint iCode is
132739 ** considered a token character (not a separator).
132740 */
132741 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
132742   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
132743   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
132744 }
132745
132746 /*
132747 ** Create a new tokenizer instance.
132748 */
132749 static int unicodeCreate(
132750   int nArg,                       /* Size of array argv[] */
132751   const char * const *azArg,      /* Tokenizer creation arguments */
132752   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
132753 ){
132754   unicode_tokenizer *pNew;        /* New tokenizer object */
132755   int i;
132756   int rc = SQLITE_OK;
132757
132758   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
132759   if( pNew==NULL ) return SQLITE_NOMEM;
132760   memset(pNew, 0, sizeof(unicode_tokenizer));
132761   pNew->bRemoveDiacritic = 1;
132762
132763   for(i=0; rc==SQLITE_OK && i<nArg; i++){
132764     const char *z = azArg[i];
132765     int n = strlen(z);
132766
132767     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
132768       pNew->bRemoveDiacritic = 1;
132769     }
132770     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
132771       pNew->bRemoveDiacritic = 0;
132772     }
132773     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
132774       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
132775     }
132776     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
132777       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
132778     }
132779     else{
132780       /* Unrecognized argument */
132781       rc  = SQLITE_ERROR;
132782     }
132783   }
132784
132785   if( rc!=SQLITE_OK ){
132786     unicodeDestroy((sqlite3_tokenizer *)pNew);
132787     pNew = 0;
132788   }
132789   *pp = (sqlite3_tokenizer *)pNew;
132790   return rc;
132791 }
132792
132793 /*
132794 ** Prepare to begin tokenizing a particular string.  The input
132795 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
132796 ** used to incrementally tokenize this string is returned in 
132797 ** *ppCursor.
132798 */
132799 static int unicodeOpen(
132800   sqlite3_tokenizer *p,           /* The tokenizer */
132801   const char *aInput,             /* Input string */
132802   int nInput,                     /* Size of string aInput in bytes */
132803   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
132804 ){
132805   unicode_cursor *pCsr;
132806
132807   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
132808   if( pCsr==0 ){
132809     return SQLITE_NOMEM;
132810   }
132811   memset(pCsr, 0, sizeof(unicode_cursor));
132812
132813   pCsr->aInput = (const unsigned char *)aInput;
132814   if( aInput==0 ){
132815     pCsr->nInput = 0;
132816   }else if( nInput<0 ){
132817     pCsr->nInput = (int)strlen(aInput);
132818   }else{
132819     pCsr->nInput = nInput;
132820   }
132821
132822   *pp = &pCsr->base;
132823   UNUSED_PARAMETER(p);
132824   return SQLITE_OK;
132825 }
132826
132827 /*
132828 ** Close a tokenization cursor previously opened by a call to
132829 ** simpleOpen() above.
132830 */
132831 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
132832   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
132833   sqlite3_free(pCsr->zToken);
132834   sqlite3_free(pCsr);
132835   return SQLITE_OK;
132836 }
132837
132838 /*
132839 ** Extract the next token from a tokenization cursor.  The cursor must
132840 ** have been opened by a prior call to simpleOpen().
132841 */
132842 static int unicodeNext(
132843   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
132844   const char **paToken,           /* OUT: Token text */
132845   int *pnToken,                   /* OUT: Number of bytes at *paToken */
132846   int *piStart,                   /* OUT: Starting offset of token */
132847   int *piEnd,                     /* OUT: Ending offset of token */
132848   int *piPos                      /* OUT: Position integer of token */
132849 ){
132850   unicode_cursor *pCsr = (unicode_cursor *)pC;
132851   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
132852   int iCode;
132853   char *zOut;
132854   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
132855   const unsigned char *zStart = z;
132856   const unsigned char *zEnd;
132857   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
132858
132859   /* Scan past any delimiter characters before the start of the next token.
132860   ** Return SQLITE_DONE early if this takes us all the way to the end of 
132861   ** the input.  */
132862   while( z<zTerm ){
132863     READ_UTF8(z, zTerm, iCode);
132864     if( unicodeIsAlnum(p, iCode) ) break;
132865     zStart = z;
132866   }
132867   if( zStart>=zTerm ) return SQLITE_DONE;
132868
132869   zOut = pCsr->zToken;
132870   do {
132871     int iOut;
132872
132873     /* Grow the output buffer if required. */
132874     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
132875       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
132876       if( !zNew ) return SQLITE_NOMEM;
132877       zOut = &zNew[zOut - pCsr->zToken];
132878       pCsr->zToken = zNew;
132879       pCsr->nAlloc += 64;
132880     }
132881
132882     /* Write the folded case of the last character read to the output */
132883     zEnd = z;
132884     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
132885     if( iOut ){
132886       WRITE_UTF8(zOut, iOut);
132887     }
132888
132889     /* If the cursor is not at EOF, read the next character */
132890     if( z>=zTerm ) break;
132891     READ_UTF8(z, zTerm, iCode);
132892   }while( unicodeIsAlnum(p, iCode) 
132893        || sqlite3FtsUnicodeIsdiacritic(iCode)
132894   );
132895
132896   /* Set the output variables and return. */
132897   pCsr->iOff = (z - pCsr->aInput);
132898   *paToken = pCsr->zToken;
132899   *pnToken = zOut - pCsr->zToken;
132900   *piStart = (zStart - pCsr->aInput);
132901   *piEnd = (zEnd - pCsr->aInput);
132902   *piPos = pCsr->iToken++;
132903   return SQLITE_OK;
132904 }
132905
132906 /*
132907 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
132908 ** structure for the unicode tokenizer.
132909 */
132910 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
132911   static const sqlite3_tokenizer_module module = {
132912     0,
132913     unicodeCreate,
132914     unicodeDestroy,
132915     unicodeOpen,
132916     unicodeClose,
132917     unicodeNext,
132918     0,
132919   };
132920   *ppModule = &module;
132921 }
132922
132923 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
132924 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
132925
132926 /************** End of fts3_unicode.c ****************************************/
132927 /************** Begin file fts3_unicode2.c ***********************************/
132928 /*
132929 ** 2012 May 25
132930 **
132931 ** The author disclaims copyright to this source code.  In place of
132932 ** a legal notice, here is a blessing:
132933 **
132934 **    May you do good and not evil.
132935 **    May you find forgiveness for yourself and forgive others.
132936 **    May you share freely, never taking more than you give.
132937 **
132938 ******************************************************************************
132939 */
132940
132941 /*
132942 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
132943 */
132944
132945 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
132946 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
132947
132948 /* #include <assert.h> */
132949
132950 /*
132951 ** Return true if the argument corresponds to a unicode codepoint
132952 ** classified as either a letter or a number. Otherwise false.
132953 **
132954 ** The results are undefined if the value passed to this function
132955 ** is less than zero.
132956 */
132957 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
132958   /* Each unsigned integer in the following array corresponds to a contiguous
132959   ** range of unicode codepoints that are not either letters or numbers (i.e.
132960   ** codepoints for which this function should return 0).
132961   **
132962   ** The most significant 22 bits in each 32-bit value contain the first 
132963   ** codepoint in the range. The least significant 10 bits are used to store
132964   ** the size of the range (always at least 1). In other words, the value 
132965   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
132966   ** C. It is not possible to represent a range larger than 1023 codepoints 
132967   ** using this format.
132968   */
132969   const static unsigned int aEntry[] = {
132970     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
132971     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
132972     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
132973     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
132974     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
132975     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
132976     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
132977     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
132978     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
132979     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
132980     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
132981     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
132982     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
132983     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
132984     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
132985     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
132986     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
132987     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
132988     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
132989     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
132990     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
132991     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
132992     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
132993     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
132994     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
132995     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
132996     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
132997     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
132998     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
132999     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
133000     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
133001     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
133002     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
133003     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
133004     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
133005     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
133006     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
133007     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
133008     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
133009     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
133010     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
133011     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
133012     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
133013     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
133014     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
133015     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
133016     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
133017     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
133018     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
133019     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
133020     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
133021     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
133022     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
133023     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
133024     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
133025     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
133026     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
133027     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
133028     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
133029     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
133030     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
133031     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
133032     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
133033     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
133034     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
133035     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
133036     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
133037     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
133038     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
133039     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
133040     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
133041     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
133042     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
133043     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
133044     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
133045     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
133046     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
133047     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
133048     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
133049     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
133050     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
133051     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
133052     0x43FFF401,
133053   };
133054   static const unsigned int aAscii[4] = {
133055     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
133056   };
133057
133058   if( c<128 ){
133059     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
133060   }else if( c<(1<<22) ){
133061     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
133062     int iRes;
133063     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133064     int iLo = 0;
133065     while( iHi>=iLo ){
133066       int iTest = (iHi + iLo) / 2;
133067       if( key >= aEntry[iTest] ){
133068         iRes = iTest;
133069         iLo = iTest+1;
133070       }else{
133071         iHi = iTest-1;
133072       }
133073     }
133074     assert( aEntry[0]<key );
133075     assert( key>=aEntry[iRes] );
133076     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
133077   }
133078   return 1;
133079 }
133080
133081
133082 /*
133083 ** If the argument is a codepoint corresponding to a lowercase letter
133084 ** in the ASCII range with a diacritic added, return the codepoint
133085 ** of the ASCII letter only. For example, if passed 235 - "LATIN
133086 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
133087 ** E"). The resuls of passing a codepoint that corresponds to an
133088 ** uppercase letter are undefined.
133089 */
133090 static int remove_diacritic(int c){
133091   unsigned short aDia[] = {
133092         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
133093      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
133094      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
133095      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
133096      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
133097      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
133098      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
133099      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
133100     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
133101     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
133102     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
133103     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
133104     62924, 63050, 63082, 63274, 63390, 
133105   };
133106   char aChar[] = {
133107     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
133108     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
133109     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
133110     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
133111     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
133112     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
133113     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
133114     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
133115     'e',  'i',  'o',  'u',  'y',  
133116   };
133117
133118   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
133119   int iRes = 0;
133120   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
133121   int iLo = 0;
133122   while( iHi>=iLo ){
133123     int iTest = (iHi + iLo) / 2;
133124     if( key >= aDia[iTest] ){
133125       iRes = iTest;
133126       iLo = iTest+1;
133127     }else{
133128       iHi = iTest-1;
133129     }
133130   }
133131   assert( key>=aDia[iRes] );
133132   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
133133 };
133134
133135
133136 /*
133137 ** Return true if the argument interpreted as a unicode codepoint
133138 ** is a diacritical modifier character.
133139 */
133140 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
133141   unsigned int mask0 = 0x08029FDF;
133142   unsigned int mask1 = 0x000361F8;
133143   if( c<768 || c>817 ) return 0;
133144   return (c < 768+32) ?
133145       (mask0 & (1 << (c-768))) :
133146       (mask1 & (1 << (c-768-32)));
133147 }
133148
133149
133150 /*
133151 ** Interpret the argument as a unicode codepoint. If the codepoint
133152 ** is an upper case character that has a lower case equivalent,
133153 ** return the codepoint corresponding to the lower case version.
133154 ** Otherwise, return a copy of the argument.
133155 **
133156 ** The results are undefined if the value passed to this function
133157 ** is less than zero.
133158 */
133159 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
133160   /* Each entry in the following array defines a rule for folding a range
133161   ** of codepoints to lower case. The rule applies to a range of nRange
133162   ** codepoints starting at codepoint iCode.
133163   **
133164   ** If the least significant bit in flags is clear, then the rule applies
133165   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
133166   ** need to be folded). Or, if it is set, then the rule only applies to
133167   ** every second codepoint in the range, starting with codepoint C.
133168   **
133169   ** The 7 most significant bits in flags are an index into the aiOff[]
133170   ** array. If a specific codepoint C does require folding, then its lower
133171   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
133172   **
133173   ** The contents of this array are generated by parsing the CaseFolding.txt
133174   ** file distributed as part of the "Unicode Character Database". See
133175   ** http://www.unicode.org for details.
133176   */
133177   static const struct TableEntry {
133178     unsigned short iCode;
133179     unsigned char flags;
133180     unsigned char nRange;
133181   } aEntry[] = {
133182     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
133183     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
133184     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
133185     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
133186     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
133187     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
133188     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
133189     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
133190     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
133191     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
133192     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
133193     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
133194     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
133195     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
133196     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
133197     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
133198     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
133199     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
133200     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
133201     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
133202     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
133203     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
133204     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
133205     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
133206     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
133207     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
133208     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
133209     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
133210     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
133211     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
133212     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
133213     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
133214     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
133215     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
133216     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
133217     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
133218     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
133219     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
133220     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
133221     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
133222     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
133223     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
133224     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
133225     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
133226     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
133227     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
133228     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
133229     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
133230     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
133231     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
133232     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
133233     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
133234     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
133235     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
133236     {65313, 14, 26},       
133237   };
133238   static const unsigned short aiOff[] = {
133239    1,     2,     8,     15,    16,    26,    28,    32,    
133240    37,    38,    40,    48,    63,    64,    69,    71,    
133241    79,    80,    116,   202,   203,   205,   206,   207,   
133242    209,   210,   211,   213,   214,   217,   218,   219,   
133243    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
133244    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
133245    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
133246    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
133247    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
133248    65514, 65521, 65527, 65528, 65529, 
133249   };
133250
133251   int ret = c;
133252
133253   assert( c>=0 );
133254   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
133255
133256   if( c<128 ){
133257     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
133258   }else if( c<65536 ){
133259     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133260     int iLo = 0;
133261     int iRes = -1;
133262
133263     while( iHi>=iLo ){
133264       int iTest = (iHi + iLo) / 2;
133265       int cmp = (c - aEntry[iTest].iCode);
133266       if( cmp>=0 ){
133267         iRes = iTest;
133268         iLo = iTest+1;
133269       }else{
133270         iHi = iTest-1;
133271       }
133272     }
133273     assert( iRes<0 || c>=aEntry[iRes].iCode );
133274
133275     if( iRes>=0 ){
133276       const struct TableEntry *p = &aEntry[iRes];
133277       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
133278         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
133279         assert( ret>0 );
133280       }
133281     }
133282
133283     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
133284   }
133285   
133286   else if( c>=66560 && c<66600 ){
133287     ret = c + 40;
133288   }
133289
133290   return ret;
133291 }
133292 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
133293 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
133294
133295 /************** End of fts3_unicode2.c ***************************************/
133296 /************** Begin file rtree.c *******************************************/
133297 /*
133298 ** 2001 September 15
133299 **
133300 ** The author disclaims copyright to this source code.  In place of
133301 ** a legal notice, here is a blessing:
133302 **
133303 **    May you do good and not evil.
133304 **    May you find forgiveness for yourself and forgive others.
133305 **    May you share freely, never taking more than you give.
133306 **
133307 *************************************************************************
133308 ** This file contains code for implementations of the r-tree and r*-tree
133309 ** algorithms packaged as an SQLite virtual table module.
133310 */
133311
133312 /*
133313 ** Database Format of R-Tree Tables
133314 ** --------------------------------
133315 **
133316 ** The data structure for a single virtual r-tree table is stored in three 
133317 ** native SQLite tables declared as follows. In each case, the '%' character
133318 ** in the table name is replaced with the user-supplied name of the r-tree
133319 ** table.
133320 **
133321 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
133322 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
133323 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
133324 **
133325 ** The data for each node of the r-tree structure is stored in the %_node
133326 ** table. For each node that is not the root node of the r-tree, there is
133327 ** an entry in the %_parent table associating the node with its parent.
133328 ** And for each row of data in the table, there is an entry in the %_rowid
133329 ** table that maps from the entries rowid to the id of the node that it
133330 ** is stored on.
133331 **
133332 ** The root node of an r-tree always exists, even if the r-tree table is
133333 ** empty. The nodeno of the root node is always 1. All other nodes in the
133334 ** table must be the same size as the root node. The content of each node
133335 ** is formatted as follows:
133336 **
133337 **   1. If the node is the root node (node 1), then the first 2 bytes
133338 **      of the node contain the tree depth as a big-endian integer.
133339 **      For non-root nodes, the first 2 bytes are left unused.
133340 **
133341 **   2. The next 2 bytes contain the number of entries currently 
133342 **      stored in the node.
133343 **
133344 **   3. The remainder of the node contains the node entries. Each entry
133345 **      consists of a single 8-byte integer followed by an even number
133346 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
133347 **      of a record. For internal nodes it is the node number of a
133348 **      child page.
133349 */
133350
133351 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
133352
133353 /*
133354 ** This file contains an implementation of a couple of different variants
133355 ** of the r-tree algorithm. See the README file for further details. The 
133356 ** same data-structure is used for all, but the algorithms for insert and
133357 ** delete operations vary. The variants used are selected at compile time 
133358 ** by defining the following symbols:
133359 */
133360
133361 /* Either, both or none of the following may be set to activate 
133362 ** r*tree variant algorithms.
133363 */
133364 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
133365 #define VARIANT_RSTARTREE_REINSERT      1
133366
133367 /* 
133368 ** Exactly one of the following must be set to 1.
133369 */
133370 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
133371 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
133372 #define VARIANT_RSTARTREE_SPLIT         1
133373
133374 #define VARIANT_GUTTMAN_SPLIT \
133375         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
133376
133377 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
133378   #define PickNext QuadraticPickNext
133379   #define PickSeeds QuadraticPickSeeds
133380   #define AssignCells splitNodeGuttman
133381 #endif
133382 #if VARIANT_GUTTMAN_LINEAR_SPLIT
133383   #define PickNext LinearPickNext
133384   #define PickSeeds LinearPickSeeds
133385   #define AssignCells splitNodeGuttman
133386 #endif
133387 #if VARIANT_RSTARTREE_SPLIT
133388   #define AssignCells splitNodeStartree
133389 #endif
133390
133391 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
133392 # define NDEBUG 1
133393 #endif
133394
133395 #ifndef SQLITE_CORE
133396   SQLITE_EXTENSION_INIT1
133397 #else
133398 #endif
133399
133400 /* #include <string.h> */
133401 /* #include <assert.h> */
133402
133403 #ifndef SQLITE_AMALGAMATION
133404 #include "sqlite3rtree.h"
133405 typedef sqlite3_int64 i64;
133406 typedef unsigned char u8;
133407 typedef unsigned int u32;
133408 #endif
133409
133410 /*  The following macro is used to suppress compiler warnings.
133411 */
133412 #ifndef UNUSED_PARAMETER
133413 # define UNUSED_PARAMETER(x) (void)(x)
133414 #endif
133415
133416 typedef struct Rtree Rtree;
133417 typedef struct RtreeCursor RtreeCursor;
133418 typedef struct RtreeNode RtreeNode;
133419 typedef struct RtreeCell RtreeCell;
133420 typedef struct RtreeConstraint RtreeConstraint;
133421 typedef struct RtreeMatchArg RtreeMatchArg;
133422 typedef struct RtreeGeomCallback RtreeGeomCallback;
133423 typedef union RtreeCoord RtreeCoord;
133424
133425 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
133426 #define RTREE_MAX_DIMENSIONS 5
133427
133428 /* Size of hash table Rtree.aHash. This hash table is not expected to
133429 ** ever contain very many entries, so a fixed number of buckets is 
133430 ** used.
133431 */
133432 #define HASHSIZE 128
133433
133434 /* 
133435 ** An rtree virtual-table object.
133436 */
133437 struct Rtree {
133438   sqlite3_vtab base;
133439   sqlite3 *db;                /* Host database connection */
133440   int iNodeSize;              /* Size in bytes of each node in the node table */
133441   int nDim;                   /* Number of dimensions */
133442   int nBytesPerCell;          /* Bytes consumed per cell */
133443   int iDepth;                 /* Current depth of the r-tree structure */
133444   char *zDb;                  /* Name of database containing r-tree table */
133445   char *zName;                /* Name of r-tree table */ 
133446   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
133447   int nBusy;                  /* Current number of users of this structure */
133448
133449   /* List of nodes removed during a CondenseTree operation. List is
133450   ** linked together via the pointer normally used for hash chains -
133451   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
133452   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
133453   */
133454   RtreeNode *pDeleted;
133455   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
133456
133457   /* Statements to read/write/delete a record from xxx_node */
133458   sqlite3_stmt *pReadNode;
133459   sqlite3_stmt *pWriteNode;
133460   sqlite3_stmt *pDeleteNode;
133461
133462   /* Statements to read/write/delete a record from xxx_rowid */
133463   sqlite3_stmt *pReadRowid;
133464   sqlite3_stmt *pWriteRowid;
133465   sqlite3_stmt *pDeleteRowid;
133466
133467   /* Statements to read/write/delete a record from xxx_parent */
133468   sqlite3_stmt *pReadParent;
133469   sqlite3_stmt *pWriteParent;
133470   sqlite3_stmt *pDeleteParent;
133471
133472   int eCoordType;
133473 };
133474
133475 /* Possible values for eCoordType: */
133476 #define RTREE_COORD_REAL32 0
133477 #define RTREE_COORD_INT32  1
133478
133479 /*
133480 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
133481 ** only deal with integer coordinates.  No floating point operations
133482 ** will be done.
133483 */
133484 #ifdef SQLITE_RTREE_INT_ONLY
133485   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
133486   typedef int RtreeValue;                  /* Low accuracy coordinate */
133487 #else
133488   typedef double RtreeDValue;              /* High accuracy coordinate */
133489   typedef float RtreeValue;                /* Low accuracy coordinate */
133490 #endif
133491
133492 /*
133493 ** The minimum number of cells allowed for a node is a third of the 
133494 ** maximum. In Gutman's notation:
133495 **
133496 **     m = M/3
133497 **
133498 ** If an R*-tree "Reinsert" operation is required, the same number of
133499 ** cells are removed from the overfull node and reinserted into the tree.
133500 */
133501 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
133502 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
133503 #define RTREE_MAXCELLS 51
133504
133505 /*
133506 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
133507 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
133508 ** Therefore all non-root nodes must contain at least 3 entries. Since 
133509 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
133510 ** 40 or less.
133511 */
133512 #define RTREE_MAX_DEPTH 40
133513
133514 /* 
133515 ** An rtree cursor object.
133516 */
133517 struct RtreeCursor {
133518   sqlite3_vtab_cursor base;
133519   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
133520   int iCell;                        /* Index of current cell in pNode */
133521   int iStrategy;                    /* Copy of idxNum search parameter */
133522   int nConstraint;                  /* Number of entries in aConstraint */
133523   RtreeConstraint *aConstraint;     /* Search constraints. */
133524 };
133525
133526 union RtreeCoord {
133527   RtreeValue f;
133528   int i;
133529 };
133530
133531 /*
133532 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
133533 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
133534 ** variable pRtree points to the Rtree structure associated with the
133535 ** RtreeCoord.
133536 */
133537 #ifdef SQLITE_RTREE_INT_ONLY
133538 # define DCOORD(coord) ((RtreeDValue)coord.i)
133539 #else
133540 # define DCOORD(coord) (                           \
133541     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
133542       ((double)coord.f) :                           \
133543       ((double)coord.i)                             \
133544   )
133545 #endif
133546
133547 /*
133548 ** A search constraint.
133549 */
133550 struct RtreeConstraint {
133551   int iCoord;                     /* Index of constrained coordinate */
133552   int op;                         /* Constraining operation */
133553   RtreeDValue rValue;             /* Constraint value. */
133554   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
133555   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
133556 };
133557
133558 /* Possible values for RtreeConstraint.op */
133559 #define RTREE_EQ    0x41
133560 #define RTREE_LE    0x42
133561 #define RTREE_LT    0x43
133562 #define RTREE_GE    0x44
133563 #define RTREE_GT    0x45
133564 #define RTREE_MATCH 0x46
133565
133566 /* 
133567 ** An rtree structure node.
133568 */
133569 struct RtreeNode {
133570   RtreeNode *pParent;               /* Parent node */
133571   i64 iNode;
133572   int nRef;
133573   int isDirty;
133574   u8 *zData;
133575   RtreeNode *pNext;                 /* Next node in this hash chain */
133576 };
133577 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
133578
133579 /* 
133580 ** Structure to store a deserialized rtree record.
133581 */
133582 struct RtreeCell {
133583   i64 iRowid;
133584   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
133585 };
133586
133587
133588 /*
133589 ** Value for the first field of every RtreeMatchArg object. The MATCH
133590 ** operator tests that the first field of a blob operand matches this
133591 ** value to avoid operating on invalid blobs (which could cause a segfault).
133592 */
133593 #define RTREE_GEOMETRY_MAGIC 0x891245AB
133594
133595 /*
133596 ** An instance of this structure must be supplied as a blob argument to
133597 ** the right-hand-side of an SQL MATCH operator used to constrain an
133598 ** r-tree query.
133599 */
133600 struct RtreeMatchArg {
133601   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
133602   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
133603   void *pContext;
133604   int nParam;
133605   RtreeDValue aParam[1];
133606 };
133607
133608 /*
133609 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
133610 ** a single instance of the following structure is allocated. It is used
133611 ** as the context for the user-function created by by s_r_g_c(). The object
133612 ** is eventually deleted by the destructor mechanism provided by
133613 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
133614 ** the geometry callback function).
133615 */
133616 struct RtreeGeomCallback {
133617   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
133618   void *pContext;
133619 };
133620
133621 #ifndef MAX
133622 # define MAX(x,y) ((x) < (y) ? (y) : (x))
133623 #endif
133624 #ifndef MIN
133625 # define MIN(x,y) ((x) > (y) ? (y) : (x))
133626 #endif
133627
133628 /*
133629 ** Functions to deserialize a 16 bit integer, 32 bit real number and
133630 ** 64 bit integer. The deserialized value is returned.
133631 */
133632 static int readInt16(u8 *p){
133633   return (p[0]<<8) + p[1];
133634 }
133635 static void readCoord(u8 *p, RtreeCoord *pCoord){
133636   u32 i = (
133637     (((u32)p[0]) << 24) + 
133638     (((u32)p[1]) << 16) + 
133639     (((u32)p[2]) <<  8) + 
133640     (((u32)p[3]) <<  0)
133641   );
133642   *(u32 *)pCoord = i;
133643 }
133644 static i64 readInt64(u8 *p){
133645   return (
133646     (((i64)p[0]) << 56) + 
133647     (((i64)p[1]) << 48) + 
133648     (((i64)p[2]) << 40) + 
133649     (((i64)p[3]) << 32) + 
133650     (((i64)p[4]) << 24) + 
133651     (((i64)p[5]) << 16) + 
133652     (((i64)p[6]) <<  8) + 
133653     (((i64)p[7]) <<  0)
133654   );
133655 }
133656
133657 /*
133658 ** Functions to serialize a 16 bit integer, 32 bit real number and
133659 ** 64 bit integer. The value returned is the number of bytes written
133660 ** to the argument buffer (always 2, 4 and 8 respectively).
133661 */
133662 static int writeInt16(u8 *p, int i){
133663   p[0] = (i>> 8)&0xFF;
133664   p[1] = (i>> 0)&0xFF;
133665   return 2;
133666 }
133667 static int writeCoord(u8 *p, RtreeCoord *pCoord){
133668   u32 i;
133669   assert( sizeof(RtreeCoord)==4 );
133670   assert( sizeof(u32)==4 );
133671   i = *(u32 *)pCoord;
133672   p[0] = (i>>24)&0xFF;
133673   p[1] = (i>>16)&0xFF;
133674   p[2] = (i>> 8)&0xFF;
133675   p[3] = (i>> 0)&0xFF;
133676   return 4;
133677 }
133678 static int writeInt64(u8 *p, i64 i){
133679   p[0] = (i>>56)&0xFF;
133680   p[1] = (i>>48)&0xFF;
133681   p[2] = (i>>40)&0xFF;
133682   p[3] = (i>>32)&0xFF;
133683   p[4] = (i>>24)&0xFF;
133684   p[5] = (i>>16)&0xFF;
133685   p[6] = (i>> 8)&0xFF;
133686   p[7] = (i>> 0)&0xFF;
133687   return 8;
133688 }
133689
133690 /*
133691 ** Increment the reference count of node p.
133692 */
133693 static void nodeReference(RtreeNode *p){
133694   if( p ){
133695     p->nRef++;
133696   }
133697 }
133698
133699 /*
133700 ** Clear the content of node p (set all bytes to 0x00).
133701 */
133702 static void nodeZero(Rtree *pRtree, RtreeNode *p){
133703   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
133704   p->isDirty = 1;
133705 }
133706
133707 /*
133708 ** Given a node number iNode, return the corresponding key to use
133709 ** in the Rtree.aHash table.
133710 */
133711 static int nodeHash(i64 iNode){
133712   return (
133713     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
133714     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
133715   ) % HASHSIZE;
133716 }
133717
133718 /*
133719 ** Search the node hash table for node iNode. If found, return a pointer
133720 ** to it. Otherwise, return 0.
133721 */
133722 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
133723   RtreeNode *p;
133724   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
133725   return p;
133726 }
133727
133728 /*
133729 ** Add node pNode to the node hash table.
133730 */
133731 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
133732   int iHash;
133733   assert( pNode->pNext==0 );
133734   iHash = nodeHash(pNode->iNode);
133735   pNode->pNext = pRtree->aHash[iHash];
133736   pRtree->aHash[iHash] = pNode;
133737 }
133738
133739 /*
133740 ** Remove node pNode from the node hash table.
133741 */
133742 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
133743   RtreeNode **pp;
133744   if( pNode->iNode!=0 ){
133745     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
133746     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
133747     *pp = pNode->pNext;
133748     pNode->pNext = 0;
133749   }
133750 }
133751
133752 /*
133753 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
133754 ** indicating that node has not yet been assigned a node number. It is
133755 ** assigned a node number when nodeWrite() is called to write the
133756 ** node contents out to the database.
133757 */
133758 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
133759   RtreeNode *pNode;
133760   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
133761   if( pNode ){
133762     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
133763     pNode->zData = (u8 *)&pNode[1];
133764     pNode->nRef = 1;
133765     pNode->pParent = pParent;
133766     pNode->isDirty = 1;
133767     nodeReference(pParent);
133768   }
133769   return pNode;
133770 }
133771
133772 /*
133773 ** Obtain a reference to an r-tree node.
133774 */
133775 static int
133776 nodeAcquire(
133777   Rtree *pRtree,             /* R-tree structure */
133778   i64 iNode,                 /* Node number to load */
133779   RtreeNode *pParent,        /* Either the parent node or NULL */
133780   RtreeNode **ppNode         /* OUT: Acquired node */
133781 ){
133782   int rc;
133783   int rc2 = SQLITE_OK;
133784   RtreeNode *pNode;
133785
133786   /* Check if the requested node is already in the hash table. If so,
133787   ** increase its reference count and return it.
133788   */
133789   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
133790     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
133791     if( pParent && !pNode->pParent ){
133792       nodeReference(pParent);
133793       pNode->pParent = pParent;
133794     }
133795     pNode->nRef++;
133796     *ppNode = pNode;
133797     return SQLITE_OK;
133798   }
133799
133800   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
133801   rc = sqlite3_step(pRtree->pReadNode);
133802   if( rc==SQLITE_ROW ){
133803     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
133804     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
133805       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
133806       if( !pNode ){
133807         rc2 = SQLITE_NOMEM;
133808       }else{
133809         pNode->pParent = pParent;
133810         pNode->zData = (u8 *)&pNode[1];
133811         pNode->nRef = 1;
133812         pNode->iNode = iNode;
133813         pNode->isDirty = 0;
133814         pNode->pNext = 0;
133815         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
133816         nodeReference(pParent);
133817       }
133818     }
133819   }
133820   rc = sqlite3_reset(pRtree->pReadNode);
133821   if( rc==SQLITE_OK ) rc = rc2;
133822
133823   /* If the root node was just loaded, set pRtree->iDepth to the height
133824   ** of the r-tree structure. A height of zero means all data is stored on
133825   ** the root node. A height of one means the children of the root node
133826   ** are the leaves, and so on. If the depth as specified on the root node
133827   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
133828   */
133829   if( pNode && iNode==1 ){
133830     pRtree->iDepth = readInt16(pNode->zData);
133831     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
133832       rc = SQLITE_CORRUPT_VTAB;
133833     }
133834   }
133835
133836   /* If no error has occurred so far, check if the "number of entries"
133837   ** field on the node is too large. If so, set the return code to 
133838   ** SQLITE_CORRUPT_VTAB.
133839   */
133840   if( pNode && rc==SQLITE_OK ){
133841     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
133842       rc = SQLITE_CORRUPT_VTAB;
133843     }
133844   }
133845
133846   if( rc==SQLITE_OK ){
133847     if( pNode!=0 ){
133848       nodeHashInsert(pRtree, pNode);
133849     }else{
133850       rc = SQLITE_CORRUPT_VTAB;
133851     }
133852     *ppNode = pNode;
133853   }else{
133854     sqlite3_free(pNode);
133855     *ppNode = 0;
133856   }
133857
133858   return rc;
133859 }
133860
133861 /*
133862 ** Overwrite cell iCell of node pNode with the contents of pCell.
133863 */
133864 static void nodeOverwriteCell(
133865   Rtree *pRtree, 
133866   RtreeNode *pNode,  
133867   RtreeCell *pCell, 
133868   int iCell
133869 ){
133870   int ii;
133871   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
133872   p += writeInt64(p, pCell->iRowid);
133873   for(ii=0; ii<(pRtree->nDim*2); ii++){
133874     p += writeCoord(p, &pCell->aCoord[ii]);
133875   }
133876   pNode->isDirty = 1;
133877 }
133878
133879 /*
133880 ** Remove cell the cell with index iCell from node pNode.
133881 */
133882 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
133883   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
133884   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
133885   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
133886   memmove(pDst, pSrc, nByte);
133887   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
133888   pNode->isDirty = 1;
133889 }
133890
133891 /*
133892 ** Insert the contents of cell pCell into node pNode. If the insert
133893 ** is successful, return SQLITE_OK.
133894 **
133895 ** If there is not enough free space in pNode, return SQLITE_FULL.
133896 */
133897 static int
133898 nodeInsertCell(
133899   Rtree *pRtree, 
133900   RtreeNode *pNode, 
133901   RtreeCell *pCell 
133902 ){
133903   int nCell;                    /* Current number of cells in pNode */
133904   int nMaxCell;                 /* Maximum number of cells for pNode */
133905
133906   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
133907   nCell = NCELL(pNode);
133908
133909   assert( nCell<=nMaxCell );
133910   if( nCell<nMaxCell ){
133911     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
133912     writeInt16(&pNode->zData[2], nCell+1);
133913     pNode->isDirty = 1;
133914   }
133915
133916   return (nCell==nMaxCell);
133917 }
133918
133919 /*
133920 ** If the node is dirty, write it out to the database.
133921 */
133922 static int
133923 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
133924   int rc = SQLITE_OK;
133925   if( pNode->isDirty ){
133926     sqlite3_stmt *p = pRtree->pWriteNode;
133927     if( pNode->iNode ){
133928       sqlite3_bind_int64(p, 1, pNode->iNode);
133929     }else{
133930       sqlite3_bind_null(p, 1);
133931     }
133932     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
133933     sqlite3_step(p);
133934     pNode->isDirty = 0;
133935     rc = sqlite3_reset(p);
133936     if( pNode->iNode==0 && rc==SQLITE_OK ){
133937       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
133938       nodeHashInsert(pRtree, pNode);
133939     }
133940   }
133941   return rc;
133942 }
133943
133944 /*
133945 ** Release a reference to a node. If the node is dirty and the reference
133946 ** count drops to zero, the node data is written to the database.
133947 */
133948 static int
133949 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
133950   int rc = SQLITE_OK;
133951   if( pNode ){
133952     assert( pNode->nRef>0 );
133953     pNode->nRef--;
133954     if( pNode->nRef==0 ){
133955       if( pNode->iNode==1 ){
133956         pRtree->iDepth = -1;
133957       }
133958       if( pNode->pParent ){
133959         rc = nodeRelease(pRtree, pNode->pParent);
133960       }
133961       if( rc==SQLITE_OK ){
133962         rc = nodeWrite(pRtree, pNode);
133963       }
133964       nodeHashDelete(pRtree, pNode);
133965       sqlite3_free(pNode);
133966     }
133967   }
133968   return rc;
133969 }
133970
133971 /*
133972 ** Return the 64-bit integer value associated with cell iCell of
133973 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
133974 ** an internal node, then the 64-bit integer is a child page number.
133975 */
133976 static i64 nodeGetRowid(
133977   Rtree *pRtree, 
133978   RtreeNode *pNode, 
133979   int iCell
133980 ){
133981   assert( iCell<NCELL(pNode) );
133982   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
133983 }
133984
133985 /*
133986 ** Return coordinate iCoord from cell iCell in node pNode.
133987 */
133988 static void nodeGetCoord(
133989   Rtree *pRtree, 
133990   RtreeNode *pNode, 
133991   int iCell,
133992   int iCoord,
133993   RtreeCoord *pCoord           /* Space to write result to */
133994 ){
133995   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
133996 }
133997
133998 /*
133999 ** Deserialize cell iCell of node pNode. Populate the structure pointed
134000 ** to by pCell with the results.
134001 */
134002 static void nodeGetCell(
134003   Rtree *pRtree, 
134004   RtreeNode *pNode, 
134005   int iCell,
134006   RtreeCell *pCell
134007 ){
134008   int ii;
134009   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
134010   for(ii=0; ii<pRtree->nDim*2; ii++){
134011     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
134012   }
134013 }
134014
134015
134016 /* Forward declaration for the function that does the work of
134017 ** the virtual table module xCreate() and xConnect() methods.
134018 */
134019 static int rtreeInit(
134020   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
134021 );
134022
134023 /* 
134024 ** Rtree virtual table module xCreate method.
134025 */
134026 static int rtreeCreate(
134027   sqlite3 *db,
134028   void *pAux,
134029   int argc, const char *const*argv,
134030   sqlite3_vtab **ppVtab,
134031   char **pzErr
134032 ){
134033   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
134034 }
134035
134036 /* 
134037 ** Rtree virtual table module xConnect method.
134038 */
134039 static int rtreeConnect(
134040   sqlite3 *db,
134041   void *pAux,
134042   int argc, const char *const*argv,
134043   sqlite3_vtab **ppVtab,
134044   char **pzErr
134045 ){
134046   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
134047 }
134048
134049 /*
134050 ** Increment the r-tree reference count.
134051 */
134052 static void rtreeReference(Rtree *pRtree){
134053   pRtree->nBusy++;
134054 }
134055
134056 /*
134057 ** Decrement the r-tree reference count. When the reference count reaches
134058 ** zero the structure is deleted.
134059 */
134060 static void rtreeRelease(Rtree *pRtree){
134061   pRtree->nBusy--;
134062   if( pRtree->nBusy==0 ){
134063     sqlite3_finalize(pRtree->pReadNode);
134064     sqlite3_finalize(pRtree->pWriteNode);
134065     sqlite3_finalize(pRtree->pDeleteNode);
134066     sqlite3_finalize(pRtree->pReadRowid);
134067     sqlite3_finalize(pRtree->pWriteRowid);
134068     sqlite3_finalize(pRtree->pDeleteRowid);
134069     sqlite3_finalize(pRtree->pReadParent);
134070     sqlite3_finalize(pRtree->pWriteParent);
134071     sqlite3_finalize(pRtree->pDeleteParent);
134072     sqlite3_free(pRtree);
134073   }
134074 }
134075
134076 /* 
134077 ** Rtree virtual table module xDisconnect method.
134078 */
134079 static int rtreeDisconnect(sqlite3_vtab *pVtab){
134080   rtreeRelease((Rtree *)pVtab);
134081   return SQLITE_OK;
134082 }
134083
134084 /* 
134085 ** Rtree virtual table module xDestroy method.
134086 */
134087 static int rtreeDestroy(sqlite3_vtab *pVtab){
134088   Rtree *pRtree = (Rtree *)pVtab;
134089   int rc;
134090   char *zCreate = sqlite3_mprintf(
134091     "DROP TABLE '%q'.'%q_node';"
134092     "DROP TABLE '%q'.'%q_rowid';"
134093     "DROP TABLE '%q'.'%q_parent';",
134094     pRtree->zDb, pRtree->zName, 
134095     pRtree->zDb, pRtree->zName,
134096     pRtree->zDb, pRtree->zName
134097   );
134098   if( !zCreate ){
134099     rc = SQLITE_NOMEM;
134100   }else{
134101     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
134102     sqlite3_free(zCreate);
134103   }
134104   if( rc==SQLITE_OK ){
134105     rtreeRelease(pRtree);
134106   }
134107
134108   return rc;
134109 }
134110
134111 /* 
134112 ** Rtree virtual table module xOpen method.
134113 */
134114 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
134115   int rc = SQLITE_NOMEM;
134116   RtreeCursor *pCsr;
134117
134118   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
134119   if( pCsr ){
134120     memset(pCsr, 0, sizeof(RtreeCursor));
134121     pCsr->base.pVtab = pVTab;
134122     rc = SQLITE_OK;
134123   }
134124   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
134125
134126   return rc;
134127 }
134128
134129
134130 /*
134131 ** Free the RtreeCursor.aConstraint[] array and its contents.
134132 */
134133 static void freeCursorConstraints(RtreeCursor *pCsr){
134134   if( pCsr->aConstraint ){
134135     int i;                        /* Used to iterate through constraint array */
134136     for(i=0; i<pCsr->nConstraint; i++){
134137       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
134138       if( pGeom ){
134139         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
134140         sqlite3_free(pGeom);
134141       }
134142     }
134143     sqlite3_free(pCsr->aConstraint);
134144     pCsr->aConstraint = 0;
134145   }
134146 }
134147
134148 /* 
134149 ** Rtree virtual table module xClose method.
134150 */
134151 static int rtreeClose(sqlite3_vtab_cursor *cur){
134152   Rtree *pRtree = (Rtree *)(cur->pVtab);
134153   int rc;
134154   RtreeCursor *pCsr = (RtreeCursor *)cur;
134155   freeCursorConstraints(pCsr);
134156   rc = nodeRelease(pRtree, pCsr->pNode);
134157   sqlite3_free(pCsr);
134158   return rc;
134159 }
134160
134161 /*
134162 ** Rtree virtual table module xEof method.
134163 **
134164 ** Return non-zero if the cursor does not currently point to a valid 
134165 ** record (i.e if the scan has finished), or zero otherwise.
134166 */
134167 static int rtreeEof(sqlite3_vtab_cursor *cur){
134168   RtreeCursor *pCsr = (RtreeCursor *)cur;
134169   return (pCsr->pNode==0);
134170 }
134171
134172 /*
134173 ** The r-tree constraint passed as the second argument to this function is
134174 ** guaranteed to be a MATCH constraint.
134175 */
134176 static int testRtreeGeom(
134177   Rtree *pRtree,                  /* R-Tree object */
134178   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
134179   RtreeCell *pCell,               /* Cell to test */
134180   int *pbRes                      /* OUT: Test result */
134181 ){
134182   int i;
134183   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
134184   int nCoord = pRtree->nDim*2;
134185
134186   assert( pConstraint->op==RTREE_MATCH );
134187   assert( pConstraint->pGeom );
134188
134189   for(i=0; i<nCoord; i++){
134190     aCoord[i] = DCOORD(pCell->aCoord[i]);
134191   }
134192   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
134193 }
134194
134195 /* 
134196 ** Cursor pCursor currently points to a cell in a non-leaf page.
134197 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
134198 ** (excluded) by the constraints in the pCursor->aConstraint[] 
134199 ** array, or false otherwise.
134200 **
134201 ** Return SQLITE_OK if successful or an SQLite error code if an error
134202 ** occurs within a geometry callback.
134203 */
134204 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134205   RtreeCell cell;
134206   int ii;
134207   int bRes = 0;
134208   int rc = SQLITE_OK;
134209
134210   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134211   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
134212     RtreeConstraint *p = &pCursor->aConstraint[ii];
134213     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
134214     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
134215
134216     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
134217         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134218     );
134219
134220     switch( p->op ){
134221       case RTREE_LE: case RTREE_LT: 
134222         bRes = p->rValue<cell_min; 
134223         break;
134224
134225       case RTREE_GE: case RTREE_GT: 
134226         bRes = p->rValue>cell_max; 
134227         break;
134228
134229       case RTREE_EQ:
134230         bRes = (p->rValue>cell_max || p->rValue<cell_min);
134231         break;
134232
134233       default: {
134234         assert( p->op==RTREE_MATCH );
134235         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
134236         bRes = !bRes;
134237         break;
134238       }
134239     }
134240   }
134241
134242   *pbEof = bRes;
134243   return rc;
134244 }
134245
134246 /* 
134247 ** Test if the cell that cursor pCursor currently points to
134248 ** would be filtered (excluded) by the constraints in the 
134249 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
134250 ** returning. If the cell is not filtered (excluded) by the constraints,
134251 ** set pbEof to zero.
134252 **
134253 ** Return SQLITE_OK if successful or an SQLite error code if an error
134254 ** occurs within a geometry callback.
134255 **
134256 ** This function assumes that the cell is part of a leaf node.
134257 */
134258 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134259   RtreeCell cell;
134260   int ii;
134261   *pbEof = 0;
134262
134263   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134264   for(ii=0; ii<pCursor->nConstraint; ii++){
134265     RtreeConstraint *p = &pCursor->aConstraint[ii];
134266     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
134267     int res;
134268     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
134269         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134270     );
134271     switch( p->op ){
134272       case RTREE_LE: res = (coord<=p->rValue); break;
134273       case RTREE_LT: res = (coord<p->rValue);  break;
134274       case RTREE_GE: res = (coord>=p->rValue); break;
134275       case RTREE_GT: res = (coord>p->rValue);  break;
134276       case RTREE_EQ: res = (coord==p->rValue); break;
134277       default: {
134278         int rc;
134279         assert( p->op==RTREE_MATCH );
134280         rc = testRtreeGeom(pRtree, p, &cell, &res);
134281         if( rc!=SQLITE_OK ){
134282           return rc;
134283         }
134284         break;
134285       }
134286     }
134287
134288     if( !res ){
134289       *pbEof = 1;
134290       return SQLITE_OK;
134291     }
134292   }
134293
134294   return SQLITE_OK;
134295 }
134296
134297 /*
134298 ** Cursor pCursor currently points at a node that heads a sub-tree of
134299 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
134300 ** to point to the left-most cell of the sub-tree that matches the 
134301 ** configured constraints.
134302 */
134303 static int descendToCell(
134304   Rtree *pRtree, 
134305   RtreeCursor *pCursor, 
134306   int iHeight,
134307   int *pEof                 /* OUT: Set to true if cannot descend */
134308 ){
134309   int isEof;
134310   int rc;
134311   int ii;
134312   RtreeNode *pChild;
134313   sqlite3_int64 iRowid;
134314
134315   RtreeNode *pSavedNode = pCursor->pNode;
134316   int iSavedCell = pCursor->iCell;
134317
134318   assert( iHeight>=0 );
134319
134320   if( iHeight==0 ){
134321     rc = testRtreeEntry(pRtree, pCursor, &isEof);
134322   }else{
134323     rc = testRtreeCell(pRtree, pCursor, &isEof);
134324   }
134325   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
134326     goto descend_to_cell_out;
134327   }
134328
134329   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
134330   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
134331   if( rc!=SQLITE_OK ){
134332     goto descend_to_cell_out;
134333   }
134334
134335   nodeRelease(pRtree, pCursor->pNode);
134336   pCursor->pNode = pChild;
134337   isEof = 1;
134338   for(ii=0; isEof && ii<NCELL(pChild); ii++){
134339     pCursor->iCell = ii;
134340     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
134341     if( rc!=SQLITE_OK ){
134342       goto descend_to_cell_out;
134343     }
134344   }
134345
134346   if( isEof ){
134347     assert( pCursor->pNode==pChild );
134348     nodeReference(pSavedNode);
134349     nodeRelease(pRtree, pChild);
134350     pCursor->pNode = pSavedNode;
134351     pCursor->iCell = iSavedCell;
134352   }
134353
134354 descend_to_cell_out:
134355   *pEof = isEof;
134356   return rc;
134357 }
134358
134359 /*
134360 ** One of the cells in node pNode is guaranteed to have a 64-bit 
134361 ** integer value equal to iRowid. Return the index of this cell.
134362 */
134363 static int nodeRowidIndex(
134364   Rtree *pRtree, 
134365   RtreeNode *pNode, 
134366   i64 iRowid,
134367   int *piIndex
134368 ){
134369   int ii;
134370   int nCell = NCELL(pNode);
134371   for(ii=0; ii<nCell; ii++){
134372     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
134373       *piIndex = ii;
134374       return SQLITE_OK;
134375     }
134376   }
134377   return SQLITE_CORRUPT_VTAB;
134378 }
134379
134380 /*
134381 ** Return the index of the cell containing a pointer to node pNode
134382 ** in its parent. If pNode is the root node, return -1.
134383 */
134384 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
134385   RtreeNode *pParent = pNode->pParent;
134386   if( pParent ){
134387     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
134388   }
134389   *piIndex = -1;
134390   return SQLITE_OK;
134391 }
134392
134393 /* 
134394 ** Rtree virtual table module xNext method.
134395 */
134396 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
134397   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
134398   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
134399   int rc = SQLITE_OK;
134400
134401   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
134402   ** already at EOF. It is against the rules to call the xNext() method of
134403   ** a cursor that has already reached EOF.
134404   */
134405   assert( pCsr->pNode );
134406
134407   if( pCsr->iStrategy==1 ){
134408     /* This "scan" is a direct lookup by rowid. There is no next entry. */
134409     nodeRelease(pRtree, pCsr->pNode);
134410     pCsr->pNode = 0;
134411   }else{
134412     /* Move to the next entry that matches the configured constraints. */
134413     int iHeight = 0;
134414     while( pCsr->pNode ){
134415       RtreeNode *pNode = pCsr->pNode;
134416       int nCell = NCELL(pNode);
134417       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
134418         int isEof;
134419         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
134420         if( rc!=SQLITE_OK || !isEof ){
134421           return rc;
134422         }
134423       }
134424       pCsr->pNode = pNode->pParent;
134425       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
134426       if( rc!=SQLITE_OK ){
134427         return rc;
134428       }
134429       nodeReference(pCsr->pNode);
134430       nodeRelease(pRtree, pNode);
134431       iHeight++;
134432     }
134433   }
134434
134435   return rc;
134436 }
134437
134438 /* 
134439 ** Rtree virtual table module xRowid method.
134440 */
134441 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
134442   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
134443   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
134444
134445   assert(pCsr->pNode);
134446   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
134447
134448   return SQLITE_OK;
134449 }
134450
134451 /* 
134452 ** Rtree virtual table module xColumn method.
134453 */
134454 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
134455   Rtree *pRtree = (Rtree *)cur->pVtab;
134456   RtreeCursor *pCsr = (RtreeCursor *)cur;
134457
134458   if( i==0 ){
134459     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
134460     sqlite3_result_int64(ctx, iRowid);
134461   }else{
134462     RtreeCoord c;
134463     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
134464 #ifndef SQLITE_RTREE_INT_ONLY
134465     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
134466       sqlite3_result_double(ctx, c.f);
134467     }else
134468 #endif
134469     {
134470       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
134471       sqlite3_result_int(ctx, c.i);
134472     }
134473   }
134474
134475   return SQLITE_OK;
134476 }
134477
134478 /* 
134479 ** Use nodeAcquire() to obtain the leaf node containing the record with 
134480 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
134481 ** return SQLITE_OK. If there is no such record in the table, set
134482 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
134483 ** to zero and return an SQLite error code.
134484 */
134485 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
134486   int rc;
134487   *ppLeaf = 0;
134488   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
134489   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
134490     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
134491     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
134492     sqlite3_reset(pRtree->pReadRowid);
134493   }else{
134494     rc = sqlite3_reset(pRtree->pReadRowid);
134495   }
134496   return rc;
134497 }
134498
134499 /*
134500 ** This function is called to configure the RtreeConstraint object passed
134501 ** as the second argument for a MATCH constraint. The value passed as the
134502 ** first argument to this function is the right-hand operand to the MATCH
134503 ** operator.
134504 */
134505 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
134506   RtreeMatchArg *p;
134507   sqlite3_rtree_geometry *pGeom;
134508   int nBlob;
134509
134510   /* Check that value is actually a blob. */
134511   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
134512
134513   /* Check that the blob is roughly the right size. */
134514   nBlob = sqlite3_value_bytes(pValue);
134515   if( nBlob<(int)sizeof(RtreeMatchArg) 
134516    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
134517   ){
134518     return SQLITE_ERROR;
134519   }
134520
134521   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
134522       sizeof(sqlite3_rtree_geometry) + nBlob
134523   );
134524   if( !pGeom ) return SQLITE_NOMEM;
134525   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
134526   p = (RtreeMatchArg *)&pGeom[1];
134527
134528   memcpy(p, sqlite3_value_blob(pValue), nBlob);
134529   if( p->magic!=RTREE_GEOMETRY_MAGIC 
134530    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
134531   ){
134532     sqlite3_free(pGeom);
134533     return SQLITE_ERROR;
134534   }
134535
134536   pGeom->pContext = p->pContext;
134537   pGeom->nParam = p->nParam;
134538   pGeom->aParam = p->aParam;
134539
134540   pCons->xGeom = p->xGeom;
134541   pCons->pGeom = pGeom;
134542   return SQLITE_OK;
134543 }
134544
134545 /* 
134546 ** Rtree virtual table module xFilter method.
134547 */
134548 static int rtreeFilter(
134549   sqlite3_vtab_cursor *pVtabCursor, 
134550   int idxNum, const char *idxStr,
134551   int argc, sqlite3_value **argv
134552 ){
134553   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
134554   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
134555
134556   RtreeNode *pRoot = 0;
134557   int ii;
134558   int rc = SQLITE_OK;
134559
134560   rtreeReference(pRtree);
134561
134562   freeCursorConstraints(pCsr);
134563   pCsr->iStrategy = idxNum;
134564
134565   if( idxNum==1 ){
134566     /* Special case - lookup by rowid. */
134567     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
134568     i64 iRowid = sqlite3_value_int64(argv[0]);
134569     rc = findLeafNode(pRtree, iRowid, &pLeaf);
134570     pCsr->pNode = pLeaf; 
134571     if( pLeaf ){
134572       assert( rc==SQLITE_OK );
134573       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
134574     }
134575   }else{
134576     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
134577     ** with the configured constraints. 
134578     */
134579     if( argc>0 ){
134580       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
134581       pCsr->nConstraint = argc;
134582       if( !pCsr->aConstraint ){
134583         rc = SQLITE_NOMEM;
134584       }else{
134585         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
134586         assert( (idxStr==0 && argc==0)
134587                 || (idxStr && (int)strlen(idxStr)==argc*2) );
134588         for(ii=0; ii<argc; ii++){
134589           RtreeConstraint *p = &pCsr->aConstraint[ii];
134590           p->op = idxStr[ii*2];
134591           p->iCoord = idxStr[ii*2+1]-'a';
134592           if( p->op==RTREE_MATCH ){
134593             /* A MATCH operator. The right-hand-side must be a blob that
134594             ** can be cast into an RtreeMatchArg object. One created using
134595             ** an sqlite3_rtree_geometry_callback() SQL user function.
134596             */
134597             rc = deserializeGeometry(argv[ii], p);
134598             if( rc!=SQLITE_OK ){
134599               break;
134600             }
134601           }else{
134602 #ifdef SQLITE_RTREE_INT_ONLY
134603             p->rValue = sqlite3_value_int64(argv[ii]);
134604 #else
134605             p->rValue = sqlite3_value_double(argv[ii]);
134606 #endif
134607           }
134608         }
134609       }
134610     }
134611   
134612     if( rc==SQLITE_OK ){
134613       pCsr->pNode = 0;
134614       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
134615     }
134616     if( rc==SQLITE_OK ){
134617       int isEof = 1;
134618       int nCell = NCELL(pRoot);
134619       pCsr->pNode = pRoot;
134620       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
134621         assert( pCsr->pNode==pRoot );
134622         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
134623         if( !isEof ){
134624           break;
134625         }
134626       }
134627       if( rc==SQLITE_OK && isEof ){
134628         assert( pCsr->pNode==pRoot );
134629         nodeRelease(pRtree, pRoot);
134630         pCsr->pNode = 0;
134631       }
134632       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
134633     }
134634   }
134635
134636   rtreeRelease(pRtree);
134637   return rc;
134638 }
134639
134640 /*
134641 ** Rtree virtual table module xBestIndex method. There are three
134642 ** table scan strategies to choose from (in order from most to 
134643 ** least desirable):
134644 **
134645 **   idxNum     idxStr        Strategy
134646 **   ------------------------------------------------
134647 **     1        Unused        Direct lookup by rowid.
134648 **     2        See below     R-tree query or full-table scan.
134649 **   ------------------------------------------------
134650 **
134651 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
134652 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
134653 ** constraint used. The first two bytes of idxStr correspond to 
134654 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
134655 ** (argvIndex==1) etc.
134656 **
134657 ** The first of each pair of bytes in idxStr identifies the constraint
134658 ** operator as follows:
134659 **
134660 **   Operator    Byte Value
134661 **   ----------------------
134662 **      =        0x41 ('A')
134663 **     <=        0x42 ('B')
134664 **      <        0x43 ('C')
134665 **     >=        0x44 ('D')
134666 **      >        0x45 ('E')
134667 **   MATCH       0x46 ('F')
134668 **   ----------------------
134669 **
134670 ** The second of each pair of bytes identifies the coordinate column
134671 ** to which the constraint applies. The leftmost coordinate column
134672 ** is 'a', the second from the left 'b' etc.
134673 */
134674 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
134675   int rc = SQLITE_OK;
134676   int ii;
134677
134678   int iIdx = 0;
134679   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
134680   memset(zIdxStr, 0, sizeof(zIdxStr));
134681   UNUSED_PARAMETER(tab);
134682
134683   assert( pIdxInfo->idxStr==0 );
134684   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
134685     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
134686
134687     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
134688       /* We have an equality constraint on the rowid. Use strategy 1. */
134689       int jj;
134690       for(jj=0; jj<ii; jj++){
134691         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
134692         pIdxInfo->aConstraintUsage[jj].omit = 0;
134693       }
134694       pIdxInfo->idxNum = 1;
134695       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
134696       pIdxInfo->aConstraintUsage[jj].omit = 1;
134697
134698       /* This strategy involves a two rowid lookups on an B-Tree structures
134699       ** and then a linear search of an R-Tree node. This should be 
134700       ** considered almost as quick as a direct rowid lookup (for which 
134701       ** sqlite uses an internal cost of 0.0).
134702       */ 
134703       pIdxInfo->estimatedCost = 10.0;
134704       return SQLITE_OK;
134705     }
134706
134707     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
134708       u8 op;
134709       switch( p->op ){
134710         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
134711         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
134712         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
134713         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
134714         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
134715         default:
134716           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
134717           op = RTREE_MATCH; 
134718           break;
134719       }
134720       zIdxStr[iIdx++] = op;
134721       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
134722       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
134723       pIdxInfo->aConstraintUsage[ii].omit = 1;
134724     }
134725   }
134726
134727   pIdxInfo->idxNum = 2;
134728   pIdxInfo->needToFreeIdxStr = 1;
134729   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
134730     return SQLITE_NOMEM;
134731   }
134732   assert( iIdx>=0 );
134733   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
134734   return rc;
134735 }
134736
134737 /*
134738 ** Return the N-dimensional volumn of the cell stored in *p.
134739 */
134740 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
134741   RtreeDValue area = (RtreeDValue)1;
134742   int ii;
134743   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
134744     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
134745   }
134746   return area;
134747 }
134748
134749 /*
134750 ** Return the margin length of cell p. The margin length is the sum
134751 ** of the objects size in each dimension.
134752 */
134753 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
134754   RtreeDValue margin = (RtreeDValue)0;
134755   int ii;
134756   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
134757     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
134758   }
134759   return margin;
134760 }
134761
134762 /*
134763 ** Store the union of cells p1 and p2 in p1.
134764 */
134765 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
134766   int ii;
134767   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
134768     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
134769       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
134770       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
134771     }
134772   }else{
134773     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
134774       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
134775       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
134776     }
134777   }
134778 }
134779
134780 /*
134781 ** Return true if the area covered by p2 is a subset of the area covered
134782 ** by p1. False otherwise.
134783 */
134784 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
134785   int ii;
134786   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
134787   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
134788     RtreeCoord *a1 = &p1->aCoord[ii];
134789     RtreeCoord *a2 = &p2->aCoord[ii];
134790     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
134791      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
134792     ){
134793       return 0;
134794     }
134795   }
134796   return 1;
134797 }
134798
134799 /*
134800 ** Return the amount cell p would grow by if it were unioned with pCell.
134801 */
134802 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
134803   RtreeDValue area;
134804   RtreeCell cell;
134805   memcpy(&cell, p, sizeof(RtreeCell));
134806   area = cellArea(pRtree, &cell);
134807   cellUnion(pRtree, &cell, pCell);
134808   return (cellArea(pRtree, &cell)-area);
134809 }
134810
134811 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
134812 static RtreeDValue cellOverlap(
134813   Rtree *pRtree, 
134814   RtreeCell *p, 
134815   RtreeCell *aCell, 
134816   int nCell, 
134817   int iExclude
134818 ){
134819   int ii;
134820   RtreeDValue overlap = 0.0;
134821   for(ii=0; ii<nCell; ii++){
134822 #if VARIANT_RSTARTREE_CHOOSESUBTREE
134823     if( ii!=iExclude )
134824 #else
134825     assert( iExclude==-1 );
134826     UNUSED_PARAMETER(iExclude);
134827 #endif
134828     {
134829       int jj;
134830       RtreeDValue o = (RtreeDValue)1;
134831       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
134832         RtreeDValue x1, x2;
134833
134834         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
134835         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
134836
134837         if( x2<x1 ){
134838           o = 0.0;
134839           break;
134840         }else{
134841           o = o * (x2-x1);
134842         }
134843       }
134844       overlap += o;
134845     }
134846   }
134847   return overlap;
134848 }
134849 #endif
134850
134851 #if VARIANT_RSTARTREE_CHOOSESUBTREE
134852 static RtreeDValue cellOverlapEnlargement(
134853   Rtree *pRtree, 
134854   RtreeCell *p, 
134855   RtreeCell *pInsert, 
134856   RtreeCell *aCell, 
134857   int nCell, 
134858   int iExclude
134859 ){
134860   RtreeDValue before, after;
134861   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
134862   cellUnion(pRtree, p, pInsert);
134863   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
134864   return (after-before);
134865 }
134866 #endif
134867
134868
134869 /*
134870 ** This function implements the ChooseLeaf algorithm from Gutman[84].
134871 ** ChooseSubTree in r*tree terminology.
134872 */
134873 static int ChooseLeaf(
134874   Rtree *pRtree,               /* Rtree table */
134875   RtreeCell *pCell,            /* Cell to insert into rtree */
134876   int iHeight,                 /* Height of sub-tree rooted at pCell */
134877   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
134878 ){
134879   int rc;
134880   int ii;
134881   RtreeNode *pNode;
134882   rc = nodeAcquire(pRtree, 1, 0, &pNode);
134883
134884   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
134885     int iCell;
134886     sqlite3_int64 iBest = 0;
134887
134888     RtreeDValue fMinGrowth = 0.0;
134889     RtreeDValue fMinArea = 0.0;
134890 #if VARIANT_RSTARTREE_CHOOSESUBTREE
134891     RtreeDValue fMinOverlap = 0.0;
134892     RtreeDValue overlap;
134893 #endif
134894
134895     int nCell = NCELL(pNode);
134896     RtreeCell cell;
134897     RtreeNode *pChild;
134898
134899     RtreeCell *aCell = 0;
134900
134901 #if VARIANT_RSTARTREE_CHOOSESUBTREE
134902     if( ii==(pRtree->iDepth-1) ){
134903       int jj;
134904       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
134905       if( !aCell ){
134906         rc = SQLITE_NOMEM;
134907         nodeRelease(pRtree, pNode);
134908         pNode = 0;
134909         continue;
134910       }
134911       for(jj=0; jj<nCell; jj++){
134912         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
134913       }
134914     }
134915 #endif
134916
134917     /* Select the child node which will be enlarged the least if pCell
134918     ** is inserted into it. Resolve ties by choosing the entry with
134919     ** the smallest area.
134920     */
134921     for(iCell=0; iCell<nCell; iCell++){
134922       int bBest = 0;
134923       RtreeDValue growth;
134924       RtreeDValue area;
134925       nodeGetCell(pRtree, pNode, iCell, &cell);
134926       growth = cellGrowth(pRtree, &cell, pCell);
134927       area = cellArea(pRtree, &cell);
134928
134929 #if VARIANT_RSTARTREE_CHOOSESUBTREE
134930       if( ii==(pRtree->iDepth-1) ){
134931         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
134932       }else{
134933         overlap = 0.0;
134934       }
134935       if( (iCell==0) 
134936        || (overlap<fMinOverlap) 
134937        || (overlap==fMinOverlap && growth<fMinGrowth)
134938        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
134939       ){
134940         bBest = 1;
134941         fMinOverlap = overlap;
134942       }
134943 #else
134944       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
134945         bBest = 1;
134946       }
134947 #endif
134948       if( bBest ){
134949         fMinGrowth = growth;
134950         fMinArea = area;
134951         iBest = cell.iRowid;
134952       }
134953     }
134954
134955     sqlite3_free(aCell);
134956     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
134957     nodeRelease(pRtree, pNode);
134958     pNode = pChild;
134959   }
134960
134961   *ppLeaf = pNode;
134962   return rc;
134963 }
134964
134965 /*
134966 ** A cell with the same content as pCell has just been inserted into
134967 ** the node pNode. This function updates the bounding box cells in
134968 ** all ancestor elements.
134969 */
134970 static int AdjustTree(
134971   Rtree *pRtree,                    /* Rtree table */
134972   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
134973   RtreeCell *pCell                  /* This cell was just inserted */
134974 ){
134975   RtreeNode *p = pNode;
134976   while( p->pParent ){
134977     RtreeNode *pParent = p->pParent;
134978     RtreeCell cell;
134979     int iCell;
134980
134981     if( nodeParentIndex(pRtree, p, &iCell) ){
134982       return SQLITE_CORRUPT_VTAB;
134983     }
134984
134985     nodeGetCell(pRtree, pParent, iCell, &cell);
134986     if( !cellContains(pRtree, &cell, pCell) ){
134987       cellUnion(pRtree, &cell, pCell);
134988       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
134989     }
134990  
134991     p = pParent;
134992   }
134993   return SQLITE_OK;
134994 }
134995
134996 /*
134997 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
134998 */
134999 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
135000   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
135001   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
135002   sqlite3_step(pRtree->pWriteRowid);
135003   return sqlite3_reset(pRtree->pWriteRowid);
135004 }
135005
135006 /*
135007 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
135008 */
135009 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
135010   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
135011   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
135012   sqlite3_step(pRtree->pWriteParent);
135013   return sqlite3_reset(pRtree->pWriteParent);
135014 }
135015
135016 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
135017
135018 #if VARIANT_GUTTMAN_LINEAR_SPLIT
135019 /*
135020 ** Implementation of the linear variant of the PickNext() function from
135021 ** Guttman[84].
135022 */
135023 static RtreeCell *LinearPickNext(
135024   Rtree *pRtree,
135025   RtreeCell *aCell, 
135026   int nCell, 
135027   RtreeCell *pLeftBox, 
135028   RtreeCell *pRightBox,
135029   int *aiUsed
135030 ){
135031   int ii;
135032   for(ii=0; aiUsed[ii]; ii++);
135033   aiUsed[ii] = 1;
135034   return &aCell[ii];
135035 }
135036
135037 /*
135038 ** Implementation of the linear variant of the PickSeeds() function from
135039 ** Guttman[84].
135040 */
135041 static void LinearPickSeeds(
135042   Rtree *pRtree,
135043   RtreeCell *aCell, 
135044   int nCell, 
135045   int *piLeftSeed, 
135046   int *piRightSeed
135047 ){
135048   int i;
135049   int iLeftSeed = 0;
135050   int iRightSeed = 1;
135051   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
135052
135053   /* Pick two "seed" cells from the array of cells. The algorithm used
135054   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
135055   ** indices of the two seed cells in the array are stored in local
135056   ** variables iLeftSeek and iRightSeed.
135057   */
135058   for(i=0; i<pRtree->nDim; i++){
135059     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
135060     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
135061     RtreeDValue x3 = x1;
135062     RtreeDValue x4 = x2;
135063     int jj;
135064
135065     int iCellLeft = 0;
135066     int iCellRight = 0;
135067
135068     for(jj=1; jj<nCell; jj++){
135069       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
135070       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
135071
135072       if( left<x1 ) x1 = left;
135073       if( right>x4 ) x4 = right;
135074       if( left>x3 ){
135075         x3 = left;
135076         iCellRight = jj;
135077       }
135078       if( right<x2 ){
135079         x2 = right;
135080         iCellLeft = jj;
135081       }
135082     }
135083
135084     if( x4!=x1 ){
135085       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
135086       if( normalwidth>maxNormalInnerWidth ){
135087         iLeftSeed = iCellLeft;
135088         iRightSeed = iCellRight;
135089       }
135090     }
135091   }
135092
135093   *piLeftSeed = iLeftSeed;
135094   *piRightSeed = iRightSeed;
135095 }
135096 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
135097
135098 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
135099 /*
135100 ** Implementation of the quadratic variant of the PickNext() function from
135101 ** Guttman[84].
135102 */
135103 static RtreeCell *QuadraticPickNext(
135104   Rtree *pRtree,
135105   RtreeCell *aCell, 
135106   int nCell, 
135107   RtreeCell *pLeftBox, 
135108   RtreeCell *pRightBox,
135109   int *aiUsed
135110 ){
135111   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
135112
135113   int iSelect = -1;
135114   RtreeDValue fDiff;
135115   int ii;
135116   for(ii=0; ii<nCell; ii++){
135117     if( aiUsed[ii]==0 ){
135118       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135119       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135120       RtreeDValue diff = FABS(right-left);
135121       if( iSelect<0 || diff>fDiff ){
135122         fDiff = diff;
135123         iSelect = ii;
135124       }
135125     }
135126   }
135127   aiUsed[iSelect] = 1;
135128   return &aCell[iSelect];
135129 }
135130
135131 /*
135132 ** Implementation of the quadratic variant of the PickSeeds() function from
135133 ** Guttman[84].
135134 */
135135 static void QuadraticPickSeeds(
135136   Rtree *pRtree,
135137   RtreeCell *aCell, 
135138   int nCell, 
135139   int *piLeftSeed, 
135140   int *piRightSeed
135141 ){
135142   int ii;
135143   int jj;
135144
135145   int iLeftSeed = 0;
135146   int iRightSeed = 1;
135147   RtreeDValue fWaste = 0.0;
135148
135149   for(ii=0; ii<nCell; ii++){
135150     for(jj=ii+1; jj<nCell; jj++){
135151       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
135152       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
135153       RtreeDValue waste = growth - right;
135154
135155       if( waste>fWaste ){
135156         iLeftSeed = ii;
135157         iRightSeed = jj;
135158         fWaste = waste;
135159       }
135160     }
135161   }
135162
135163   *piLeftSeed = iLeftSeed;
135164   *piRightSeed = iRightSeed;
135165 }
135166 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
135167
135168 /*
135169 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
135170 ** nIdx. The aIdx array contains the set of integers from 0 to 
135171 ** (nIdx-1) in no particular order. This function sorts the values
135172 ** in aIdx according to the indexed values in aDistance. For
135173 ** example, assuming the inputs:
135174 **
135175 **   aIdx      = { 0,   1,   2,   3 }
135176 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
135177 **
135178 ** this function sets the aIdx array to contain:
135179 **
135180 **   aIdx      = { 0,   1,   2,   3 }
135181 **
135182 ** The aSpare array is used as temporary working space by the
135183 ** sorting algorithm.
135184 */
135185 static void SortByDistance(
135186   int *aIdx, 
135187   int nIdx, 
135188   RtreeDValue *aDistance, 
135189   int *aSpare
135190 ){
135191   if( nIdx>1 ){
135192     int iLeft = 0;
135193     int iRight = 0;
135194
135195     int nLeft = nIdx/2;
135196     int nRight = nIdx-nLeft;
135197     int *aLeft = aIdx;
135198     int *aRight = &aIdx[nLeft];
135199
135200     SortByDistance(aLeft, nLeft, aDistance, aSpare);
135201     SortByDistance(aRight, nRight, aDistance, aSpare);
135202
135203     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135204     aLeft = aSpare;
135205
135206     while( iLeft<nLeft || iRight<nRight ){
135207       if( iLeft==nLeft ){
135208         aIdx[iLeft+iRight] = aRight[iRight];
135209         iRight++;
135210       }else if( iRight==nRight ){
135211         aIdx[iLeft+iRight] = aLeft[iLeft];
135212         iLeft++;
135213       }else{
135214         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
135215         RtreeDValue fRight = aDistance[aRight[iRight]];
135216         if( fLeft<fRight ){
135217           aIdx[iLeft+iRight] = aLeft[iLeft];
135218           iLeft++;
135219         }else{
135220           aIdx[iLeft+iRight] = aRight[iRight];
135221           iRight++;
135222         }
135223       }
135224     }
135225
135226 #if 0
135227     /* Check that the sort worked */
135228     {
135229       int jj;
135230       for(jj=1; jj<nIdx; jj++){
135231         RtreeDValue left = aDistance[aIdx[jj-1]];
135232         RtreeDValue right = aDistance[aIdx[jj]];
135233         assert( left<=right );
135234       }
135235     }
135236 #endif
135237   }
135238 }
135239
135240 /*
135241 ** Arguments aIdx, aCell and aSpare all point to arrays of size
135242 ** nIdx. The aIdx array contains the set of integers from 0 to 
135243 ** (nIdx-1) in no particular order. This function sorts the values
135244 ** in aIdx according to dimension iDim of the cells in aCell. The
135245 ** minimum value of dimension iDim is considered first, the
135246 ** maximum used to break ties.
135247 **
135248 ** The aSpare array is used as temporary working space by the
135249 ** sorting algorithm.
135250 */
135251 static void SortByDimension(
135252   Rtree *pRtree,
135253   int *aIdx, 
135254   int nIdx, 
135255   int iDim, 
135256   RtreeCell *aCell, 
135257   int *aSpare
135258 ){
135259   if( nIdx>1 ){
135260
135261     int iLeft = 0;
135262     int iRight = 0;
135263
135264     int nLeft = nIdx/2;
135265     int nRight = nIdx-nLeft;
135266     int *aLeft = aIdx;
135267     int *aRight = &aIdx[nLeft];
135268
135269     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
135270     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
135271
135272     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135273     aLeft = aSpare;
135274     while( iLeft<nLeft || iRight<nRight ){
135275       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
135276       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
135277       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
135278       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
135279       if( (iLeft!=nLeft) && ((iRight==nRight)
135280        || (xleft1<xright1)
135281        || (xleft1==xright1 && xleft2<xright2)
135282       )){
135283         aIdx[iLeft+iRight] = aLeft[iLeft];
135284         iLeft++;
135285       }else{
135286         aIdx[iLeft+iRight] = aRight[iRight];
135287         iRight++;
135288       }
135289     }
135290
135291 #if 0
135292     /* Check that the sort worked */
135293     {
135294       int jj;
135295       for(jj=1; jj<nIdx; jj++){
135296         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
135297         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
135298         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
135299         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
135300         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
135301       }
135302     }
135303 #endif
135304   }
135305 }
135306
135307 #if VARIANT_RSTARTREE_SPLIT
135308 /*
135309 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
135310 */
135311 static int splitNodeStartree(
135312   Rtree *pRtree,
135313   RtreeCell *aCell,
135314   int nCell,
135315   RtreeNode *pLeft,
135316   RtreeNode *pRight,
135317   RtreeCell *pBboxLeft,
135318   RtreeCell *pBboxRight
135319 ){
135320   int **aaSorted;
135321   int *aSpare;
135322   int ii;
135323
135324   int iBestDim = 0;
135325   int iBestSplit = 0;
135326   RtreeDValue fBestMargin = 0.0;
135327
135328   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
135329
135330   aaSorted = (int **)sqlite3_malloc(nByte);
135331   if( !aaSorted ){
135332     return SQLITE_NOMEM;
135333   }
135334
135335   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
135336   memset(aaSorted, 0, nByte);
135337   for(ii=0; ii<pRtree->nDim; ii++){
135338     int jj;
135339     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
135340     for(jj=0; jj<nCell; jj++){
135341       aaSorted[ii][jj] = jj;
135342     }
135343     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
135344   }
135345
135346   for(ii=0; ii<pRtree->nDim; ii++){
135347     RtreeDValue margin = 0.0;
135348     RtreeDValue fBestOverlap = 0.0;
135349     RtreeDValue fBestArea = 0.0;
135350     int iBestLeft = 0;
135351     int nLeft;
135352
135353     for(
135354       nLeft=RTREE_MINCELLS(pRtree); 
135355       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
135356       nLeft++
135357     ){
135358       RtreeCell left;
135359       RtreeCell right;
135360       int kk;
135361       RtreeDValue overlap;
135362       RtreeDValue area;
135363
135364       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
135365       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
135366       for(kk=1; kk<(nCell-1); kk++){
135367         if( kk<nLeft ){
135368           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
135369         }else{
135370           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
135371         }
135372       }
135373       margin += cellMargin(pRtree, &left);
135374       margin += cellMargin(pRtree, &right);
135375       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
135376       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
135377       if( (nLeft==RTREE_MINCELLS(pRtree))
135378        || (overlap<fBestOverlap)
135379        || (overlap==fBestOverlap && area<fBestArea)
135380       ){
135381         iBestLeft = nLeft;
135382         fBestOverlap = overlap;
135383         fBestArea = area;
135384       }
135385     }
135386
135387     if( ii==0 || margin<fBestMargin ){
135388       iBestDim = ii;
135389       fBestMargin = margin;
135390       iBestSplit = iBestLeft;
135391     }
135392   }
135393
135394   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
135395   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
135396   for(ii=0; ii<nCell; ii++){
135397     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
135398     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
135399     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
135400     nodeInsertCell(pRtree, pTarget, pCell);
135401     cellUnion(pRtree, pBbox, pCell);
135402   }
135403
135404   sqlite3_free(aaSorted);
135405   return SQLITE_OK;
135406 }
135407 #endif
135408
135409 #if VARIANT_GUTTMAN_SPLIT
135410 /*
135411 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
135412 */
135413 static int splitNodeGuttman(
135414   Rtree *pRtree,
135415   RtreeCell *aCell,
135416   int nCell,
135417   RtreeNode *pLeft,
135418   RtreeNode *pRight,
135419   RtreeCell *pBboxLeft,
135420   RtreeCell *pBboxRight
135421 ){
135422   int iLeftSeed = 0;
135423   int iRightSeed = 1;
135424   int *aiUsed;
135425   int i;
135426
135427   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
135428   if( !aiUsed ){
135429     return SQLITE_NOMEM;
135430   }
135431   memset(aiUsed, 0, sizeof(int)*nCell);
135432
135433   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
135434
135435   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
135436   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
135437   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
135438   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
135439   aiUsed[iLeftSeed] = 1;
135440   aiUsed[iRightSeed] = 1;
135441
135442   for(i=nCell-2; i>0; i--){
135443     RtreeCell *pNext;
135444     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
135445     RtreeDValue diff =  
135446       cellGrowth(pRtree, pBboxLeft, pNext) - 
135447       cellGrowth(pRtree, pBboxRight, pNext)
135448     ;
135449     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
135450      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
135451     ){
135452       nodeInsertCell(pRtree, pRight, pNext);
135453       cellUnion(pRtree, pBboxRight, pNext);
135454     }else{
135455       nodeInsertCell(pRtree, pLeft, pNext);
135456       cellUnion(pRtree, pBboxLeft, pNext);
135457     }
135458   }
135459
135460   sqlite3_free(aiUsed);
135461   return SQLITE_OK;
135462 }
135463 #endif
135464
135465 static int updateMapping(
135466   Rtree *pRtree, 
135467   i64 iRowid, 
135468   RtreeNode *pNode, 
135469   int iHeight
135470 ){
135471   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
135472   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
135473   if( iHeight>0 ){
135474     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
135475     if( pChild ){
135476       nodeRelease(pRtree, pChild->pParent);
135477       nodeReference(pNode);
135478       pChild->pParent = pNode;
135479     }
135480   }
135481   return xSetMapping(pRtree, iRowid, pNode->iNode);
135482 }
135483
135484 static int SplitNode(
135485   Rtree *pRtree,
135486   RtreeNode *pNode,
135487   RtreeCell *pCell,
135488   int iHeight
135489 ){
135490   int i;
135491   int newCellIsRight = 0;
135492
135493   int rc = SQLITE_OK;
135494   int nCell = NCELL(pNode);
135495   RtreeCell *aCell;
135496   int *aiUsed;
135497
135498   RtreeNode *pLeft = 0;
135499   RtreeNode *pRight = 0;
135500
135501   RtreeCell leftbbox;
135502   RtreeCell rightbbox;
135503
135504   /* Allocate an array and populate it with a copy of pCell and 
135505   ** all cells from node pLeft. Then zero the original node.
135506   */
135507   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
135508   if( !aCell ){
135509     rc = SQLITE_NOMEM;
135510     goto splitnode_out;
135511   }
135512   aiUsed = (int *)&aCell[nCell+1];
135513   memset(aiUsed, 0, sizeof(int)*(nCell+1));
135514   for(i=0; i<nCell; i++){
135515     nodeGetCell(pRtree, pNode, i, &aCell[i]);
135516   }
135517   nodeZero(pRtree, pNode);
135518   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
135519   nCell++;
135520
135521   if( pNode->iNode==1 ){
135522     pRight = nodeNew(pRtree, pNode);
135523     pLeft = nodeNew(pRtree, pNode);
135524     pRtree->iDepth++;
135525     pNode->isDirty = 1;
135526     writeInt16(pNode->zData, pRtree->iDepth);
135527   }else{
135528     pLeft = pNode;
135529     pRight = nodeNew(pRtree, pLeft->pParent);
135530     nodeReference(pLeft);
135531   }
135532
135533   if( !pLeft || !pRight ){
135534     rc = SQLITE_NOMEM;
135535     goto splitnode_out;
135536   }
135537
135538   memset(pLeft->zData, 0, pRtree->iNodeSize);
135539   memset(pRight->zData, 0, pRtree->iNodeSize);
135540
135541   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
135542   if( rc!=SQLITE_OK ){
135543     goto splitnode_out;
135544   }
135545
135546   /* Ensure both child nodes have node numbers assigned to them by calling
135547   ** nodeWrite(). Node pRight always needs a node number, as it was created
135548   ** by nodeNew() above. But node pLeft sometimes already has a node number.
135549   ** In this case avoid the all to nodeWrite().
135550   */
135551   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
135552    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
135553   ){
135554     goto splitnode_out;
135555   }
135556
135557   rightbbox.iRowid = pRight->iNode;
135558   leftbbox.iRowid = pLeft->iNode;
135559
135560   if( pNode->iNode==1 ){
135561     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
135562     if( rc!=SQLITE_OK ){
135563       goto splitnode_out;
135564     }
135565   }else{
135566     RtreeNode *pParent = pLeft->pParent;
135567     int iCell;
135568     rc = nodeParentIndex(pRtree, pLeft, &iCell);
135569     if( rc==SQLITE_OK ){
135570       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
135571       rc = AdjustTree(pRtree, pParent, &leftbbox);
135572     }
135573     if( rc!=SQLITE_OK ){
135574       goto splitnode_out;
135575     }
135576   }
135577   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
135578     goto splitnode_out;
135579   }
135580
135581   for(i=0; i<NCELL(pRight); i++){
135582     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
135583     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
135584     if( iRowid==pCell->iRowid ){
135585       newCellIsRight = 1;
135586     }
135587     if( rc!=SQLITE_OK ){
135588       goto splitnode_out;
135589     }
135590   }
135591   if( pNode->iNode==1 ){
135592     for(i=0; i<NCELL(pLeft); i++){
135593       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
135594       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
135595       if( rc!=SQLITE_OK ){
135596         goto splitnode_out;
135597       }
135598     }
135599   }else if( newCellIsRight==0 ){
135600     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
135601   }
135602
135603   if( rc==SQLITE_OK ){
135604     rc = nodeRelease(pRtree, pRight);
135605     pRight = 0;
135606   }
135607   if( rc==SQLITE_OK ){
135608     rc = nodeRelease(pRtree, pLeft);
135609     pLeft = 0;
135610   }
135611
135612 splitnode_out:
135613   nodeRelease(pRtree, pRight);
135614   nodeRelease(pRtree, pLeft);
135615   sqlite3_free(aCell);
135616   return rc;
135617 }
135618
135619 /*
135620 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
135621 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
135622 ** the pLeaf->pParent chain all the way up to the root node.
135623 **
135624 ** This operation is required when a row is deleted (or updated - an update
135625 ** is implemented as a delete followed by an insert). SQLite provides the
135626 ** rowid of the row to delete, which can be used to find the leaf on which
135627 ** the entry resides (argument pLeaf). Once the leaf is located, this 
135628 ** function is called to determine its ancestry.
135629 */
135630 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
135631   int rc = SQLITE_OK;
135632   RtreeNode *pChild = pLeaf;
135633   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
135634     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
135635     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
135636     rc = sqlite3_step(pRtree->pReadParent);
135637     if( rc==SQLITE_ROW ){
135638       RtreeNode *pTest;           /* Used to test for reference loops */
135639       i64 iNode;                  /* Node number of parent node */
135640
135641       /* Before setting pChild->pParent, test that we are not creating a
135642       ** loop of references (as we would if, say, pChild==pParent). We don't
135643       ** want to do this as it leads to a memory leak when trying to delete
135644       ** the referenced counted node structures.
135645       */
135646       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
135647       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
135648       if( !pTest ){
135649         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
135650       }
135651     }
135652     rc = sqlite3_reset(pRtree->pReadParent);
135653     if( rc==SQLITE_OK ) rc = rc2;
135654     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
135655     pChild = pChild->pParent;
135656   }
135657   return rc;
135658 }
135659
135660 static int deleteCell(Rtree *, RtreeNode *, int, int);
135661
135662 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
135663   int rc;
135664   int rc2;
135665   RtreeNode *pParent = 0;
135666   int iCell;
135667
135668   assert( pNode->nRef==1 );
135669
135670   /* Remove the entry in the parent cell. */
135671   rc = nodeParentIndex(pRtree, pNode, &iCell);
135672   if( rc==SQLITE_OK ){
135673     pParent = pNode->pParent;
135674     pNode->pParent = 0;
135675     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
135676   }
135677   rc2 = nodeRelease(pRtree, pParent);
135678   if( rc==SQLITE_OK ){
135679     rc = rc2;
135680   }
135681   if( rc!=SQLITE_OK ){
135682     return rc;
135683   }
135684
135685   /* Remove the xxx_node entry. */
135686   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
135687   sqlite3_step(pRtree->pDeleteNode);
135688   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
135689     return rc;
135690   }
135691
135692   /* Remove the xxx_parent entry. */
135693   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
135694   sqlite3_step(pRtree->pDeleteParent);
135695   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
135696     return rc;
135697   }
135698   
135699   /* Remove the node from the in-memory hash table and link it into
135700   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
135701   */
135702   nodeHashDelete(pRtree, pNode);
135703   pNode->iNode = iHeight;
135704   pNode->pNext = pRtree->pDeleted;
135705   pNode->nRef++;
135706   pRtree->pDeleted = pNode;
135707
135708   return SQLITE_OK;
135709 }
135710
135711 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
135712   RtreeNode *pParent = pNode->pParent;
135713   int rc = SQLITE_OK; 
135714   if( pParent ){
135715     int ii; 
135716     int nCell = NCELL(pNode);
135717     RtreeCell box;                            /* Bounding box for pNode */
135718     nodeGetCell(pRtree, pNode, 0, &box);
135719     for(ii=1; ii<nCell; ii++){
135720       RtreeCell cell;
135721       nodeGetCell(pRtree, pNode, ii, &cell);
135722       cellUnion(pRtree, &box, &cell);
135723     }
135724     box.iRowid = pNode->iNode;
135725     rc = nodeParentIndex(pRtree, pNode, &ii);
135726     if( rc==SQLITE_OK ){
135727       nodeOverwriteCell(pRtree, pParent, &box, ii);
135728       rc = fixBoundingBox(pRtree, pParent);
135729     }
135730   }
135731   return rc;
135732 }
135733
135734 /*
135735 ** Delete the cell at index iCell of node pNode. After removing the
135736 ** cell, adjust the r-tree data structure if required.
135737 */
135738 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
135739   RtreeNode *pParent;
135740   int rc;
135741
135742   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
135743     return rc;
135744   }
135745
135746   /* Remove the cell from the node. This call just moves bytes around
135747   ** the in-memory node image, so it cannot fail.
135748   */
135749   nodeDeleteCell(pRtree, pNode, iCell);
135750
135751   /* If the node is not the tree root and now has less than the minimum
135752   ** number of cells, remove it from the tree. Otherwise, update the
135753   ** cell in the parent node so that it tightly contains the updated
135754   ** node.
135755   */
135756   pParent = pNode->pParent;
135757   assert( pParent || pNode->iNode==1 );
135758   if( pParent ){
135759     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
135760       rc = removeNode(pRtree, pNode, iHeight);
135761     }else{
135762       rc = fixBoundingBox(pRtree, pNode);
135763     }
135764   }
135765
135766   return rc;
135767 }
135768
135769 static int Reinsert(
135770   Rtree *pRtree, 
135771   RtreeNode *pNode, 
135772   RtreeCell *pCell, 
135773   int iHeight
135774 ){
135775   int *aOrder;
135776   int *aSpare;
135777   RtreeCell *aCell;
135778   RtreeDValue *aDistance;
135779   int nCell;
135780   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
135781   int iDim;
135782   int ii;
135783   int rc = SQLITE_OK;
135784   int n;
135785
135786   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
135787
135788   nCell = NCELL(pNode)+1;
135789   n = (nCell+1)&(~1);
135790
135791   /* Allocate the buffers used by this operation. The allocation is
135792   ** relinquished before this function returns.
135793   */
135794   aCell = (RtreeCell *)sqlite3_malloc(n * (
135795     sizeof(RtreeCell)     +         /* aCell array */
135796     sizeof(int)           +         /* aOrder array */
135797     sizeof(int)           +         /* aSpare array */
135798     sizeof(RtreeDValue)             /* aDistance array */
135799   ));
135800   if( !aCell ){
135801     return SQLITE_NOMEM;
135802   }
135803   aOrder    = (int *)&aCell[n];
135804   aSpare    = (int *)&aOrder[n];
135805   aDistance = (RtreeDValue *)&aSpare[n];
135806
135807   for(ii=0; ii<nCell; ii++){
135808     if( ii==(nCell-1) ){
135809       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
135810     }else{
135811       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
135812     }
135813     aOrder[ii] = ii;
135814     for(iDim=0; iDim<pRtree->nDim; iDim++){
135815       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
135816       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
135817     }
135818   }
135819   for(iDim=0; iDim<pRtree->nDim; iDim++){
135820     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
135821   }
135822
135823   for(ii=0; ii<nCell; ii++){
135824     aDistance[ii] = 0.0;
135825     for(iDim=0; iDim<pRtree->nDim; iDim++){
135826       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
135827                                DCOORD(aCell[ii].aCoord[iDim*2]));
135828       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
135829     }
135830   }
135831
135832   SortByDistance(aOrder, nCell, aDistance, aSpare);
135833   nodeZero(pRtree, pNode);
135834
135835   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
135836     RtreeCell *p = &aCell[aOrder[ii]];
135837     nodeInsertCell(pRtree, pNode, p);
135838     if( p->iRowid==pCell->iRowid ){
135839       if( iHeight==0 ){
135840         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
135841       }else{
135842         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
135843       }
135844     }
135845   }
135846   if( rc==SQLITE_OK ){
135847     rc = fixBoundingBox(pRtree, pNode);
135848   }
135849   for(; rc==SQLITE_OK && ii<nCell; ii++){
135850     /* Find a node to store this cell in. pNode->iNode currently contains
135851     ** the height of the sub-tree headed by the cell.
135852     */
135853     RtreeNode *pInsert;
135854     RtreeCell *p = &aCell[aOrder[ii]];
135855     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
135856     if( rc==SQLITE_OK ){
135857       int rc2;
135858       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
135859       rc2 = nodeRelease(pRtree, pInsert);
135860       if( rc==SQLITE_OK ){
135861         rc = rc2;
135862       }
135863     }
135864   }
135865
135866   sqlite3_free(aCell);
135867   return rc;
135868 }
135869
135870 /*
135871 ** Insert cell pCell into node pNode. Node pNode is the head of a 
135872 ** subtree iHeight high (leaf nodes have iHeight==0).
135873 */
135874 static int rtreeInsertCell(
135875   Rtree *pRtree,
135876   RtreeNode *pNode,
135877   RtreeCell *pCell,
135878   int iHeight
135879 ){
135880   int rc = SQLITE_OK;
135881   if( iHeight>0 ){
135882     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
135883     if( pChild ){
135884       nodeRelease(pRtree, pChild->pParent);
135885       nodeReference(pNode);
135886       pChild->pParent = pNode;
135887     }
135888   }
135889   if( nodeInsertCell(pRtree, pNode, pCell) ){
135890 #if VARIANT_RSTARTREE_REINSERT
135891     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
135892       rc = SplitNode(pRtree, pNode, pCell, iHeight);
135893     }else{
135894       pRtree->iReinsertHeight = iHeight;
135895       rc = Reinsert(pRtree, pNode, pCell, iHeight);
135896     }
135897 #else
135898     rc = SplitNode(pRtree, pNode, pCell, iHeight);
135899 #endif
135900   }else{
135901     rc = AdjustTree(pRtree, pNode, pCell);
135902     if( rc==SQLITE_OK ){
135903       if( iHeight==0 ){
135904         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
135905       }else{
135906         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
135907       }
135908     }
135909   }
135910   return rc;
135911 }
135912
135913 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
135914   int ii;
135915   int rc = SQLITE_OK;
135916   int nCell = NCELL(pNode);
135917
135918   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
135919     RtreeNode *pInsert;
135920     RtreeCell cell;
135921     nodeGetCell(pRtree, pNode, ii, &cell);
135922
135923     /* Find a node to store this cell in. pNode->iNode currently contains
135924     ** the height of the sub-tree headed by the cell.
135925     */
135926     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
135927     if( rc==SQLITE_OK ){
135928       int rc2;
135929       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
135930       rc2 = nodeRelease(pRtree, pInsert);
135931       if( rc==SQLITE_OK ){
135932         rc = rc2;
135933       }
135934     }
135935   }
135936   return rc;
135937 }
135938
135939 /*
135940 ** Select a currently unused rowid for a new r-tree record.
135941 */
135942 static int newRowid(Rtree *pRtree, i64 *piRowid){
135943   int rc;
135944   sqlite3_bind_null(pRtree->pWriteRowid, 1);
135945   sqlite3_bind_null(pRtree->pWriteRowid, 2);
135946   sqlite3_step(pRtree->pWriteRowid);
135947   rc = sqlite3_reset(pRtree->pWriteRowid);
135948   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
135949   return rc;
135950 }
135951
135952 /*
135953 ** Remove the entry with rowid=iDelete from the r-tree structure.
135954 */
135955 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
135956   int rc;                         /* Return code */
135957   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
135958   int iCell;                      /* Index of iDelete cell in pLeaf */
135959   RtreeNode *pRoot;               /* Root node of rtree structure */
135960
135961
135962   /* Obtain a reference to the root node to initialise Rtree.iDepth */
135963   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
135964
135965   /* Obtain a reference to the leaf node that contains the entry 
135966   ** about to be deleted. 
135967   */
135968   if( rc==SQLITE_OK ){
135969     rc = findLeafNode(pRtree, iDelete, &pLeaf);
135970   }
135971
135972   /* Delete the cell in question from the leaf node. */
135973   if( rc==SQLITE_OK ){
135974     int rc2;
135975     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
135976     if( rc==SQLITE_OK ){
135977       rc = deleteCell(pRtree, pLeaf, iCell, 0);
135978     }
135979     rc2 = nodeRelease(pRtree, pLeaf);
135980     if( rc==SQLITE_OK ){
135981       rc = rc2;
135982     }
135983   }
135984
135985   /* Delete the corresponding entry in the <rtree>_rowid table. */
135986   if( rc==SQLITE_OK ){
135987     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
135988     sqlite3_step(pRtree->pDeleteRowid);
135989     rc = sqlite3_reset(pRtree->pDeleteRowid);
135990   }
135991
135992   /* Check if the root node now has exactly one child. If so, remove
135993   ** it, schedule the contents of the child for reinsertion and 
135994   ** reduce the tree height by one.
135995   **
135996   ** This is equivalent to copying the contents of the child into
135997   ** the root node (the operation that Gutman's paper says to perform 
135998   ** in this scenario).
135999   */
136000   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
136001     int rc2;
136002     RtreeNode *pChild;
136003     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
136004     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
136005     if( rc==SQLITE_OK ){
136006       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
136007     }
136008     rc2 = nodeRelease(pRtree, pChild);
136009     if( rc==SQLITE_OK ) rc = rc2;
136010     if( rc==SQLITE_OK ){
136011       pRtree->iDepth--;
136012       writeInt16(pRoot->zData, pRtree->iDepth);
136013       pRoot->isDirty = 1;
136014     }
136015   }
136016
136017   /* Re-insert the contents of any underfull nodes removed from the tree. */
136018   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
136019     if( rc==SQLITE_OK ){
136020       rc = reinsertNodeContent(pRtree, pLeaf);
136021     }
136022     pRtree->pDeleted = pLeaf->pNext;
136023     sqlite3_free(pLeaf);
136024   }
136025
136026   /* Release the reference to the root node. */
136027   if( rc==SQLITE_OK ){
136028     rc = nodeRelease(pRtree, pRoot);
136029   }else{
136030     nodeRelease(pRtree, pRoot);
136031   }
136032
136033   return rc;
136034 }
136035
136036 /*
136037 ** Rounding constants for float->double conversion.
136038 */
136039 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
136040 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
136041
136042 #if !defined(SQLITE_RTREE_INT_ONLY)
136043 /*
136044 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
136045 ** while taking care to round toward negative or positive, respectively.
136046 */
136047 static RtreeValue rtreeValueDown(sqlite3_value *v){
136048   double d = sqlite3_value_double(v);
136049   float f = (float)d;
136050   if( f>d ){
136051     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
136052   }
136053   return f;
136054 }
136055 static RtreeValue rtreeValueUp(sqlite3_value *v){
136056   double d = sqlite3_value_double(v);
136057   float f = (float)d;
136058   if( f<d ){
136059     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
136060   }
136061   return f;
136062 }
136063 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
136064
136065
136066 /*
136067 ** The xUpdate method for rtree module virtual tables.
136068 */
136069 static int rtreeUpdate(
136070   sqlite3_vtab *pVtab, 
136071   int nData, 
136072   sqlite3_value **azData, 
136073   sqlite_int64 *pRowid
136074 ){
136075   Rtree *pRtree = (Rtree *)pVtab;
136076   int rc = SQLITE_OK;
136077   RtreeCell cell;                 /* New cell to insert if nData>1 */
136078   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
136079
136080   rtreeReference(pRtree);
136081   assert(nData>=1);
136082
136083   /* Constraint handling. A write operation on an r-tree table may return
136084   ** SQLITE_CONSTRAINT for two reasons:
136085   **
136086   **   1. A duplicate rowid value, or
136087   **   2. The supplied data violates the "x2>=x1" constraint.
136088   **
136089   ** In the first case, if the conflict-handling mode is REPLACE, then
136090   ** the conflicting row can be removed before proceeding. In the second
136091   ** case, SQLITE_CONSTRAINT must be returned regardless of the
136092   ** conflict-handling mode specified by the user.
136093   */
136094   if( nData>1 ){
136095     int ii;
136096
136097     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
136098     assert( nData==(pRtree->nDim*2 + 3) );
136099 #ifndef SQLITE_RTREE_INT_ONLY
136100     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136101       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136102         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
136103         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
136104         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
136105           rc = SQLITE_CONSTRAINT;
136106           goto constraint;
136107         }
136108       }
136109     }else
136110 #endif
136111     {
136112       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136113         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
136114         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
136115         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
136116           rc = SQLITE_CONSTRAINT;
136117           goto constraint;
136118         }
136119       }
136120     }
136121
136122     /* If a rowid value was supplied, check if it is already present in 
136123     ** the table. If so, the constraint has failed. */
136124     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
136125       cell.iRowid = sqlite3_value_int64(azData[2]);
136126       if( sqlite3_value_type(azData[0])==SQLITE_NULL
136127        || sqlite3_value_int64(azData[0])!=cell.iRowid
136128       ){
136129         int steprc;
136130         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
136131         steprc = sqlite3_step(pRtree->pReadRowid);
136132         rc = sqlite3_reset(pRtree->pReadRowid);
136133         if( SQLITE_ROW==steprc ){
136134           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
136135             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
136136           }else{
136137             rc = SQLITE_CONSTRAINT;
136138             goto constraint;
136139           }
136140         }
136141       }
136142       bHaveRowid = 1;
136143     }
136144   }
136145
136146   /* If azData[0] is not an SQL NULL value, it is the rowid of a
136147   ** record to delete from the r-tree table. The following block does
136148   ** just that.
136149   */
136150   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
136151     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
136152   }
136153
136154   /* If the azData[] array contains more than one element, elements
136155   ** (azData[2]..azData[argc-1]) contain a new record to insert into
136156   ** the r-tree structure.
136157   */
136158   if( rc==SQLITE_OK && nData>1 ){
136159     /* Insert the new record into the r-tree */
136160     RtreeNode *pLeaf = 0;
136161
136162     /* Figure out the rowid of the new row. */
136163     if( bHaveRowid==0 ){
136164       rc = newRowid(pRtree, &cell.iRowid);
136165     }
136166     *pRowid = cell.iRowid;
136167
136168     if( rc==SQLITE_OK ){
136169       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
136170     }
136171     if( rc==SQLITE_OK ){
136172       int rc2;
136173       pRtree->iReinsertHeight = -1;
136174       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
136175       rc2 = nodeRelease(pRtree, pLeaf);
136176       if( rc==SQLITE_OK ){
136177         rc = rc2;
136178       }
136179     }
136180   }
136181
136182 constraint:
136183   rtreeRelease(pRtree);
136184   return rc;
136185 }
136186
136187 /*
136188 ** The xRename method for rtree module virtual tables.
136189 */
136190 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
136191   Rtree *pRtree = (Rtree *)pVtab;
136192   int rc = SQLITE_NOMEM;
136193   char *zSql = sqlite3_mprintf(
136194     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
136195     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
136196     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
136197     , pRtree->zDb, pRtree->zName, zNewName 
136198     , pRtree->zDb, pRtree->zName, zNewName 
136199     , pRtree->zDb, pRtree->zName, zNewName
136200   );
136201   if( zSql ){
136202     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
136203     sqlite3_free(zSql);
136204   }
136205   return rc;
136206 }
136207
136208 static sqlite3_module rtreeModule = {
136209   0,                          /* iVersion */
136210   rtreeCreate,                /* xCreate - create a table */
136211   rtreeConnect,               /* xConnect - connect to an existing table */
136212   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
136213   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
136214   rtreeDestroy,               /* xDestroy - Drop a table */
136215   rtreeOpen,                  /* xOpen - open a cursor */
136216   rtreeClose,                 /* xClose - close a cursor */
136217   rtreeFilter,                /* xFilter - configure scan constraints */
136218   rtreeNext,                  /* xNext - advance a cursor */
136219   rtreeEof,                   /* xEof */
136220   rtreeColumn,                /* xColumn - read data */
136221   rtreeRowid,                 /* xRowid - read data */
136222   rtreeUpdate,                /* xUpdate - write data */
136223   0,                          /* xBegin - begin transaction */
136224   0,                          /* xSync - sync transaction */
136225   0,                          /* xCommit - commit transaction */
136226   0,                          /* xRollback - rollback transaction */
136227   0,                          /* xFindFunction - function overloading */
136228   rtreeRename,                /* xRename - rename the table */
136229   0,                          /* xSavepoint */
136230   0,                          /* xRelease */
136231   0                           /* xRollbackTo */
136232 };
136233
136234 static int rtreeSqlInit(
136235   Rtree *pRtree, 
136236   sqlite3 *db, 
136237   const char *zDb, 
136238   const char *zPrefix, 
136239   int isCreate
136240 ){
136241   int rc = SQLITE_OK;
136242
136243   #define N_STATEMENT 9
136244   static const char *azSql[N_STATEMENT] = {
136245     /* Read and write the xxx_node table */
136246     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
136247     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
136248     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
136249
136250     /* Read and write the xxx_rowid table */
136251     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
136252     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
136253     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
136254
136255     /* Read and write the xxx_parent table */
136256     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
136257     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
136258     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
136259   };
136260   sqlite3_stmt **appStmt[N_STATEMENT];
136261   int i;
136262
136263   pRtree->db = db;
136264
136265   if( isCreate ){
136266     char *zCreate = sqlite3_mprintf(
136267 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
136268 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
136269 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
136270 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
136271       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
136272     );
136273     if( !zCreate ){
136274       return SQLITE_NOMEM;
136275     }
136276     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
136277     sqlite3_free(zCreate);
136278     if( rc!=SQLITE_OK ){
136279       return rc;
136280     }
136281   }
136282
136283   appStmt[0] = &pRtree->pReadNode;
136284   appStmt[1] = &pRtree->pWriteNode;
136285   appStmt[2] = &pRtree->pDeleteNode;
136286   appStmt[3] = &pRtree->pReadRowid;
136287   appStmt[4] = &pRtree->pWriteRowid;
136288   appStmt[5] = &pRtree->pDeleteRowid;
136289   appStmt[6] = &pRtree->pReadParent;
136290   appStmt[7] = &pRtree->pWriteParent;
136291   appStmt[8] = &pRtree->pDeleteParent;
136292
136293   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
136294     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
136295     if( zSql ){
136296       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
136297     }else{
136298       rc = SQLITE_NOMEM;
136299     }
136300     sqlite3_free(zSql);
136301   }
136302
136303   return rc;
136304 }
136305
136306 /*
136307 ** The second argument to this function contains the text of an SQL statement
136308 ** that returns a single integer value. The statement is compiled and executed
136309 ** using database connection db. If successful, the integer value returned
136310 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
136311 ** code is returned and the value of *piVal after returning is not defined.
136312 */
136313 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
136314   int rc = SQLITE_NOMEM;
136315   if( zSql ){
136316     sqlite3_stmt *pStmt = 0;
136317     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
136318     if( rc==SQLITE_OK ){
136319       if( SQLITE_ROW==sqlite3_step(pStmt) ){
136320         *piVal = sqlite3_column_int(pStmt, 0);
136321       }
136322       rc = sqlite3_finalize(pStmt);
136323     }
136324   }
136325   return rc;
136326 }
136327
136328 /*
136329 ** This function is called from within the xConnect() or xCreate() method to
136330 ** determine the node-size used by the rtree table being created or connected
136331 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
136332 ** Otherwise, an SQLite error code is returned.
136333 **
136334 ** If this function is being called as part of an xConnect(), then the rtree
136335 ** table already exists. In this case the node-size is determined by inspecting
136336 ** the root node of the tree.
136337 **
136338 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
136339 ** This ensures that each node is stored on a single database page. If the 
136340 ** database page-size is so large that more than RTREE_MAXCELLS entries 
136341 ** would fit in a single node, use a smaller node-size.
136342 */
136343 static int getNodeSize(
136344   sqlite3 *db,                    /* Database handle */
136345   Rtree *pRtree,                  /* Rtree handle */
136346   int isCreate                    /* True for xCreate, false for xConnect */
136347 ){
136348   int rc;
136349   char *zSql;
136350   if( isCreate ){
136351     int iPageSize = 0;
136352     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
136353     rc = getIntFromStmt(db, zSql, &iPageSize);
136354     if( rc==SQLITE_OK ){
136355       pRtree->iNodeSize = iPageSize-64;
136356       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
136357         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
136358       }
136359     }
136360   }else{
136361     zSql = sqlite3_mprintf(
136362         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
136363         pRtree->zDb, pRtree->zName
136364     );
136365     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
136366   }
136367
136368   sqlite3_free(zSql);
136369   return rc;
136370 }
136371
136372 /* 
136373 ** This function is the implementation of both the xConnect and xCreate
136374 ** methods of the r-tree virtual table.
136375 **
136376 **   argv[0]   -> module name
136377 **   argv[1]   -> database name
136378 **   argv[2]   -> table name
136379 **   argv[...] -> column names...
136380 */
136381 static int rtreeInit(
136382   sqlite3 *db,                        /* Database connection */
136383   void *pAux,                         /* One of the RTREE_COORD_* constants */
136384   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
136385   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
136386   char **pzErr,                       /* OUT: Error message, if any */
136387   int isCreate                        /* True for xCreate, false for xConnect */
136388 ){
136389   int rc = SQLITE_OK;
136390   Rtree *pRtree;
136391   int nDb;              /* Length of string argv[1] */
136392   int nName;            /* Length of string argv[2] */
136393   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
136394
136395   const char *aErrMsg[] = {
136396     0,                                                    /* 0 */
136397     "Wrong number of columns for an rtree table",         /* 1 */
136398     "Too few columns for an rtree table",                 /* 2 */
136399     "Too many columns for an rtree table"                 /* 3 */
136400   };
136401
136402   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
136403   if( aErrMsg[iErr] ){
136404     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
136405     return SQLITE_ERROR;
136406   }
136407
136408   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
136409
136410   /* Allocate the sqlite3_vtab structure */
136411   nDb = (int)strlen(argv[1]);
136412   nName = (int)strlen(argv[2]);
136413   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
136414   if( !pRtree ){
136415     return SQLITE_NOMEM;
136416   }
136417   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
136418   pRtree->nBusy = 1;
136419   pRtree->base.pModule = &rtreeModule;
136420   pRtree->zDb = (char *)&pRtree[1];
136421   pRtree->zName = &pRtree->zDb[nDb+1];
136422   pRtree->nDim = (argc-4)/2;
136423   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
136424   pRtree->eCoordType = eCoordType;
136425   memcpy(pRtree->zDb, argv[1], nDb);
136426   memcpy(pRtree->zName, argv[2], nName);
136427
136428   /* Figure out the node size to use. */
136429   rc = getNodeSize(db, pRtree, isCreate);
136430
136431   /* Create/Connect to the underlying relational database schema. If
136432   ** that is successful, call sqlite3_declare_vtab() to configure
136433   ** the r-tree table schema.
136434   */
136435   if( rc==SQLITE_OK ){
136436     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
136437       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
136438     }else{
136439       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
136440       char *zTmp;
136441       int ii;
136442       for(ii=4; zSql && ii<argc; ii++){
136443         zTmp = zSql;
136444         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
136445         sqlite3_free(zTmp);
136446       }
136447       if( zSql ){
136448         zTmp = zSql;
136449         zSql = sqlite3_mprintf("%s);", zTmp);
136450         sqlite3_free(zTmp);
136451       }
136452       if( !zSql ){
136453         rc = SQLITE_NOMEM;
136454       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
136455         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
136456       }
136457       sqlite3_free(zSql);
136458     }
136459   }
136460
136461   if( rc==SQLITE_OK ){
136462     *ppVtab = (sqlite3_vtab *)pRtree;
136463   }else{
136464     rtreeRelease(pRtree);
136465   }
136466   return rc;
136467 }
136468
136469
136470 /*
136471 ** Implementation of a scalar function that decodes r-tree nodes to
136472 ** human readable strings. This can be used for debugging and analysis.
136473 **
136474 ** The scalar function takes two arguments, a blob of data containing
136475 ** an r-tree node, and the number of dimensions the r-tree indexes.
136476 ** For a two-dimensional r-tree structure called "rt", to deserialize
136477 ** all nodes, a statement like:
136478 **
136479 **   SELECT rtreenode(2, data) FROM rt_node;
136480 **
136481 ** The human readable string takes the form of a Tcl list with one
136482 ** entry for each cell in the r-tree node. Each entry is itself a
136483 ** list, containing the 8-byte rowid/pageno followed by the 
136484 ** <num-dimension>*2 coordinates.
136485 */
136486 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
136487   char *zText = 0;
136488   RtreeNode node;
136489   Rtree tree;
136490   int ii;
136491
136492   UNUSED_PARAMETER(nArg);
136493   memset(&node, 0, sizeof(RtreeNode));
136494   memset(&tree, 0, sizeof(Rtree));
136495   tree.nDim = sqlite3_value_int(apArg[0]);
136496   tree.nBytesPerCell = 8 + 8 * tree.nDim;
136497   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
136498
136499   for(ii=0; ii<NCELL(&node); ii++){
136500     char zCell[512];
136501     int nCell = 0;
136502     RtreeCell cell;
136503     int jj;
136504
136505     nodeGetCell(&tree, &node, ii, &cell);
136506     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
136507     nCell = (int)strlen(zCell);
136508     for(jj=0; jj<tree.nDim*2; jj++){
136509 #ifndef SQLITE_RTREE_INT_ONLY
136510       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
136511                        (double)cell.aCoord[jj].f);
136512 #else
136513       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
136514                        cell.aCoord[jj].i);
136515 #endif
136516       nCell = (int)strlen(zCell);
136517     }
136518
136519     if( zText ){
136520       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
136521       sqlite3_free(zText);
136522       zText = zTextNew;
136523     }else{
136524       zText = sqlite3_mprintf("{%s}", zCell);
136525     }
136526   }
136527   
136528   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
136529 }
136530
136531 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
136532   UNUSED_PARAMETER(nArg);
136533   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
136534    || sqlite3_value_bytes(apArg[0])<2
136535   ){
136536     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
136537   }else{
136538     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
136539     sqlite3_result_int(ctx, readInt16(zBlob));
136540   }
136541 }
136542
136543 /*
136544 ** Register the r-tree module with database handle db. This creates the
136545 ** virtual table module "rtree" and the debugging/analysis scalar 
136546 ** function "rtreenode".
136547 */
136548 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
136549   const int utf8 = SQLITE_UTF8;
136550   int rc;
136551
136552   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
136553   if( rc==SQLITE_OK ){
136554     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
136555   }
136556   if( rc==SQLITE_OK ){
136557 #ifdef SQLITE_RTREE_INT_ONLY
136558     void *c = (void *)RTREE_COORD_INT32;
136559 #else
136560     void *c = (void *)RTREE_COORD_REAL32;
136561 #endif
136562     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
136563   }
136564   if( rc==SQLITE_OK ){
136565     void *c = (void *)RTREE_COORD_INT32;
136566     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
136567   }
136568
136569   return rc;
136570 }
136571
136572 /*
136573 ** A version of sqlite3_free() that can be used as a callback. This is used
136574 ** in two places - as the destructor for the blob value returned by the
136575 ** invocation of a geometry function, and as the destructor for the geometry
136576 ** functions themselves.
136577 */
136578 static void doSqlite3Free(void *p){
136579   sqlite3_free(p);
136580 }
136581
136582 /*
136583 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
136584 ** scalar user function. This C function is the callback used for all such
136585 ** registered SQL functions.
136586 **
136587 ** The scalar user functions return a blob that is interpreted by r-tree
136588 ** table MATCH operators.
136589 */
136590 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
136591   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
136592   RtreeMatchArg *pBlob;
136593   int nBlob;
136594
136595   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
136596   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
136597   if( !pBlob ){
136598     sqlite3_result_error_nomem(ctx);
136599   }else{
136600     int i;
136601     pBlob->magic = RTREE_GEOMETRY_MAGIC;
136602     pBlob->xGeom = pGeomCtx->xGeom;
136603     pBlob->pContext = pGeomCtx->pContext;
136604     pBlob->nParam = nArg;
136605     for(i=0; i<nArg; i++){
136606 #ifdef SQLITE_RTREE_INT_ONLY
136607       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
136608 #else
136609       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
136610 #endif
136611     }
136612     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
136613   }
136614 }
136615
136616 /*
136617 ** Register a new geometry function for use with the r-tree MATCH operator.
136618 */
136619 SQLITE_API int sqlite3_rtree_geometry_callback(
136620   sqlite3 *db,
136621   const char *zGeom,
136622   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
136623   void *pContext
136624 ){
136625   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
136626
136627   /* Allocate and populate the context object. */
136628   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
136629   if( !pGeomCtx ) return SQLITE_NOMEM;
136630   pGeomCtx->xGeom = xGeom;
136631   pGeomCtx->pContext = pContext;
136632
136633   /* Create the new user-function. Register a destructor function to delete
136634   ** the context object when it is no longer required.  */
136635   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
136636       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
136637   );
136638 }
136639
136640 #if !SQLITE_CORE
136641 SQLITE_API int sqlite3_extension_init(
136642   sqlite3 *db,
136643   char **pzErrMsg,
136644   const sqlite3_api_routines *pApi
136645 ){
136646   SQLITE_EXTENSION_INIT2(pApi)
136647   return sqlite3RtreeInit(db);
136648 }
136649 #endif
136650
136651 #endif
136652
136653 /************** End of rtree.c ***********************************************/
136654 /************** Begin file icu.c *********************************************/
136655 /*
136656 ** 2007 May 6
136657 **
136658 ** The author disclaims copyright to this source code.  In place of
136659 ** a legal notice, here is a blessing:
136660 **
136661 **    May you do good and not evil.
136662 **    May you find forgiveness for yourself and forgive others.
136663 **    May you share freely, never taking more than you give.
136664 **
136665 *************************************************************************
136666 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
136667 **
136668 ** This file implements an integration between the ICU library 
136669 ** ("International Components for Unicode", an open-source library 
136670 ** for handling unicode data) and SQLite. The integration uses 
136671 ** ICU to provide the following to SQLite:
136672 **
136673 **   * An implementation of the SQL regexp() function (and hence REGEXP
136674 **     operator) using the ICU uregex_XX() APIs.
136675 **
136676 **   * Implementations of the SQL scalar upper() and lower() functions
136677 **     for case mapping.
136678 **
136679 **   * Integration of ICU and SQLite collation seqences.
136680 **
136681 **   * An implementation of the LIKE operator that uses ICU to 
136682 **     provide case-independent matching.
136683 */
136684
136685 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
136686
136687 /* Include ICU headers */
136688 #include <unicode/utypes.h>
136689 #include <unicode/uregex.h>
136690 #include <unicode/ustring.h>
136691 #include <unicode/ucol.h>
136692
136693 /* #include <assert.h> */
136694
136695 #ifndef SQLITE_CORE
136696   SQLITE_EXTENSION_INIT1
136697 #else
136698 #endif
136699
136700 /*
136701 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
136702 ** operator.
136703 */
136704 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
136705 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
136706 #endif
136707
136708 /*
136709 ** Version of sqlite3_free() that is always a function, never a macro.
136710 */
136711 static void xFree(void *p){
136712   sqlite3_free(p);
136713 }
136714
136715 /*
136716 ** Compare two UTF-8 strings for equality where the first string is
136717 ** a "LIKE" expression. Return true (1) if they are the same and 
136718 ** false (0) if they are different.
136719 */
136720 static int icuLikeCompare(
136721   const uint8_t *zPattern,   /* LIKE pattern */
136722   const uint8_t *zString,    /* The UTF-8 string to compare against */
136723   const UChar32 uEsc         /* The escape character */
136724 ){
136725   static const int MATCH_ONE = (UChar32)'_';
136726   static const int MATCH_ALL = (UChar32)'%';
136727
136728   int iPattern = 0;       /* Current byte index in zPattern */
136729   int iString = 0;        /* Current byte index in zString */
136730
136731   int prevEscape = 0;     /* True if the previous character was uEsc */
136732
136733   while( zPattern[iPattern]!=0 ){
136734
136735     /* Read (and consume) the next character from the input pattern. */
136736     UChar32 uPattern;
136737     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
136738     assert(uPattern!=0);
136739
136740     /* There are now 4 possibilities:
136741     **
136742     **     1. uPattern is an unescaped match-all character "%",
136743     **     2. uPattern is an unescaped match-one character "_",
136744     **     3. uPattern is an unescaped escape character, or
136745     **     4. uPattern is to be handled as an ordinary character
136746     */
136747     if( !prevEscape && uPattern==MATCH_ALL ){
136748       /* Case 1. */
136749       uint8_t c;
136750
136751       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
136752       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
136753       ** test string.
136754       */
136755       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
136756         if( c==MATCH_ONE ){
136757           if( zString[iString]==0 ) return 0;
136758           U8_FWD_1_UNSAFE(zString, iString);
136759         }
136760         iPattern++;
136761       }
136762
136763       if( zPattern[iPattern]==0 ) return 1;
136764
136765       while( zString[iString] ){
136766         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
136767           return 1;
136768         }
136769         U8_FWD_1_UNSAFE(zString, iString);
136770       }
136771       return 0;
136772
136773     }else if( !prevEscape && uPattern==MATCH_ONE ){
136774       /* Case 2. */
136775       if( zString[iString]==0 ) return 0;
136776       U8_FWD_1_UNSAFE(zString, iString);
136777
136778     }else if( !prevEscape && uPattern==uEsc){
136779       /* Case 3. */
136780       prevEscape = 1;
136781
136782     }else{
136783       /* Case 4. */
136784       UChar32 uString;
136785       U8_NEXT_UNSAFE(zString, iString, uString);
136786       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
136787       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
136788       if( uString!=uPattern ){
136789         return 0;
136790       }
136791       prevEscape = 0;
136792     }
136793   }
136794
136795   return zString[iString]==0;
136796 }
136797
136798 /*
136799 ** Implementation of the like() SQL function.  This function implements
136800 ** the build-in LIKE operator.  The first argument to the function is the
136801 ** pattern and the second argument is the string.  So, the SQL statements:
136802 **
136803 **       A LIKE B
136804 **
136805 ** is implemented as like(B, A). If there is an escape character E, 
136806 **
136807 **       A LIKE B ESCAPE E
136808 **
136809 ** is mapped to like(B, A, E).
136810 */
136811 static void icuLikeFunc(
136812   sqlite3_context *context, 
136813   int argc, 
136814   sqlite3_value **argv
136815 ){
136816   const unsigned char *zA = sqlite3_value_text(argv[0]);
136817   const unsigned char *zB = sqlite3_value_text(argv[1]);
136818   UChar32 uEsc = 0;
136819
136820   /* Limit the length of the LIKE or GLOB pattern to avoid problems
136821   ** of deep recursion and N*N behavior in patternCompare().
136822   */
136823   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
136824     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
136825     return;
136826   }
136827
136828
136829   if( argc==3 ){
136830     /* The escape character string must consist of a single UTF-8 character.
136831     ** Otherwise, return an error.
136832     */
136833     int nE= sqlite3_value_bytes(argv[2]);
136834     const unsigned char *zE = sqlite3_value_text(argv[2]);
136835     int i = 0;
136836     if( zE==0 ) return;
136837     U8_NEXT(zE, i, nE, uEsc);
136838     if( i!=nE){
136839       sqlite3_result_error(context, 
136840           "ESCAPE expression must be a single character", -1);
136841       return;
136842     }
136843   }
136844
136845   if( zA && zB ){
136846     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
136847   }
136848 }
136849
136850 /*
136851 ** This function is called when an ICU function called from within
136852 ** the implementation of an SQL scalar function returns an error.
136853 **
136854 ** The scalar function context passed as the first argument is 
136855 ** loaded with an error message based on the following two args.
136856 */
136857 static void icuFunctionError(
136858   sqlite3_context *pCtx,       /* SQLite scalar function context */
136859   const char *zName,           /* Name of ICU function that failed */
136860   UErrorCode e                 /* Error code returned by ICU function */
136861 ){
136862   char zBuf[128];
136863   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
136864   zBuf[127] = '\0';
136865   sqlite3_result_error(pCtx, zBuf, -1);
136866 }
136867
136868 /*
136869 ** Function to delete compiled regexp objects. Registered as
136870 ** a destructor function with sqlite3_set_auxdata().
136871 */
136872 static void icuRegexpDelete(void *p){
136873   URegularExpression *pExpr = (URegularExpression *)p;
136874   uregex_close(pExpr);
136875 }
136876
136877 /*
136878 ** Implementation of SQLite REGEXP operator. This scalar function takes
136879 ** two arguments. The first is a regular expression pattern to compile
136880 ** the second is a string to match against that pattern. If either 
136881 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
136882 ** is 1 if the string matches the pattern, or 0 otherwise.
136883 **
136884 ** SQLite maps the regexp() function to the regexp() operator such
136885 ** that the following two are equivalent:
136886 **
136887 **     zString REGEXP zPattern
136888 **     regexp(zPattern, zString)
136889 **
136890 ** Uses the following ICU regexp APIs:
136891 **
136892 **     uregex_open()
136893 **     uregex_matches()
136894 **     uregex_close()
136895 */
136896 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
136897   UErrorCode status = U_ZERO_ERROR;
136898   URegularExpression *pExpr;
136899   UBool res;
136900   const UChar *zString = sqlite3_value_text16(apArg[1]);
136901
136902   (void)nArg;  /* Unused parameter */
136903
136904   /* If the left hand side of the regexp operator is NULL, 
136905   ** then the result is also NULL. 
136906   */
136907   if( !zString ){
136908     return;
136909   }
136910
136911   pExpr = sqlite3_get_auxdata(p, 0);
136912   if( !pExpr ){
136913     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
136914     if( !zPattern ){
136915       return;
136916     }
136917     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
136918
136919     if( U_SUCCESS(status) ){
136920       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
136921     }else{
136922       assert(!pExpr);
136923       icuFunctionError(p, "uregex_open", status);
136924       return;
136925     }
136926   }
136927
136928   /* Configure the text that the regular expression operates on. */
136929   uregex_setText(pExpr, zString, -1, &status);
136930   if( !U_SUCCESS(status) ){
136931     icuFunctionError(p, "uregex_setText", status);
136932     return;
136933   }
136934
136935   /* Attempt the match */
136936   res = uregex_matches(pExpr, 0, &status);
136937   if( !U_SUCCESS(status) ){
136938     icuFunctionError(p, "uregex_matches", status);
136939     return;
136940   }
136941
136942   /* Set the text that the regular expression operates on to a NULL
136943   ** pointer. This is not really necessary, but it is tidier than 
136944   ** leaving the regular expression object configured with an invalid
136945   ** pointer after this function returns.
136946   */
136947   uregex_setText(pExpr, 0, 0, &status);
136948
136949   /* Return 1 or 0. */
136950   sqlite3_result_int(p, res ? 1 : 0);
136951 }
136952
136953 /*
136954 ** Implementations of scalar functions for case mapping - upper() and 
136955 ** lower(). Function upper() converts its input to upper-case (ABC).
136956 ** Function lower() converts to lower-case (abc).
136957 **
136958 ** ICU provides two types of case mapping, "general" case mapping and
136959 ** "language specific". Refer to ICU documentation for the differences
136960 ** between the two.
136961 **
136962 ** To utilise "general" case mapping, the upper() or lower() scalar 
136963 ** functions are invoked with one argument:
136964 **
136965 **     upper('ABC') -> 'abc'
136966 **     lower('abc') -> 'ABC'
136967 **
136968 ** To access ICU "language specific" case mapping, upper() or lower()
136969 ** should be invoked with two arguments. The second argument is the name
136970 ** of the locale to use. Passing an empty string ("") or SQL NULL value
136971 ** as the second argument is the same as invoking the 1 argument version
136972 ** of upper() or lower().
136973 **
136974 **     lower('I', 'en_us') -> 'i'
136975 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
136976 **
136977 ** http://www.icu-project.org/userguide/posix.html#case_mappings
136978 */
136979 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
136980   const UChar *zInput;
136981   UChar *zOutput;
136982   int nInput;
136983   int nOutput;
136984
136985   UErrorCode status = U_ZERO_ERROR;
136986   const char *zLocale = 0;
136987
136988   assert(nArg==1 || nArg==2);
136989   if( nArg==2 ){
136990     zLocale = (const char *)sqlite3_value_text(apArg[1]);
136991   }
136992
136993   zInput = sqlite3_value_text16(apArg[0]);
136994   if( !zInput ){
136995     return;
136996   }
136997   nInput = sqlite3_value_bytes16(apArg[0]);
136998
136999   nOutput = nInput * 2 + 2;
137000   zOutput = sqlite3_malloc(nOutput);
137001   if( !zOutput ){
137002     return;
137003   }
137004
137005   if( sqlite3_user_data(p) ){
137006     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137007   }else{
137008     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137009   }
137010
137011   if( !U_SUCCESS(status) ){
137012     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
137013     return;
137014   }
137015
137016   sqlite3_result_text16(p, zOutput, -1, xFree);
137017 }
137018
137019 /*
137020 ** Collation sequence destructor function. The pCtx argument points to
137021 ** a UCollator structure previously allocated using ucol_open().
137022 */
137023 static void icuCollationDel(void *pCtx){
137024   UCollator *p = (UCollator *)pCtx;
137025   ucol_close(p);
137026 }
137027
137028 /*
137029 ** Collation sequence comparison function. The pCtx argument points to
137030 ** a UCollator structure previously allocated using ucol_open().
137031 */
137032 static int icuCollationColl(
137033   void *pCtx,
137034   int nLeft,
137035   const void *zLeft,
137036   int nRight,
137037   const void *zRight
137038 ){
137039   UCollationResult res;
137040   UCollator *p = (UCollator *)pCtx;
137041   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
137042   switch( res ){
137043     case UCOL_LESS:    return -1;
137044     case UCOL_GREATER: return +1;
137045     case UCOL_EQUAL:   return 0;
137046   }
137047   assert(!"Unexpected return value from ucol_strcoll()");
137048   return 0;
137049 }
137050
137051 /*
137052 ** Implementation of the scalar function icu_load_collation().
137053 **
137054 ** This scalar function is used to add ICU collation based collation 
137055 ** types to an SQLite database connection. It is intended to be called
137056 ** as follows:
137057 **
137058 **     SELECT icu_load_collation(<locale>, <collation-name>);
137059 **
137060 ** Where <locale> is a string containing an ICU locale identifier (i.e.
137061 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
137062 ** collation sequence to create.
137063 */
137064 static void icuLoadCollation(
137065   sqlite3_context *p, 
137066   int nArg, 
137067   sqlite3_value **apArg
137068 ){
137069   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
137070   UErrorCode status = U_ZERO_ERROR;
137071   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
137072   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
137073   UCollator *pUCollator;    /* ICU library collation object */
137074   int rc;                   /* Return code from sqlite3_create_collation_x() */
137075
137076   assert(nArg==2);
137077   zLocale = (const char *)sqlite3_value_text(apArg[0]);
137078   zName = (const char *)sqlite3_value_text(apArg[1]);
137079
137080   if( !zLocale || !zName ){
137081     return;
137082   }
137083
137084   pUCollator = ucol_open(zLocale, &status);
137085   if( !U_SUCCESS(status) ){
137086     icuFunctionError(p, "ucol_open", status);
137087     return;
137088   }
137089   assert(p);
137090
137091   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
137092       icuCollationColl, icuCollationDel
137093   );
137094   if( rc!=SQLITE_OK ){
137095     ucol_close(pUCollator);
137096     sqlite3_result_error(p, "Error registering collation function", -1);
137097   }
137098 }
137099
137100 /*
137101 ** Register the ICU extension functions with database db.
137102 */
137103 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
137104   struct IcuScalar {
137105     const char *zName;                        /* Function name */
137106     int nArg;                                 /* Number of arguments */
137107     int enc;                                  /* Optimal text encoding */
137108     void *pContext;                           /* sqlite3_user_data() context */
137109     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
137110   } scalars[] = {
137111     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
137112
137113     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
137114     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
137115     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137116     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137117
137118     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
137119     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
137120     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137121     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137122
137123     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
137124     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
137125
137126     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
137127   };
137128
137129   int rc = SQLITE_OK;
137130   int i;
137131
137132   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
137133     struct IcuScalar *p = &scalars[i];
137134     rc = sqlite3_create_function(
137135         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
137136     );
137137   }
137138
137139   return rc;
137140 }
137141
137142 #if !SQLITE_CORE
137143 SQLITE_API int sqlite3_extension_init(
137144   sqlite3 *db, 
137145   char **pzErrMsg,
137146   const sqlite3_api_routines *pApi
137147 ){
137148   SQLITE_EXTENSION_INIT2(pApi)
137149   return sqlite3IcuInit(db);
137150 }
137151 #endif
137152
137153 #endif
137154
137155 /************** End of icu.c *************************************************/
137156 /************** Begin file fts3_icu.c ****************************************/
137157 /*
137158 ** 2007 June 22
137159 **
137160 ** The author disclaims copyright to this source code.  In place of
137161 ** a legal notice, here is a blessing:
137162 **
137163 **    May you do good and not evil.
137164 **    May you find forgiveness for yourself and forgive others.
137165 **    May you share freely, never taking more than you give.
137166 **
137167 *************************************************************************
137168 ** This file implements a tokenizer for fts3 based on the ICU library.
137169 */
137170 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137171 #ifdef SQLITE_ENABLE_ICU
137172
137173 /* #include <assert.h> */
137174 /* #include <string.h> */
137175
137176 #include <unicode/ubrk.h>
137177 /* #include <unicode/ucol.h> */
137178 /* #include <unicode/ustring.h> */
137179 #include <unicode/utf16.h>
137180
137181 typedef struct IcuTokenizer IcuTokenizer;
137182 typedef struct IcuCursor IcuCursor;
137183
137184 struct IcuTokenizer {
137185   sqlite3_tokenizer base;
137186   char *zLocale;
137187 };
137188
137189 struct IcuCursor {
137190   sqlite3_tokenizer_cursor base;
137191
137192   UBreakIterator *pIter;      /* ICU break-iterator object */
137193   int nChar;                  /* Number of UChar elements in pInput */
137194   UChar *aChar;               /* Copy of input using utf-16 encoding */
137195   int *aOffset;               /* Offsets of each character in utf-8 input */
137196
137197   int nBuffer;
137198   char *zBuffer;
137199
137200   int iToken;
137201 };
137202
137203 /*
137204 ** Create a new tokenizer instance.
137205 */
137206 static int icuCreate(
137207   int argc,                            /* Number of entries in argv[] */
137208   const char * const *argv,            /* Tokenizer creation arguments */
137209   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
137210 ){
137211   IcuTokenizer *p;
137212   int n = 0;
137213
137214   if( argc>0 ){
137215     n = strlen(argv[0])+1;
137216   }
137217   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
137218   if( !p ){
137219     return SQLITE_NOMEM;
137220   }
137221   memset(p, 0, sizeof(IcuTokenizer));
137222
137223   if( n ){
137224     p->zLocale = (char *)&p[1];
137225     memcpy(p->zLocale, argv[0], n);
137226   }
137227
137228   *ppTokenizer = (sqlite3_tokenizer *)p;
137229
137230   return SQLITE_OK;
137231 }
137232
137233 /*
137234 ** Destroy a tokenizer
137235 */
137236 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
137237   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137238   sqlite3_free(p);
137239   return SQLITE_OK;
137240 }
137241
137242 /*
137243 ** Prepare to begin tokenizing a particular string.  The input
137244 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
137245 ** used to incrementally tokenize this string is returned in 
137246 ** *ppCursor.
137247 */
137248 static int icuOpen(
137249   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
137250   const char *zInput,                    /* Input string */
137251   int nInput,                            /* Length of zInput in bytes */
137252   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
137253 ){
137254   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137255   IcuCursor *pCsr;
137256
137257   const int32_t opt = U_FOLD_CASE_DEFAULT;
137258   UErrorCode status = U_ZERO_ERROR;
137259   int nChar;
137260
137261   UChar32 c;
137262   int iInput = 0;
137263   int iOut = 0;
137264
137265   *ppCursor = 0;
137266
137267   if( zInput==0 ){
137268     nInput = 0;
137269     zInput = "";
137270   }else if( nInput<0 ){
137271     nInput = strlen(zInput);
137272   }
137273   nChar = nInput+1;
137274   pCsr = (IcuCursor *)sqlite3_malloc(
137275       sizeof(IcuCursor) +                /* IcuCursor */
137276       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
137277       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
137278   );
137279   if( !pCsr ){
137280     return SQLITE_NOMEM;
137281   }
137282   memset(pCsr, 0, sizeof(IcuCursor));
137283   pCsr->aChar = (UChar *)&pCsr[1];
137284   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
137285
137286   pCsr->aOffset[iOut] = iInput;
137287   U8_NEXT(zInput, iInput, nInput, c); 
137288   while( c>0 ){
137289     int isError = 0;
137290     c = u_foldCase(c, opt);
137291     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
137292     if( isError ){
137293       sqlite3_free(pCsr);
137294       return SQLITE_ERROR;
137295     }
137296     pCsr->aOffset[iOut] = iInput;
137297
137298     if( iInput<nInput ){
137299       U8_NEXT(zInput, iInput, nInput, c);
137300     }else{
137301       c = 0;
137302     }
137303   }
137304
137305   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
137306   if( !U_SUCCESS(status) ){
137307     sqlite3_free(pCsr);
137308     return SQLITE_ERROR;
137309   }
137310   pCsr->nChar = iOut;
137311
137312   ubrk_first(pCsr->pIter);
137313   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
137314   return SQLITE_OK;
137315 }
137316
137317 /*
137318 ** Close a tokenization cursor previously opened by a call to icuOpen().
137319 */
137320 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
137321   IcuCursor *pCsr = (IcuCursor *)pCursor;
137322   ubrk_close(pCsr->pIter);
137323   sqlite3_free(pCsr->zBuffer);
137324   sqlite3_free(pCsr);
137325   return SQLITE_OK;
137326 }
137327
137328 /*
137329 ** Extract the next token from a tokenization cursor.
137330 */
137331 static int icuNext(
137332   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
137333   const char **ppToken,               /* OUT: *ppToken is the token text */
137334   int *pnBytes,                       /* OUT: Number of bytes in token */
137335   int *piStartOffset,                 /* OUT: Starting offset of token */
137336   int *piEndOffset,                   /* OUT: Ending offset of token */
137337   int *piPosition                     /* OUT: Position integer of token */
137338 ){
137339   IcuCursor *pCsr = (IcuCursor *)pCursor;
137340
137341   int iStart = 0;
137342   int iEnd = 0;
137343   int nByte = 0;
137344
137345   while( iStart==iEnd ){
137346     UChar32 c;
137347
137348     iStart = ubrk_current(pCsr->pIter);
137349     iEnd = ubrk_next(pCsr->pIter);
137350     if( iEnd==UBRK_DONE ){
137351       return SQLITE_DONE;
137352     }
137353
137354     while( iStart<iEnd ){
137355       int iWhite = iStart;
137356       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
137357       if( u_isspace(c) ){
137358         iStart = iWhite;
137359       }else{
137360         break;
137361       }
137362     }
137363     assert(iStart<=iEnd);
137364   }
137365
137366   do {
137367     UErrorCode status = U_ZERO_ERROR;
137368     if( nByte ){
137369       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
137370       if( !zNew ){
137371         return SQLITE_NOMEM;
137372       }
137373       pCsr->zBuffer = zNew;
137374       pCsr->nBuffer = nByte;
137375     }
137376
137377     u_strToUTF8(
137378         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
137379         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
137380         &status                                  /* Output success/failure */
137381     );
137382   } while( nByte>pCsr->nBuffer );
137383
137384   *ppToken = pCsr->zBuffer;
137385   *pnBytes = nByte;
137386   *piStartOffset = pCsr->aOffset[iStart];
137387   *piEndOffset = pCsr->aOffset[iEnd];
137388   *piPosition = pCsr->iToken++;
137389
137390   return SQLITE_OK;
137391 }
137392
137393 /*
137394 ** The set of routines that implement the simple tokenizer
137395 */
137396 static const sqlite3_tokenizer_module icuTokenizerModule = {
137397   0,                           /* iVersion */
137398   icuCreate,                   /* xCreate  */
137399   icuDestroy,                  /* xCreate  */
137400   icuOpen,                     /* xOpen    */
137401   icuClose,                    /* xClose   */
137402   icuNext,                     /* xNext    */
137403 };
137404
137405 /*
137406 ** Set *ppModule to point at the implementation of the ICU tokenizer.
137407 */
137408 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
137409   sqlite3_tokenizer_module const**ppModule
137410 ){
137411   *ppModule = &icuTokenizerModule;
137412 }
137413
137414 #endif /* defined(SQLITE_ENABLE_ICU) */
137415 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
137416
137417 /************** End of fts3_icu.c ********************************************/